xref: /llvm-project/bolt/runtime/instr.cpp (revision 4314f4ceb5c8a95835b50d3b93f82e0f11f587f1)
12f09f445SMaksim Panchenko //===- bolt/runtime/instr.cpp ---------------------------------------------===//
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 
43cb8d701bSVladislav Khmelevsky #if defined (__x86_64__)
449bd71615SXun Li #include "common.h"
4562aa74f8SRafael Auler 
4616a497c6SRafael Auler // Enables a very verbose logging to stderr useful when debugging
47cc4b2fb6SRafael Auler //#define ENABLE_DEBUG
48cc4b2fb6SRafael Auler 
49cc4b2fb6SRafael Auler #ifdef ENABLE_DEBUG
50cc4b2fb6SRafael Auler #define DEBUG(X)                                                               \
51cc4b2fb6SRafael Auler   { X; }
52cc4b2fb6SRafael Auler #else
53cc4b2fb6SRafael Auler #define DEBUG(X)                                                               \
54cc4b2fb6SRafael Auler   {}
55cc4b2fb6SRafael Auler #endif
56cc4b2fb6SRafael Auler 
57af58da4eSVladislav Khmelevsky #pragma GCC visibility push(hidden)
583b876cc3SAlexander Shaposhnikov 
593b876cc3SAlexander Shaposhnikov extern "C" {
60553f28e9SVladislav Khmelevsky 
61553f28e9SVladislav Khmelevsky #if defined(__APPLE__)
623b876cc3SAlexander Shaposhnikov extern uint64_t* _bolt_instr_locations_getter();
633b876cc3SAlexander Shaposhnikov extern uint32_t _bolt_num_counters_getter();
643b876cc3SAlexander Shaposhnikov 
65a0dd5b05SAlexander Shaposhnikov extern uint8_t* _bolt_instr_tables_getter();
66a0dd5b05SAlexander Shaposhnikov extern uint32_t _bolt_instr_num_funcs_getter();
673b876cc3SAlexander Shaposhnikov 
683b876cc3SAlexander Shaposhnikov #else
69bbd9d610SAlexander Shaposhnikov 
7016a497c6SRafael Auler // Main counters inserted by instrumentation, incremented during runtime when
7116a497c6SRafael Auler // points of interest (locations) in the program are reached. Those are direct
7216a497c6SRafael Auler // calls and direct and indirect branches (local ones). There are also counters
7316a497c6SRafael Auler // for basic block execution if they are a spanning tree leaf and need to be
7416a497c6SRafael Auler // counted in order to infer the execution count of other edges of the CFG.
7562aa74f8SRafael Auler extern uint64_t __bolt_instr_locations[];
7616a497c6SRafael Auler extern uint32_t __bolt_num_counters;
7716a497c6SRafael Auler // Descriptions are serialized metadata about binary functions written by BOLT,
7816a497c6SRafael Auler // so we have a minimal understanding about the program structure. For a
7916a497c6SRafael Auler // reference on the exact format of this metadata, see *Description structs,
8016a497c6SRafael Auler // Location, IntrumentedNode and EntryNode.
8116a497c6SRafael Auler // Number of indirect call site descriptions
8216a497c6SRafael Auler extern uint32_t __bolt_instr_num_ind_calls;
8316a497c6SRafael Auler // Number of indirect call target descriptions
8416a497c6SRafael Auler extern uint32_t __bolt_instr_num_ind_targets;
85cc4b2fb6SRafael Auler // Number of function descriptions
86cc4b2fb6SRafael Auler extern uint32_t __bolt_instr_num_funcs;
8716a497c6SRafael Auler // Time to sleep across dumps (when we write the fdata profile to disk)
8816a497c6SRafael Auler extern uint32_t __bolt_instr_sleep_time;
8976d346caSVladislav Khmelevsky // Do not clear counters across dumps, rewrite file with the updated values
9076d346caSVladislav Khmelevsky extern bool __bolt_instr_no_counters_clear;
9176d346caSVladislav Khmelevsky // Wait until all forks of instrumented process will finish
9276d346caSVladislav Khmelevsky extern bool __bolt_instr_wait_forks;
93cc4b2fb6SRafael Auler // Filename to dump data to
9462aa74f8SRafael Auler extern char __bolt_instr_filename[];
95519cbbaaSVasily Leonenko // Instumented binary file path
96519cbbaaSVasily Leonenko extern char __bolt_instr_binpath[];
9716a497c6SRafael Auler // If true, append current PID to the fdata filename when creating it so
9816a497c6SRafael Auler // different invocations of the same program can be differentiated.
9916a497c6SRafael Auler extern bool __bolt_instr_use_pid;
10016a497c6SRafael Auler // Functions that will be used to instrument indirect calls. BOLT static pass
10116a497c6SRafael Auler // will identify indirect calls and modify them to load the address in these
10216a497c6SRafael Auler // trampolines and call this address instead. BOLT can't use direct calls to
10316a497c6SRafael Auler // our handlers because our addresses here are not known at analysis time. We
10416a497c6SRafael Auler // only support resolving dependencies from this file to the output of BOLT,
10516a497c6SRafael Auler // *not* the other way around.
10616a497c6SRafael Auler // TODO: We need better linking support to make that happen.
107361f3b55SVladislav Khmelevsky extern void (*__bolt_ind_call_counter_func_pointer)();
108361f3b55SVladislav Khmelevsky extern void (*__bolt_ind_tailcall_counter_func_pointer)();
109ad79d517SVasily Leonenko // Function pointers to init/fini trampoline routines in the binary, so we can
110ad79d517SVasily Leonenko // resume regular execution of these functions that we hooked
111553f28e9SVladislav Khmelevsky extern void __bolt_start_trampoline();
112553f28e9SVladislav Khmelevsky extern void __bolt_fini_trampoline();
11362aa74f8SRafael Auler 
114a0dd5b05SAlexander Shaposhnikov #endif
115553f28e9SVladislav Khmelevsky }
116a0dd5b05SAlexander Shaposhnikov 
117cc4b2fb6SRafael Auler namespace {
118cc4b2fb6SRafael Auler 
119cc4b2fb6SRafael Auler /// A simple allocator that mmaps a fixed size region and manages this space
120cc4b2fb6SRafael Auler /// in a stack fashion, meaning you always deallocate the last element that
12116a497c6SRafael Auler /// was allocated. In practice, we don't need to deallocate individual elements.
12216a497c6SRafael Auler /// We monotonically increase our usage and then deallocate everything once we
12316a497c6SRafael Auler /// are done processing something.
124cc4b2fb6SRafael Auler class BumpPtrAllocator {
12516a497c6SRafael Auler   /// This is written before each allocation and act as a canary to detect when
12616a497c6SRafael Auler   /// a bug caused our program to cross allocation boundaries.
127cc4b2fb6SRafael Auler   struct EntryMetadata {
128cc4b2fb6SRafael Auler     uint64_t Magic;
129cc4b2fb6SRafael Auler     uint64_t AllocSize;
130cc4b2fb6SRafael Auler   };
1319bd71615SXun Li 
132cc4b2fb6SRafael Auler public:
133faaefff6SAlexander Shaposhnikov   void *allocate(size_t Size) {
13416a497c6SRafael Auler     Lock L(M);
135a0dd5b05SAlexander Shaposhnikov 
136cc4b2fb6SRafael Auler     if (StackBase == nullptr) {
13716a497c6SRafael Auler       StackBase = reinterpret_cast<uint8_t *>(
138f0b45fbaSDenis Revunov           __mmap(0, MaxSize, PROT_READ | PROT_WRITE,
139f0b45fbaSDenis Revunov                  (Shared ? MAP_SHARED : MAP_PRIVATE) | MAP_ANONYMOUS, -1, 0));
1408f7c53efSDenis Revunov       assert(StackBase != MAP_FAILED,
1418f7c53efSDenis Revunov              "BumpPtrAllocator: failed to mmap stack!");
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.
213*4314f4ceSAmir Ayupov 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));
222ea2182feSMaksim Panchenko   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));
230ea2182feSMaksim Panchenko   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 
2399aa134dcSVasily Leonenko // Disable instrumentation optimizations that sacrifice profile accuracy
2409aa134dcSVasily Leonenko extern "C" bool __bolt_instr_conservative;
2419aa134dcSVasily Leonenko 
24216a497c6SRafael Auler /// Basic key-val atom stored in our hash
24316a497c6SRafael Auler struct SimpleHashTableEntryBase {
24416a497c6SRafael Auler   uint64_t Key;
24516a497c6SRafael Auler   uint64_t Val;
24647934c11SDenis Revunov   void dump(const char *Msg = nullptr) {
24747934c11SDenis Revunov     // TODO: make some sort of formatting function
24847934c11SDenis Revunov     // Currently we have to do it the ugly way because
24947934c11SDenis Revunov     // we want every message to be printed atomically via a single call to
25047934c11SDenis Revunov     // __write. If we use reportNumber() and others nultiple times, we'll get
25147934c11SDenis Revunov     // garbage in mulithreaded environment
25247934c11SDenis Revunov     char Buf[BufSize];
25347934c11SDenis Revunov     char *Ptr = Buf;
25447934c11SDenis Revunov     Ptr = intToStr(Ptr, __getpid(), 10);
25547934c11SDenis Revunov     *Ptr++ = ':';
25647934c11SDenis Revunov     *Ptr++ = ' ';
25747934c11SDenis Revunov     if (Msg)
25847934c11SDenis Revunov       Ptr = strCopy(Ptr, Msg, strLen(Msg));
25947934c11SDenis Revunov     *Ptr++ = '0';
26047934c11SDenis Revunov     *Ptr++ = 'x';
26147934c11SDenis Revunov     Ptr = intToStr(Ptr, (uint64_t)this, 16);
26247934c11SDenis Revunov     *Ptr++ = ':';
26347934c11SDenis Revunov     *Ptr++ = ' ';
26447934c11SDenis Revunov     Ptr = strCopy(Ptr, "MapEntry(0x", sizeof("MapEntry(0x") - 1);
26547934c11SDenis Revunov     Ptr = intToStr(Ptr, Key, 16);
26647934c11SDenis Revunov     *Ptr++ = ',';
26747934c11SDenis Revunov     *Ptr++ = ' ';
26847934c11SDenis Revunov     *Ptr++ = '0';
26947934c11SDenis Revunov     *Ptr++ = 'x';
27047934c11SDenis Revunov     Ptr = intToStr(Ptr, Val, 16);
27147934c11SDenis Revunov     *Ptr++ = ')';
27247934c11SDenis Revunov     *Ptr++ = '\n';
27347934c11SDenis Revunov     assert(Ptr - Buf < BufSize, "Buffer overflow!");
27447934c11SDenis Revunov     // print everything all at once for atomicity
27547934c11SDenis Revunov     __write(2, Buf, Ptr - Buf);
27647934c11SDenis Revunov   }
27716a497c6SRafael Auler };
27816a497c6SRafael Auler 
27916a497c6SRafael Auler /// This hash table implementation starts by allocating a table of size
28016a497c6SRafael Auler /// InitialSize. When conflicts happen in this main table, it resolves
28116a497c6SRafael Auler /// them by chaining a new table of size IncSize. It never reallocs as our
28216a497c6SRafael Auler /// allocator doesn't support it. The key is intended to be function pointers.
28316a497c6SRafael Auler /// There's no clever hash function (it's just x mod size, size being prime).
28416a497c6SRafael Auler /// I never tuned the coefficientes in the modular equation (TODO)
28516a497c6SRafael Auler /// This is used for indirect calls (each call site has one of this, so it
28616a497c6SRafael Auler /// should have a small footprint) and for tallying call counts globally for
28716a497c6SRafael Auler /// each target to check if we missed the origin of some calls (this one is a
28816a497c6SRafael Auler /// large instantiation of this template, since it is global for all call sites)
28916a497c6SRafael Auler template <typename T = SimpleHashTableEntryBase, uint32_t InitialSize = 7,
29016a497c6SRafael Auler           uint32_t IncSize = 7>
29116a497c6SRafael Auler class SimpleHashTable {
29216a497c6SRafael Auler public:
29316a497c6SRafael Auler   using MapEntry = T;
29416a497c6SRafael Auler 
29516a497c6SRafael Auler   /// Increment by 1 the value of \p Key. If it is not in this table, it will be
29616a497c6SRafael Auler   /// added to the table and its value set to 1.
29716a497c6SRafael Auler   void incrementVal(uint64_t Key, BumpPtrAllocator &Alloc) {
298*4314f4ceSAmir Ayupov     ++get(Key, Alloc).Val;
29916a497c6SRafael Auler   }
30016a497c6SRafael Auler 
30116a497c6SRafael Auler   /// Basic member accessing interface. Here we pass the allocator explicitly to
30216a497c6SRafael Auler   /// avoid storing a pointer to it as part of this table (remember there is one
30316a497c6SRafael Auler   /// hash for each indirect call site, so we wan't to minimize our footprint).
30416a497c6SRafael Auler   MapEntry &get(uint64_t Key, BumpPtrAllocator &Alloc) {
3059aa134dcSVasily Leonenko     if (!__bolt_instr_conservative) {
3069aa134dcSVasily Leonenko       TryLock L(M);
3079aa134dcSVasily Leonenko       if (!L.isLocked())
3089aa134dcSVasily Leonenko         return NoEntry;
3099aa134dcSVasily Leonenko       return getOrAllocEntry(Key, Alloc);
3109aa134dcSVasily Leonenko     }
31116a497c6SRafael Auler     Lock L(M);
3129aa134dcSVasily Leonenko     return getOrAllocEntry(Key, Alloc);
31316a497c6SRafael Auler   }
31416a497c6SRafael Auler 
31516a497c6SRafael Auler   /// Traverses all elements in the table
31616a497c6SRafael Auler   template <typename... Args>
31716a497c6SRafael Auler   void forEachElement(void (*Callback)(MapEntry &, Args...), Args... args) {
318bd301a41SMichał Chojnowski     Lock L(M);
31916a497c6SRafael Auler     if (!TableRoot)
32016a497c6SRafael Auler       return;
32116a497c6SRafael Auler     return forEachElement(Callback, InitialSize, TableRoot, args...);
32216a497c6SRafael Auler   }
32316a497c6SRafael Auler 
32416a497c6SRafael Auler   void resetCounters();
32516a497c6SRafael Auler 
32616a497c6SRafael Auler private:
32716a497c6SRafael Auler   constexpr static uint64_t VacantMarker = 0;
32816a497c6SRafael Auler   constexpr static uint64_t FollowUpTableMarker = 0x8000000000000000ull;
32916a497c6SRafael Auler 
33016a497c6SRafael Auler   MapEntry *TableRoot{nullptr};
3319aa134dcSVasily Leonenko   MapEntry NoEntry;
33216a497c6SRafael Auler   Mutex M;
33316a497c6SRafael Auler 
33416a497c6SRafael Auler   template <typename... Args>
33516a497c6SRafael Auler   void forEachElement(void (*Callback)(MapEntry &, Args...),
33616a497c6SRafael Auler                       uint32_t NumEntries, MapEntry *Entries, Args... args) {
337c7306cc2SAmir Ayupov     for (uint32_t I = 0; I < NumEntries; ++I) {
338c7306cc2SAmir Ayupov       MapEntry &Entry = Entries[I];
33916a497c6SRafael Auler       if (Entry.Key == VacantMarker)
34016a497c6SRafael Auler         continue;
34116a497c6SRafael Auler       if (Entry.Key & FollowUpTableMarker) {
342*4314f4ceSAmir Ayupov         forEachElement(Callback, IncSize,
343*4314f4ceSAmir Ayupov                        reinterpret_cast<MapEntry *>(Entry.Key &
344*4314f4ceSAmir Ayupov                                                     ~FollowUpTableMarker),
345*4314f4ceSAmir Ayupov                        args...);
34616a497c6SRafael Auler         continue;
34716a497c6SRafael Auler       }
34816a497c6SRafael Auler       Callback(Entry, args...);
34916a497c6SRafael Auler     }
35016a497c6SRafael Auler   }
35116a497c6SRafael Auler 
35216a497c6SRafael Auler   MapEntry &firstAllocation(uint64_t Key, BumpPtrAllocator &Alloc) {
35316a497c6SRafael Auler     TableRoot = new (Alloc, 0) MapEntry[InitialSize];
354c7306cc2SAmir Ayupov     MapEntry &Entry = TableRoot[Key % InitialSize];
35516a497c6SRafael Auler     Entry.Key = Key;
35647934c11SDenis Revunov     // DEBUG(Entry.dump("Created root entry: "));
35716a497c6SRafael Auler     return Entry;
35816a497c6SRafael Auler   }
35916a497c6SRafael Auler 
36016a497c6SRafael Auler   MapEntry &getEntry(MapEntry *Entries, uint64_t Key, uint64_t Selector,
36116a497c6SRafael Auler                      BumpPtrAllocator &Alloc, int CurLevel) {
36247934c11SDenis Revunov     // DEBUG(reportNumber("getEntry called, level ", CurLevel, 10));
36316a497c6SRafael Auler     const uint32_t NumEntries = CurLevel == 0 ? InitialSize : IncSize;
36416a497c6SRafael Auler     uint64_t Remainder = Selector / NumEntries;
36516a497c6SRafael Auler     Selector = Selector % NumEntries;
366c7306cc2SAmir Ayupov     MapEntry &Entry = Entries[Selector];
36716a497c6SRafael Auler 
36816a497c6SRafael Auler     // A hit
36916a497c6SRafael Auler     if (Entry.Key == Key) {
37047934c11SDenis Revunov       // DEBUG(Entry.dump("Hit: "));
37116a497c6SRafael Auler       return Entry;
37216a497c6SRafael Auler     }
37316a497c6SRafael Auler 
37416a497c6SRafael Auler     // Vacant - add new entry
37516a497c6SRafael Auler     if (Entry.Key == VacantMarker) {
37616a497c6SRafael Auler       Entry.Key = Key;
37747934c11SDenis Revunov       // DEBUG(Entry.dump("Adding new entry: "));
37816a497c6SRafael Auler       return Entry;
37916a497c6SRafael Auler     }
38016a497c6SRafael Auler 
38116a497c6SRafael Auler     // Defer to the next level
38216a497c6SRafael Auler     if (Entry.Key & FollowUpTableMarker) {
38316a497c6SRafael Auler       return getEntry(
38416a497c6SRafael Auler           reinterpret_cast<MapEntry *>(Entry.Key & ~FollowUpTableMarker),
38516a497c6SRafael Auler           Key, Remainder, Alloc, CurLevel + 1);
38616a497c6SRafael Auler     }
38716a497c6SRafael Auler 
38816a497c6SRafael Auler     // Conflict - create the next level
38947934c11SDenis Revunov     // DEBUG(Entry.dump("Creating new level: "));
39047934c11SDenis Revunov 
39116a497c6SRafael Auler     MapEntry *NextLevelTbl = new (Alloc, 0) MapEntry[IncSize];
39247934c11SDenis Revunov     // DEBUG(
39347934c11SDenis Revunov     //     reportNumber("Newly allocated level: 0x", uint64_t(NextLevelTbl),
39447934c11SDenis Revunov     //     16));
39516a497c6SRafael Auler     uint64_t CurEntrySelector = Entry.Key / InitialSize;
39616a497c6SRafael Auler     for (int I = 0; I < CurLevel; ++I)
39716a497c6SRafael Auler       CurEntrySelector /= IncSize;
39816a497c6SRafael Auler     CurEntrySelector = CurEntrySelector % IncSize;
39916a497c6SRafael Auler     NextLevelTbl[CurEntrySelector] = Entry;
40016a497c6SRafael Auler     Entry.Key = reinterpret_cast<uint64_t>(NextLevelTbl) | FollowUpTableMarker;
401ad4e0770SDenis Revunov     assert((NextLevelTbl[CurEntrySelector].Key & ~FollowUpTableMarker) !=
402ad4e0770SDenis Revunov                uint64_t(Entries),
403ad4e0770SDenis Revunov            "circular reference created!\n");
40447934c11SDenis Revunov     // DEBUG(NextLevelTbl[CurEntrySelector].dump("New level entry: "));
40547934c11SDenis Revunov     // DEBUG(Entry.dump("Updated old entry: "));
40616a497c6SRafael Auler     return getEntry(NextLevelTbl, Key, Remainder, Alloc, CurLevel + 1);
40716a497c6SRafael Auler   }
4089aa134dcSVasily Leonenko 
4099aa134dcSVasily Leonenko   MapEntry &getOrAllocEntry(uint64_t Key, BumpPtrAllocator &Alloc) {
410*4314f4ceSAmir Ayupov     if (TableRoot)
411*4314f4ceSAmir Ayupov       return getEntry(TableRoot, Key, Key, Alloc, 0);
4129aa134dcSVasily Leonenko     return firstAllocation(Key, Alloc);
4139aa134dcSVasily Leonenko   }
41416a497c6SRafael Auler };
41516a497c6SRafael Auler 
41616a497c6SRafael Auler template <typename T> void resetIndCallCounter(T &Entry) {
41716a497c6SRafael Auler   Entry.Val = 0;
41816a497c6SRafael Auler }
41916a497c6SRafael Auler 
42016a497c6SRafael Auler template <typename T, uint32_t X, uint32_t Y>
42116a497c6SRafael Auler void SimpleHashTable<T, X, Y>::resetCounters() {
42216a497c6SRafael Auler   forEachElement(resetIndCallCounter);
42316a497c6SRafael Auler }
42416a497c6SRafael Auler 
42516a497c6SRafael Auler /// Represents a hash table mapping a function target address to its counter.
42616a497c6SRafael Auler using IndirectCallHashTable = SimpleHashTable<>;
42716a497c6SRafael Auler 
42816a497c6SRafael Auler /// Initialize with number 1 instead of 0 so we don't go into .bss. This is the
42916a497c6SRafael Auler /// global array of all hash tables storing indirect call destinations happening
43016a497c6SRafael Auler /// during runtime, one table per call site.
43116a497c6SRafael Auler IndirectCallHashTable *GlobalIndCallCounters{
43216a497c6SRafael Auler     reinterpret_cast<IndirectCallHashTable *>(1)};
43316a497c6SRafael Auler 
43416a497c6SRafael Auler /// Don't allow reentrancy in the fdata writing phase - only one thread writes
43516a497c6SRafael Auler /// it
43616a497c6SRafael Auler Mutex *GlobalWriteProfileMutex{reinterpret_cast<Mutex *>(1)};
43716a497c6SRafael Auler 
43816a497c6SRafael Auler /// Store number of calls in additional to target address (Key) and frequency
43916a497c6SRafael Auler /// as perceived by the basic block counter (Val).
44016a497c6SRafael Auler struct CallFlowEntryBase : public SimpleHashTableEntryBase {
44116a497c6SRafael Auler   uint64_t Calls;
44216a497c6SRafael Auler };
44316a497c6SRafael Auler 
44416a497c6SRafael Auler using CallFlowHashTableBase = SimpleHashTable<CallFlowEntryBase, 11939, 233>;
44516a497c6SRafael Auler 
44616a497c6SRafael Auler /// This is a large table indexing all possible call targets (indirect and
44716a497c6SRafael Auler /// direct ones). The goal is to find mismatches between number of calls (for
44816a497c6SRafael Auler /// those calls we were able to track) and the entry basic block counter of the
44916a497c6SRafael Auler /// callee. In most cases, these two should be equal. If not, there are two
45016a497c6SRafael Auler /// possible scenarios here:
45116a497c6SRafael Auler ///
45216a497c6SRafael Auler ///  * Entry BB has higher frequency than all known calls to this function.
45316a497c6SRafael Auler ///    In this case, we have dynamic library code or any uninstrumented code
45416a497c6SRafael Auler ///    calling this function. We will write the profile for these untracked
45516a497c6SRafael Auler ///    calls as having source "0 [unknown] 0" in the fdata file.
45616a497c6SRafael Auler ///
45716a497c6SRafael Auler ///  * Number of known calls is higher than the frequency of entry BB
45816a497c6SRafael Auler ///    This only happens when there is no counter for the entry BB / callee
45916a497c6SRafael Auler ///    function is not simple (in BOLT terms). We don't do anything special
46016a497c6SRafael Auler ///    here and just ignore those (we still report all calls to the non-simple
46116a497c6SRafael Auler ///    function, though).
46216a497c6SRafael Auler ///
46316a497c6SRafael Auler class CallFlowHashTable : public CallFlowHashTableBase {
46416a497c6SRafael Auler public:
46516a497c6SRafael Auler   CallFlowHashTable(BumpPtrAllocator &Alloc) : Alloc(Alloc) {}
46616a497c6SRafael Auler 
46716a497c6SRafael Auler   MapEntry &get(uint64_t Key) { return CallFlowHashTableBase::get(Key, Alloc); }
46816a497c6SRafael Auler 
46916a497c6SRafael Auler private:
47016a497c6SRafael Auler   // Different than the hash table for indirect call targets, we do store the
47116a497c6SRafael Auler   // allocator here since there is only one call flow hash and space overhead
47216a497c6SRafael Auler   // is negligible.
47316a497c6SRafael Auler   BumpPtrAllocator &Alloc;
47416a497c6SRafael Auler };
47516a497c6SRafael Auler 
47616a497c6SRafael Auler ///
47716a497c6SRafael Auler /// Description metadata emitted by BOLT to describe the program - refer to
47816a497c6SRafael Auler /// Passes/Instrumentation.cpp - Instrumentation::emitTablesAsELFNote()
47916a497c6SRafael Auler ///
48016a497c6SRafael Auler struct Location {
48116a497c6SRafael Auler   uint32_t FunctionName;
48216a497c6SRafael Auler   uint32_t Offset;
48316a497c6SRafael Auler };
48416a497c6SRafael Auler 
48516a497c6SRafael Auler struct CallDescription {
48616a497c6SRafael Auler   Location From;
48716a497c6SRafael Auler   uint32_t FromNode;
48816a497c6SRafael Auler   Location To;
48916a497c6SRafael Auler   uint32_t Counter;
49016a497c6SRafael Auler   uint64_t TargetAddress;
49116a497c6SRafael Auler };
49216a497c6SRafael Auler 
49316a497c6SRafael Auler using IndCallDescription = Location;
49416a497c6SRafael Auler 
49516a497c6SRafael Auler struct IndCallTargetDescription {
49616a497c6SRafael Auler   Location Loc;
49716a497c6SRafael Auler   uint64_t Address;
49816a497c6SRafael Auler };
49916a497c6SRafael Auler 
50016a497c6SRafael Auler struct EdgeDescription {
50116a497c6SRafael Auler   Location From;
50216a497c6SRafael Auler   uint32_t FromNode;
50316a497c6SRafael Auler   Location To;
50416a497c6SRafael Auler   uint32_t ToNode;
50516a497c6SRafael Auler   uint32_t Counter;
50616a497c6SRafael Auler };
50716a497c6SRafael Auler 
50816a497c6SRafael Auler struct InstrumentedNode {
50916a497c6SRafael Auler   uint32_t Node;
51016a497c6SRafael Auler   uint32_t Counter;
51116a497c6SRafael Auler };
51216a497c6SRafael Auler 
51316a497c6SRafael Auler struct EntryNode {
51416a497c6SRafael Auler   uint64_t Node;
51516a497c6SRafael Auler   uint64_t Address;
51616a497c6SRafael Auler };
51716a497c6SRafael Auler 
51816a497c6SRafael Auler struct FunctionDescription {
51916a497c6SRafael Auler   uint32_t NumLeafNodes;
52016a497c6SRafael Auler   const InstrumentedNode *LeafNodes;
52116a497c6SRafael Auler   uint32_t NumEdges;
52216a497c6SRafael Auler   const EdgeDescription *Edges;
52316a497c6SRafael Auler   uint32_t NumCalls;
52416a497c6SRafael Auler   const CallDescription *Calls;
52516a497c6SRafael Auler   uint32_t NumEntryNodes;
52616a497c6SRafael Auler   const EntryNode *EntryNodes;
52716a497c6SRafael Auler 
52816a497c6SRafael Auler   /// Constructor will parse the serialized function metadata written by BOLT
52916a497c6SRafael Auler   FunctionDescription(const uint8_t *FuncDesc);
53016a497c6SRafael Auler 
53116a497c6SRafael Auler   uint64_t getSize() const {
53216a497c6SRafael Auler     return 16 + NumLeafNodes * sizeof(InstrumentedNode) +
53316a497c6SRafael Auler            NumEdges * sizeof(EdgeDescription) +
53416a497c6SRafael Auler            NumCalls * sizeof(CallDescription) +
53516a497c6SRafael Auler            NumEntryNodes * sizeof(EntryNode);
53616a497c6SRafael Auler   }
53716a497c6SRafael Auler };
53816a497c6SRafael Auler 
53916a497c6SRafael Auler /// The context is created when the fdata profile needs to be written to disk
54016a497c6SRafael Auler /// and we need to interpret our runtime counters. It contains pointers to the
54116a497c6SRafael Auler /// mmaped binary (only the BOLT written metadata section). Deserialization
54216a497c6SRafael Auler /// should be straightforward as most data is POD or an array of POD elements.
54316a497c6SRafael Auler /// This metadata is used to reconstruct function CFGs.
54416a497c6SRafael Auler struct ProfileWriterContext {
54516a497c6SRafael Auler   IndCallDescription *IndCallDescriptions;
54616a497c6SRafael Auler   IndCallTargetDescription *IndCallTargets;
54716a497c6SRafael Auler   uint8_t *FuncDescriptions;
54816a497c6SRafael Auler   char *Strings;  // String table with function names used in this binary
54916a497c6SRafael Auler   int FileDesc;   // File descriptor for the file on disk backing this
55016a497c6SRafael Auler                   // information in memory via mmap
55116a497c6SRafael Auler   void *MMapPtr;  // The mmap ptr
55216a497c6SRafael Auler   int MMapSize;   // The mmap size
55316a497c6SRafael Auler 
55416a497c6SRafael Auler   /// Hash table storing all possible call destinations to detect untracked
55516a497c6SRafael Auler   /// calls and correctly report them as [unknown] in output fdata.
55616a497c6SRafael Auler   CallFlowHashTable *CallFlowTable;
55716a497c6SRafael Auler 
55816a497c6SRafael Auler   /// Lookup the sorted indirect call target vector to fetch function name and
55916a497c6SRafael Auler   /// offset for an arbitrary function pointer.
56016a497c6SRafael Auler   const IndCallTargetDescription *lookupIndCallTarget(uint64_t Target) const;
56116a497c6SRafael Auler };
56216a497c6SRafael Auler 
56316a497c6SRafael Auler /// Perform a string comparison and returns zero if Str1 matches Str2. Compares
56416a497c6SRafael Auler /// at most Size characters.
565cc4b2fb6SRafael Auler int compareStr(const char *Str1, const char *Str2, int Size) {
566821480d2SRafael Auler   while (*Str1 == *Str2) {
567821480d2SRafael Auler     if (*Str1 == '\0' || --Size == 0)
568821480d2SRafael Auler       return 0;
569821480d2SRafael Auler     ++Str1;
570821480d2SRafael Auler     ++Str2;
571821480d2SRafael Auler   }
572821480d2SRafael Auler   return 1;
573821480d2SRafael Auler }
574821480d2SRafael Auler 
57516a497c6SRafael Auler /// Output Location to the fdata file
57616a497c6SRafael Auler char *serializeLoc(const ProfileWriterContext &Ctx, char *OutBuf,
577cc4b2fb6SRafael Auler                    const Location Loc, uint32_t BufSize) {
578821480d2SRafael Auler   // fdata location format: Type Name Offset
579821480d2SRafael Auler   // Type 1 - regular symbol
580821480d2SRafael Auler   OutBuf = strCopy(OutBuf, "1 ");
58116a497c6SRafael Auler   const char *Str = Ctx.Strings + Loc.FunctionName;
582cc4b2fb6SRafael Auler   uint32_t Size = 25;
58362aa74f8SRafael Auler   while (*Str) {
58462aa74f8SRafael Auler     *OutBuf++ = *Str++;
585cc4b2fb6SRafael Auler     if (++Size >= BufSize)
586cc4b2fb6SRafael Auler       break;
58762aa74f8SRafael Auler   }
588cc4b2fb6SRafael Auler   assert(!*Str, "buffer overflow, function name too large");
58962aa74f8SRafael Auler   *OutBuf++ = ' ';
590821480d2SRafael Auler   OutBuf = intToStr(OutBuf, Loc.Offset, 16);
59162aa74f8SRafael Auler   *OutBuf++ = ' ';
59262aa74f8SRafael Auler   return OutBuf;
59362aa74f8SRafael Auler }
59462aa74f8SRafael Auler 
59516a497c6SRafael Auler /// Read and deserialize a function description written by BOLT. \p FuncDesc
59616a497c6SRafael Auler /// points at the beginning of the function metadata structure in the file.
59716a497c6SRafael Auler /// See Instrumentation::emitTablesAsELFNote()
59816a497c6SRafael Auler FunctionDescription::FunctionDescription(const uint8_t *FuncDesc) {
59916a497c6SRafael Auler   NumLeafNodes = *reinterpret_cast<const uint32_t *>(FuncDesc);
60016a497c6SRafael Auler   DEBUG(reportNumber("NumLeafNodes = ", NumLeafNodes, 10));
60116a497c6SRafael Auler   LeafNodes = reinterpret_cast<const InstrumentedNode *>(FuncDesc + 4);
60216a497c6SRafael Auler 
60316a497c6SRafael Auler   NumEdges = *reinterpret_cast<const uint32_t *>(
60416a497c6SRafael Auler       FuncDesc + 4 + NumLeafNodes * sizeof(InstrumentedNode));
60516a497c6SRafael Auler   DEBUG(reportNumber("NumEdges = ", NumEdges, 10));
60616a497c6SRafael Auler   Edges = reinterpret_cast<const EdgeDescription *>(
60716a497c6SRafael Auler       FuncDesc + 8 + NumLeafNodes * sizeof(InstrumentedNode));
60816a497c6SRafael Auler 
60916a497c6SRafael Auler   NumCalls = *reinterpret_cast<const uint32_t *>(
61016a497c6SRafael Auler       FuncDesc + 8 + NumLeafNodes * sizeof(InstrumentedNode) +
61116a497c6SRafael Auler       NumEdges * sizeof(EdgeDescription));
61216a497c6SRafael Auler   DEBUG(reportNumber("NumCalls = ", NumCalls, 10));
61316a497c6SRafael Auler   Calls = reinterpret_cast<const CallDescription *>(
61416a497c6SRafael Auler       FuncDesc + 12 + NumLeafNodes * sizeof(InstrumentedNode) +
61516a497c6SRafael Auler       NumEdges * sizeof(EdgeDescription));
61616a497c6SRafael Auler   NumEntryNodes = *reinterpret_cast<const uint32_t *>(
61716a497c6SRafael Auler       FuncDesc + 12 + NumLeafNodes * sizeof(InstrumentedNode) +
61816a497c6SRafael Auler       NumEdges * sizeof(EdgeDescription) + NumCalls * sizeof(CallDescription));
61916a497c6SRafael Auler   DEBUG(reportNumber("NumEntryNodes = ", NumEntryNodes, 10));
62016a497c6SRafael Auler   EntryNodes = reinterpret_cast<const EntryNode *>(
62116a497c6SRafael Auler       FuncDesc + 16 + NumLeafNodes * sizeof(InstrumentedNode) +
62216a497c6SRafael Auler       NumEdges * sizeof(EdgeDescription) + NumCalls * sizeof(CallDescription));
62316a497c6SRafael Auler }
62416a497c6SRafael Auler 
62516a497c6SRafael Auler /// Read and mmap descriptions written by BOLT from the executable's notes
62616a497c6SRafael Auler /// section
627a0dd5b05SAlexander Shaposhnikov #if defined(HAVE_ELF_H) and !defined(__APPLE__)
6282ffd6e2bSElvina Yakubova 
6292ffd6e2bSElvina Yakubova void *__attribute__((noinline)) __get_pc() {
6302ffd6e2bSElvina Yakubova   return __builtin_extract_return_addr(__builtin_return_address(0));
6312ffd6e2bSElvina Yakubova }
6322ffd6e2bSElvina Yakubova 
6332ffd6e2bSElvina Yakubova /// Get string with address and parse it to hex pair <StartAddress, EndAddress>
6342ffd6e2bSElvina Yakubova bool parseAddressRange(const char *Str, uint64_t &StartAddress,
6352ffd6e2bSElvina Yakubova                        uint64_t &EndAddress) {
6362ffd6e2bSElvina Yakubova   if (!Str)
6372ffd6e2bSElvina Yakubova     return false;
6382ffd6e2bSElvina Yakubova   // Parsed string format: <hex1>-<hex2>
6392ffd6e2bSElvina Yakubova   StartAddress = hexToLong(Str, '-');
6402ffd6e2bSElvina Yakubova   while (*Str && *Str != '-')
6412ffd6e2bSElvina Yakubova     ++Str;
6422ffd6e2bSElvina Yakubova   if (!*Str)
6432ffd6e2bSElvina Yakubova     return false;
6442ffd6e2bSElvina Yakubova   ++Str; // swallow '-'
6452ffd6e2bSElvina Yakubova   EndAddress = hexToLong(Str);
6462ffd6e2bSElvina Yakubova   return true;
6472ffd6e2bSElvina Yakubova }
6482ffd6e2bSElvina Yakubova 
6492ffd6e2bSElvina Yakubova /// Get full path to the real binary by getting current virtual address
6502ffd6e2bSElvina Yakubova /// and searching for the appropriate link in address range in
6512ffd6e2bSElvina Yakubova /// /proc/self/map_files
6522ffd6e2bSElvina Yakubova static char *getBinaryPath() {
6532ffd6e2bSElvina Yakubova   const uint32_t BufSize = 1024;
65446bc197dSMarius Wachtler   const uint32_t NameMax = 4096;
6552ffd6e2bSElvina Yakubova   const char DirPath[] = "/proc/self/map_files/";
6562ffd6e2bSElvina Yakubova   static char TargetPath[NameMax] = {};
6572ffd6e2bSElvina Yakubova   char Buf[BufSize];
6582ffd6e2bSElvina Yakubova 
659519cbbaaSVasily Leonenko   if (__bolt_instr_binpath[0] != '\0')
660519cbbaaSVasily Leonenko     return __bolt_instr_binpath;
661519cbbaaSVasily Leonenko 
6622ffd6e2bSElvina Yakubova   if (TargetPath[0] != '\0')
6632ffd6e2bSElvina Yakubova     return TargetPath;
6642ffd6e2bSElvina Yakubova 
6652ffd6e2bSElvina Yakubova   unsigned long CurAddr = (unsigned long)__get_pc();
6662ffd6e2bSElvina Yakubova   uint64_t FDdir = __open(DirPath,
667821480d2SRafael Auler                           /*flags=*/0 /*O_RDONLY*/,
668821480d2SRafael Auler                           /*mode=*/0666);
6693b00a3a2SMarius Wachtler   assert(static_cast<int64_t>(FDdir) >= 0,
6702ffd6e2bSElvina Yakubova          "failed to open /proc/self/map_files");
6712ffd6e2bSElvina Yakubova 
6722ffd6e2bSElvina Yakubova   while (long Nread = __getdents(FDdir, (struct dirent *)Buf, BufSize)) {
6732ffd6e2bSElvina Yakubova     assert(static_cast<int64_t>(Nread) != -1, "failed to get folder entries");
6742ffd6e2bSElvina Yakubova 
6752ffd6e2bSElvina Yakubova     struct dirent *d;
6762ffd6e2bSElvina Yakubova     for (long Bpos = 0; Bpos < Nread; Bpos += d->d_reclen) {
6772ffd6e2bSElvina Yakubova       d = (struct dirent *)(Buf + Bpos);
6782ffd6e2bSElvina Yakubova 
6792ffd6e2bSElvina Yakubova       uint64_t StartAddress, EndAddress;
6802ffd6e2bSElvina Yakubova       if (!parseAddressRange(d->d_name, StartAddress, EndAddress))
6812ffd6e2bSElvina Yakubova         continue;
6822ffd6e2bSElvina Yakubova       if (CurAddr < StartAddress || CurAddr > EndAddress)
6832ffd6e2bSElvina Yakubova         continue;
6842ffd6e2bSElvina Yakubova       char FindBuf[NameMax];
6852ffd6e2bSElvina Yakubova       char *C = strCopy(FindBuf, DirPath, NameMax);
6862ffd6e2bSElvina Yakubova       C = strCopy(C, d->d_name, NameMax - (C - FindBuf));
6872ffd6e2bSElvina Yakubova       *C = '\0';
6882ffd6e2bSElvina Yakubova       uint32_t Ret = __readlink(FindBuf, TargetPath, sizeof(TargetPath));
6892ffd6e2bSElvina Yakubova       assert(Ret != -1 && Ret != BufSize, "readlink error");
6902ffd6e2bSElvina Yakubova       TargetPath[Ret] = '\0';
6912ffd6e2bSElvina Yakubova       return TargetPath;
6922ffd6e2bSElvina Yakubova     }
6932ffd6e2bSElvina Yakubova   }
6942ffd6e2bSElvina Yakubova   return nullptr;
6952ffd6e2bSElvina Yakubova }
6962ffd6e2bSElvina Yakubova 
6972ffd6e2bSElvina Yakubova ProfileWriterContext readDescriptions() {
6982ffd6e2bSElvina Yakubova   ProfileWriterContext Result;
6992ffd6e2bSElvina Yakubova   char *BinPath = getBinaryPath();
7002ffd6e2bSElvina Yakubova   assert(BinPath && BinPath[0] != '\0', "failed to find binary path");
7012ffd6e2bSElvina Yakubova 
7022ffd6e2bSElvina Yakubova   uint64_t FD = __open(BinPath,
7032ffd6e2bSElvina Yakubova                        /*flags=*/0 /*O_RDONLY*/,
7042ffd6e2bSElvina Yakubova                        /*mode=*/0666);
7053b00a3a2SMarius Wachtler   assert(static_cast<int64_t>(FD) >= 0, "failed to open binary path");
7062ffd6e2bSElvina Yakubova 
707821480d2SRafael Auler   Result.FileDesc = FD;
708821480d2SRafael Auler 
709821480d2SRafael Auler   // mmap our binary to memory
710821480d2SRafael Auler   uint64_t Size = __lseek(FD, 0, 2 /*SEEK_END*/);
711821480d2SRafael Auler   uint8_t *BinContents = reinterpret_cast<uint8_t *>(
712f0b45fbaSDenis Revunov       __mmap(0, Size, PROT_READ, MAP_PRIVATE, FD, 0));
7138f7c53efSDenis Revunov   assert(BinContents != MAP_FAILED, "readDescriptions: Failed to mmap self!");
714821480d2SRafael Auler   Result.MMapPtr = BinContents;
715821480d2SRafael Auler   Result.MMapSize = Size;
716821480d2SRafael Auler   Elf64_Ehdr *Hdr = reinterpret_cast<Elf64_Ehdr *>(BinContents);
717821480d2SRafael Auler   Elf64_Shdr *Shdr = reinterpret_cast<Elf64_Shdr *>(BinContents + Hdr->e_shoff);
718821480d2SRafael Auler   Elf64_Shdr *StringTblHeader = reinterpret_cast<Elf64_Shdr *>(
719821480d2SRafael Auler       BinContents + Hdr->e_shoff + Hdr->e_shstrndx * Hdr->e_shentsize);
720821480d2SRafael Auler 
721821480d2SRafael Auler   // Find .bolt.instr.tables with the data we need and set pointers to it
722821480d2SRafael Auler   for (int I = 0; I < Hdr->e_shnum; ++I) {
723821480d2SRafael Auler     char *SecName = reinterpret_cast<char *>(
724821480d2SRafael Auler         BinContents + StringTblHeader->sh_offset + Shdr->sh_name);
725821480d2SRafael Auler     if (compareStr(SecName, ".bolt.instr.tables", 64) != 0) {
726821480d2SRafael Auler       Shdr = reinterpret_cast<Elf64_Shdr *>(BinContents + Hdr->e_shoff +
727821480d2SRafael Auler                                             (I + 1) * Hdr->e_shentsize);
728821480d2SRafael Auler       continue;
729821480d2SRafael Auler     }
730821480d2SRafael Auler     // Actual contents of the ELF note start after offset 20 decimal:
731821480d2SRafael Auler     // Offset 0: Producer name size (4 bytes)
732821480d2SRafael Auler     // Offset 4: Contents size (4 bytes)
733821480d2SRafael Auler     // Offset 8: Note type (4 bytes)
734821480d2SRafael Auler     // Offset 12: Producer name (BOLT\0) (5 bytes + align to 4-byte boundary)
735821480d2SRafael Auler     // Offset 20: Contents
73616a497c6SRafael Auler     uint32_t IndCallDescSize =
737cc4b2fb6SRafael Auler         *reinterpret_cast<uint32_t *>(BinContents + Shdr->sh_offset + 20);
73816a497c6SRafael Auler     uint32_t IndCallTargetDescSize = *reinterpret_cast<uint32_t *>(
73916a497c6SRafael Auler         BinContents + Shdr->sh_offset + 24 + IndCallDescSize);
74016a497c6SRafael Auler     uint32_t FuncDescSize =
74116a497c6SRafael Auler         *reinterpret_cast<uint32_t *>(BinContents + Shdr->sh_offset + 28 +
74216a497c6SRafael Auler                                       IndCallDescSize + IndCallTargetDescSize);
74316a497c6SRafael Auler     Result.IndCallDescriptions = reinterpret_cast<IndCallDescription *>(
74416a497c6SRafael Auler         BinContents + Shdr->sh_offset + 24);
74516a497c6SRafael Auler     Result.IndCallTargets = reinterpret_cast<IndCallTargetDescription *>(
74616a497c6SRafael Auler         BinContents + Shdr->sh_offset + 28 + IndCallDescSize);
74716a497c6SRafael Auler     Result.FuncDescriptions = BinContents + Shdr->sh_offset + 32 +
74816a497c6SRafael Auler                               IndCallDescSize + IndCallTargetDescSize;
74916a497c6SRafael Auler     Result.Strings = reinterpret_cast<char *>(
75016a497c6SRafael Auler         BinContents + Shdr->sh_offset + 32 + IndCallDescSize +
75116a497c6SRafael Auler         IndCallTargetDescSize + FuncDescSize);
752821480d2SRafael Auler     return Result;
753821480d2SRafael Auler   }
754821480d2SRafael Auler   const char ErrMsg[] =
755821480d2SRafael Auler       "BOLT instrumentation runtime error: could not find section "
756821480d2SRafael Auler       ".bolt.instr.tables\n";
757821480d2SRafael Auler   reportError(ErrMsg, sizeof(ErrMsg));
758821480d2SRafael Auler   return Result;
759821480d2SRafael Auler }
760a0dd5b05SAlexander Shaposhnikov 
761ba31344fSRafael Auler #else
762a0dd5b05SAlexander Shaposhnikov 
76316a497c6SRafael Auler ProfileWriterContext readDescriptions() {
76416a497c6SRafael Auler   ProfileWriterContext Result;
765a0dd5b05SAlexander Shaposhnikov   uint8_t *Tables = _bolt_instr_tables_getter();
766a0dd5b05SAlexander Shaposhnikov   uint32_t IndCallDescSize = *reinterpret_cast<uint32_t *>(Tables);
767a0dd5b05SAlexander Shaposhnikov   uint32_t IndCallTargetDescSize =
768a0dd5b05SAlexander Shaposhnikov       *reinterpret_cast<uint32_t *>(Tables + 4 + IndCallDescSize);
769a0dd5b05SAlexander Shaposhnikov   uint32_t FuncDescSize = *reinterpret_cast<uint32_t *>(
770a0dd5b05SAlexander Shaposhnikov       Tables + 8 + IndCallDescSize + IndCallTargetDescSize);
771a0dd5b05SAlexander Shaposhnikov   Result.IndCallDescriptions =
772a0dd5b05SAlexander Shaposhnikov       reinterpret_cast<IndCallDescription *>(Tables + 4);
773a0dd5b05SAlexander Shaposhnikov   Result.IndCallTargets = reinterpret_cast<IndCallTargetDescription *>(
774a0dd5b05SAlexander Shaposhnikov       Tables + 8 + IndCallDescSize);
775a0dd5b05SAlexander Shaposhnikov   Result.FuncDescriptions =
776a0dd5b05SAlexander Shaposhnikov       Tables + 12 + IndCallDescSize + IndCallTargetDescSize;
777a0dd5b05SAlexander Shaposhnikov   Result.Strings = reinterpret_cast<char *>(
778a0dd5b05SAlexander Shaposhnikov       Tables + 12 + IndCallDescSize + IndCallTargetDescSize + FuncDescSize);
779ba31344fSRafael Auler   return Result;
780ba31344fSRafael Auler }
781a0dd5b05SAlexander Shaposhnikov 
782ba31344fSRafael Auler #endif
783821480d2SRafael Auler 
784a0dd5b05SAlexander Shaposhnikov #if !defined(__APPLE__)
78516a497c6SRafael Auler /// Debug by printing overall metadata global numbers to check it is sane
78616a497c6SRafael Auler void printStats(const ProfileWriterContext &Ctx) {
787cc4b2fb6SRafael Auler   char StatMsg[BufSize];
788cc4b2fb6SRafael Auler   char *StatPtr = StatMsg;
78916a497c6SRafael Auler   StatPtr =
79016a497c6SRafael Auler       strCopy(StatPtr,
79116a497c6SRafael Auler               "\nBOLT INSTRUMENTATION RUNTIME STATISTICS\n\nIndCallDescSize: ");
792cc4b2fb6SRafael Auler   StatPtr = intToStr(StatPtr,
79316a497c6SRafael Auler                      Ctx.FuncDescriptions -
79416a497c6SRafael Auler                          reinterpret_cast<uint8_t *>(Ctx.IndCallDescriptions),
795cc4b2fb6SRafael Auler                      10);
796cc4b2fb6SRafael Auler   StatPtr = strCopy(StatPtr, "\nFuncDescSize: ");
797cc4b2fb6SRafael Auler   StatPtr = intToStr(
798cc4b2fb6SRafael Auler       StatPtr,
79916a497c6SRafael Auler       reinterpret_cast<uint8_t *>(Ctx.Strings) - Ctx.FuncDescriptions, 10);
80016a497c6SRafael Auler   StatPtr = strCopy(StatPtr, "\n__bolt_instr_num_ind_calls: ");
80116a497c6SRafael Auler   StatPtr = intToStr(StatPtr, __bolt_instr_num_ind_calls, 10);
802cc4b2fb6SRafael Auler   StatPtr = strCopy(StatPtr, "\n__bolt_instr_num_funcs: ");
803cc4b2fb6SRafael Auler   StatPtr = intToStr(StatPtr, __bolt_instr_num_funcs, 10);
804cc4b2fb6SRafael Auler   StatPtr = strCopy(StatPtr, "\n");
805cc4b2fb6SRafael Auler   __write(2, StatMsg, StatPtr - StatMsg);
806cc4b2fb6SRafael Auler }
807a0dd5b05SAlexander Shaposhnikov #endif
808a0dd5b05SAlexander Shaposhnikov 
809cc4b2fb6SRafael Auler 
810cc4b2fb6SRafael Auler /// This is part of a simple CFG representation in memory, where we store
811cc4b2fb6SRafael Auler /// a dynamically sized array of input and output edges per node, and store
812cc4b2fb6SRafael Auler /// a dynamically sized array of nodes per graph. We also store the spanning
813cc4b2fb6SRafael Auler /// tree edges for that CFG in a separate array of nodes in
814cc4b2fb6SRafael Auler /// \p SpanningTreeNodes, while the regular nodes live in \p CFGNodes.
815cc4b2fb6SRafael Auler struct Edge {
816cc4b2fb6SRafael Auler   uint32_t Node; // Index in nodes array regarding the destination of this edge
817cc4b2fb6SRafael Auler   uint32_t ID;   // Edge index in an array comprising all edges of the graph
818cc4b2fb6SRafael Auler };
819cc4b2fb6SRafael Auler 
820cc4b2fb6SRafael Auler /// A regular graph node or a spanning tree node
821cc4b2fb6SRafael Auler struct Node {
822cc4b2fb6SRafael Auler   uint32_t NumInEdges{0};  // Input edge count used to size InEdge
823cc4b2fb6SRafael Auler   uint32_t NumOutEdges{0}; // Output edge count used to size OutEdges
824cc4b2fb6SRafael Auler   Edge *InEdges{nullptr};  // Created and managed by \p Graph
825cc4b2fb6SRafael Auler   Edge *OutEdges{nullptr}; // ditto
826cc4b2fb6SRafael Auler };
827cc4b2fb6SRafael Auler 
828cc4b2fb6SRafael Auler /// Main class for CFG representation in memory. Manages object creation and
829cc4b2fb6SRafael Auler /// destruction, populates an array of CFG nodes as well as corresponding
830cc4b2fb6SRafael Auler /// spanning tree nodes.
831cc4b2fb6SRafael Auler struct Graph {
832cc4b2fb6SRafael Auler   uint32_t NumNodes;
833cc4b2fb6SRafael Auler   Node *CFGNodes;
834cc4b2fb6SRafael Auler   Node *SpanningTreeNodes;
83516a497c6SRafael Auler   uint64_t *EdgeFreqs;
83616a497c6SRafael Auler   uint64_t *CallFreqs;
837cc4b2fb6SRafael Auler   BumpPtrAllocator &Alloc;
83816a497c6SRafael Auler   const FunctionDescription &D;
839cc4b2fb6SRafael Auler 
84016a497c6SRafael Auler   /// Reads a list of edges from function description \p D and builds
841cc4b2fb6SRafael Auler   /// the graph from it. Allocates several internal dynamic structures that are
84216a497c6SRafael Auler   /// later destroyed by ~Graph() and uses \p Alloc. D.LeafNodes contain all
843cc4b2fb6SRafael Auler   /// spanning tree leaf nodes descriptions (their counters). They are the seed
844cc4b2fb6SRafael Auler   /// used to compute the rest of the missing edge counts in a bottom-up
845cc4b2fb6SRafael Auler   /// traversal of the spanning tree.
84616a497c6SRafael Auler   Graph(BumpPtrAllocator &Alloc, const FunctionDescription &D,
84716a497c6SRafael Auler         const uint64_t *Counters, ProfileWriterContext &Ctx);
848cc4b2fb6SRafael Auler   ~Graph();
849cc4b2fb6SRafael Auler   void dump() const;
85016a497c6SRafael Auler 
85116a497c6SRafael Auler private:
85216a497c6SRafael Auler   void computeEdgeFrequencies(const uint64_t *Counters,
85316a497c6SRafael Auler                               ProfileWriterContext &Ctx);
85416a497c6SRafael Auler   void dumpEdgeFreqs() const;
855cc4b2fb6SRafael Auler };
856cc4b2fb6SRafael Auler 
85716a497c6SRafael Auler Graph::Graph(BumpPtrAllocator &Alloc, const FunctionDescription &D,
85816a497c6SRafael Auler              const uint64_t *Counters, ProfileWriterContext &Ctx)
85916a497c6SRafael Auler     : Alloc(Alloc), D(D) {
860cc4b2fb6SRafael Auler   DEBUG(reportNumber("G = 0x", (uint64_t)this, 16));
861cc4b2fb6SRafael Auler   // First pass to determine number of nodes
86216a497c6SRafael Auler   int32_t MaxNodes = -1;
86316a497c6SRafael Auler   CallFreqs = nullptr;
86416a497c6SRafael Auler   EdgeFreqs = nullptr;
86516a497c6SRafael Auler   for (int I = 0; I < D.NumEdges; ++I) {
86616a497c6SRafael Auler     if (static_cast<int32_t>(D.Edges[I].FromNode) > MaxNodes)
86716a497c6SRafael Auler       MaxNodes = D.Edges[I].FromNode;
86816a497c6SRafael Auler     if (static_cast<int32_t>(D.Edges[I].ToNode) > MaxNodes)
86916a497c6SRafael Auler       MaxNodes = D.Edges[I].ToNode;
870cc4b2fb6SRafael Auler   }
871a0dd5b05SAlexander Shaposhnikov 
872883bf0e8SAmir Ayupov   for (int I = 0; I < D.NumLeafNodes; ++I)
87316a497c6SRafael Auler     if (static_cast<int32_t>(D.LeafNodes[I].Node) > MaxNodes)
87416a497c6SRafael Auler       MaxNodes = D.LeafNodes[I].Node;
875883bf0e8SAmir Ayupov 
876883bf0e8SAmir Ayupov   for (int I = 0; I < D.NumCalls; ++I)
87716a497c6SRafael Auler     if (static_cast<int32_t>(D.Calls[I].FromNode) > MaxNodes)
87816a497c6SRafael Auler       MaxNodes = D.Calls[I].FromNode;
879883bf0e8SAmir Ayupov 
88016a497c6SRafael Auler   // No nodes? Nothing to do
88116a497c6SRafael Auler   if (MaxNodes < 0) {
88216a497c6SRafael Auler     DEBUG(report("No nodes!\n"));
883cc4b2fb6SRafael Auler     CFGNodes = nullptr;
884cc4b2fb6SRafael Auler     SpanningTreeNodes = nullptr;
885cc4b2fb6SRafael Auler     NumNodes = 0;
886cc4b2fb6SRafael Auler     return;
887cc4b2fb6SRafael Auler   }
888cc4b2fb6SRafael Auler   ++MaxNodes;
889cc4b2fb6SRafael Auler   DEBUG(reportNumber("NumNodes = ", MaxNodes, 10));
89016a497c6SRafael Auler   NumNodes = static_cast<uint32_t>(MaxNodes);
891cc4b2fb6SRafael Auler 
892cc4b2fb6SRafael Auler   // Initial allocations
893cc4b2fb6SRafael Auler   CFGNodes = new (Alloc) Node[MaxNodes];
894a0dd5b05SAlexander Shaposhnikov 
895cc4b2fb6SRafael Auler   DEBUG(reportNumber("G->CFGNodes = 0x", (uint64_t)CFGNodes, 16));
896cc4b2fb6SRafael Auler   SpanningTreeNodes = new (Alloc) Node[MaxNodes];
897cc4b2fb6SRafael Auler   DEBUG(reportNumber("G->SpanningTreeNodes = 0x",
898cc4b2fb6SRafael Auler                      (uint64_t)SpanningTreeNodes, 16));
899cc4b2fb6SRafael Auler 
900cc4b2fb6SRafael Auler   // Figure out how much to allocate to each vector (in/out edge sets)
90116a497c6SRafael Auler   for (int I = 0; I < D.NumEdges; ++I) {
90216a497c6SRafael Auler     CFGNodes[D.Edges[I].FromNode].NumOutEdges++;
90316a497c6SRafael Auler     CFGNodes[D.Edges[I].ToNode].NumInEdges++;
90416a497c6SRafael Auler     if (D.Edges[I].Counter != 0xffffffff)
905cc4b2fb6SRafael Auler       continue;
906cc4b2fb6SRafael Auler 
90716a497c6SRafael Auler     SpanningTreeNodes[D.Edges[I].FromNode].NumOutEdges++;
90816a497c6SRafael Auler     SpanningTreeNodes[D.Edges[I].ToNode].NumInEdges++;
909cc4b2fb6SRafael Auler   }
910cc4b2fb6SRafael Auler 
911cc4b2fb6SRafael Auler   // Allocate in/out edge sets
912cc4b2fb6SRafael Auler   for (int I = 0; I < MaxNodes; ++I) {
913cc4b2fb6SRafael Auler     if (CFGNodes[I].NumInEdges > 0)
914cc4b2fb6SRafael Auler       CFGNodes[I].InEdges = new (Alloc) Edge[CFGNodes[I].NumInEdges];
915cc4b2fb6SRafael Auler     if (CFGNodes[I].NumOutEdges > 0)
916cc4b2fb6SRafael Auler       CFGNodes[I].OutEdges = new (Alloc) Edge[CFGNodes[I].NumOutEdges];
917cc4b2fb6SRafael Auler     if (SpanningTreeNodes[I].NumInEdges > 0)
918cc4b2fb6SRafael Auler       SpanningTreeNodes[I].InEdges =
919cc4b2fb6SRafael Auler           new (Alloc) Edge[SpanningTreeNodes[I].NumInEdges];
920cc4b2fb6SRafael Auler     if (SpanningTreeNodes[I].NumOutEdges > 0)
921cc4b2fb6SRafael Auler       SpanningTreeNodes[I].OutEdges =
922cc4b2fb6SRafael Auler           new (Alloc) Edge[SpanningTreeNodes[I].NumOutEdges];
923cc4b2fb6SRafael Auler     CFGNodes[I].NumInEdges = 0;
924cc4b2fb6SRafael Auler     CFGNodes[I].NumOutEdges = 0;
925cc4b2fb6SRafael Auler     SpanningTreeNodes[I].NumInEdges = 0;
926cc4b2fb6SRafael Auler     SpanningTreeNodes[I].NumOutEdges = 0;
927cc4b2fb6SRafael Auler   }
928cc4b2fb6SRafael Auler 
929cc4b2fb6SRafael Auler   // Fill in/out edge sets
93016a497c6SRafael Auler   for (int I = 0; I < D.NumEdges; ++I) {
93116a497c6SRafael Auler     const uint32_t Src = D.Edges[I].FromNode;
93216a497c6SRafael Auler     const uint32_t Dst = D.Edges[I].ToNode;
933cc4b2fb6SRafael Auler     Edge *E = &CFGNodes[Src].OutEdges[CFGNodes[Src].NumOutEdges++];
934cc4b2fb6SRafael Auler     E->Node = Dst;
935cc4b2fb6SRafael Auler     E->ID = I;
936cc4b2fb6SRafael Auler 
937cc4b2fb6SRafael Auler     E = &CFGNodes[Dst].InEdges[CFGNodes[Dst].NumInEdges++];
938cc4b2fb6SRafael Auler     E->Node = Src;
939cc4b2fb6SRafael Auler     E->ID = I;
940cc4b2fb6SRafael Auler 
94116a497c6SRafael Auler     if (D.Edges[I].Counter != 0xffffffff)
942cc4b2fb6SRafael Auler       continue;
943cc4b2fb6SRafael Auler 
944cc4b2fb6SRafael Auler     E = &SpanningTreeNodes[Src]
945cc4b2fb6SRafael Auler              .OutEdges[SpanningTreeNodes[Src].NumOutEdges++];
946cc4b2fb6SRafael Auler     E->Node = Dst;
947cc4b2fb6SRafael Auler     E->ID = I;
948cc4b2fb6SRafael Auler 
949cc4b2fb6SRafael Auler     E = &SpanningTreeNodes[Dst]
950cc4b2fb6SRafael Auler              .InEdges[SpanningTreeNodes[Dst].NumInEdges++];
951cc4b2fb6SRafael Auler     E->Node = Src;
952cc4b2fb6SRafael Auler     E->ID = I;
953cc4b2fb6SRafael Auler   }
95416a497c6SRafael Auler 
95516a497c6SRafael Auler   computeEdgeFrequencies(Counters, Ctx);
956cc4b2fb6SRafael Auler }
957cc4b2fb6SRafael Auler 
958cc4b2fb6SRafael Auler Graph::~Graph() {
95916a497c6SRafael Auler   if (CallFreqs)
96016a497c6SRafael Auler     Alloc.deallocate(CallFreqs);
96116a497c6SRafael Auler   if (EdgeFreqs)
96216a497c6SRafael Auler     Alloc.deallocate(EdgeFreqs);
963cc4b2fb6SRafael Auler   for (int I = NumNodes - 1; I >= 0; --I) {
964cc4b2fb6SRafael Auler     if (SpanningTreeNodes[I].OutEdges)
965cc4b2fb6SRafael Auler       Alloc.deallocate(SpanningTreeNodes[I].OutEdges);
966cc4b2fb6SRafael Auler     if (SpanningTreeNodes[I].InEdges)
967cc4b2fb6SRafael Auler       Alloc.deallocate(SpanningTreeNodes[I].InEdges);
968cc4b2fb6SRafael Auler     if (CFGNodes[I].OutEdges)
969cc4b2fb6SRafael Auler       Alloc.deallocate(CFGNodes[I].OutEdges);
970cc4b2fb6SRafael Auler     if (CFGNodes[I].InEdges)
971cc4b2fb6SRafael Auler       Alloc.deallocate(CFGNodes[I].InEdges);
972cc4b2fb6SRafael Auler   }
973cc4b2fb6SRafael Auler   if (SpanningTreeNodes)
974cc4b2fb6SRafael Auler     Alloc.deallocate(SpanningTreeNodes);
975cc4b2fb6SRafael Auler   if (CFGNodes)
976cc4b2fb6SRafael Auler     Alloc.deallocate(CFGNodes);
977cc4b2fb6SRafael Auler }
978cc4b2fb6SRafael Auler 
979cc4b2fb6SRafael Auler void Graph::dump() const {
980cc4b2fb6SRafael Auler   reportNumber("Dumping graph with number of nodes: ", NumNodes, 10);
981cc4b2fb6SRafael Auler   report("  Full graph:\n");
982cc4b2fb6SRafael Auler   for (int I = 0; I < NumNodes; ++I) {
983cc4b2fb6SRafael Auler     const Node *N = &CFGNodes[I];
984cc4b2fb6SRafael Auler     reportNumber("    Node #", I, 10);
985cc4b2fb6SRafael Auler     reportNumber("      InEdges total ", N->NumInEdges, 10);
986cc4b2fb6SRafael Auler     for (int J = 0; J < N->NumInEdges; ++J)
987cc4b2fb6SRafael Auler       reportNumber("        ", N->InEdges[J].Node, 10);
988cc4b2fb6SRafael Auler     reportNumber("      OutEdges total ", N->NumOutEdges, 10);
989cc4b2fb6SRafael Auler     for (int J = 0; J < N->NumOutEdges; ++J)
990cc4b2fb6SRafael Auler       reportNumber("        ", N->OutEdges[J].Node, 10);
991cc4b2fb6SRafael Auler     report("\n");
992cc4b2fb6SRafael Auler   }
993cc4b2fb6SRafael Auler   report("  Spanning tree:\n");
994cc4b2fb6SRafael Auler   for (int I = 0; I < NumNodes; ++I) {
995cc4b2fb6SRafael Auler     const Node *N = &SpanningTreeNodes[I];
996cc4b2fb6SRafael Auler     reportNumber("    Node #", I, 10);
997cc4b2fb6SRafael Auler     reportNumber("      InEdges total ", N->NumInEdges, 10);
998cc4b2fb6SRafael Auler     for (int J = 0; J < N->NumInEdges; ++J)
999cc4b2fb6SRafael Auler       reportNumber("        ", N->InEdges[J].Node, 10);
1000cc4b2fb6SRafael Auler     reportNumber("      OutEdges total ", N->NumOutEdges, 10);
1001cc4b2fb6SRafael Auler     for (int J = 0; J < N->NumOutEdges; ++J)
1002cc4b2fb6SRafael Auler       reportNumber("        ", N->OutEdges[J].Node, 10);
1003cc4b2fb6SRafael Auler     report("\n");
1004cc4b2fb6SRafael Auler   }
1005cc4b2fb6SRafael Auler }
1006cc4b2fb6SRafael Auler 
100716a497c6SRafael Auler void Graph::dumpEdgeFreqs() const {
100816a497c6SRafael Auler   reportNumber(
100916a497c6SRafael Auler       "Dumping edge frequencies for graph with num edges: ", D.NumEdges, 10);
101016a497c6SRafael Auler   for (int I = 0; I < D.NumEdges; ++I) {
101116a497c6SRafael Auler     reportNumber("* Src: ", D.Edges[I].FromNode, 10);
101216a497c6SRafael Auler     reportNumber("  Dst: ", D.Edges[I].ToNode, 10);
1013cc4b2fb6SRafael Auler     reportNumber("    Cnt: ", EdgeFreqs[I], 10);
1014cc4b2fb6SRafael Auler   }
1015cc4b2fb6SRafael Auler }
1016cc4b2fb6SRafael Auler 
101716a497c6SRafael Auler /// Auxiliary map structure for fast lookups of which calls map to each node of
101816a497c6SRafael Auler /// the function CFG
101916a497c6SRafael Auler struct NodeToCallsMap {
102016a497c6SRafael Auler   struct MapEntry {
102116a497c6SRafael Auler     uint32_t NumCalls;
102216a497c6SRafael Auler     uint32_t *Calls;
102316a497c6SRafael Auler   };
102416a497c6SRafael Auler   MapEntry *Entries;
102516a497c6SRafael Auler   BumpPtrAllocator &Alloc;
102616a497c6SRafael Auler   const uint32_t NumNodes;
1027cc4b2fb6SRafael Auler 
102816a497c6SRafael Auler   NodeToCallsMap(BumpPtrAllocator &Alloc, const FunctionDescription &D,
102916a497c6SRafael Auler                  uint32_t NumNodes)
103016a497c6SRafael Auler       : Alloc(Alloc), NumNodes(NumNodes) {
103116a497c6SRafael Auler     Entries = new (Alloc, 0) MapEntry[NumNodes];
103216a497c6SRafael Auler     for (int I = 0; I < D.NumCalls; ++I) {
103316a497c6SRafael Auler       DEBUG(reportNumber("Registering call in node ", D.Calls[I].FromNode, 10));
103416a497c6SRafael Auler       ++Entries[D.Calls[I].FromNode].NumCalls;
103516a497c6SRafael Auler     }
103616a497c6SRafael Auler     for (int I = 0; I < NumNodes; ++I) {
103716a497c6SRafael Auler       Entries[I].Calls = Entries[I].NumCalls ? new (Alloc)
103816a497c6SRafael Auler                                                    uint32_t[Entries[I].NumCalls]
103916a497c6SRafael Auler                                              : nullptr;
104016a497c6SRafael Auler       Entries[I].NumCalls = 0;
104116a497c6SRafael Auler     }
104216a497c6SRafael Auler     for (int I = 0; I < D.NumCalls; ++I) {
1043c7306cc2SAmir Ayupov       MapEntry &Entry = Entries[D.Calls[I].FromNode];
104416a497c6SRafael Auler       Entry.Calls[Entry.NumCalls++] = I;
104516a497c6SRafael Auler     }
104616a497c6SRafael Auler   }
104716a497c6SRafael Auler 
104816a497c6SRafael Auler   /// Set the frequency of all calls in node \p NodeID to Freq. However, if
104916a497c6SRafael Auler   /// the calls have their own counters and do not depend on the basic block
105016a497c6SRafael Auler   /// counter, this means they have landing pads and throw exceptions. In this
105116a497c6SRafael Auler   /// case, set their frequency with their counters and return the maximum
105216a497c6SRafael Auler   /// value observed in such counters. This will be used as the new frequency
105316a497c6SRafael Auler   /// at basic block entry. This is used to fix the CFG edge frequencies in the
105416a497c6SRafael Auler   /// presence of exceptions.
105516a497c6SRafael Auler   uint64_t visitAllCallsIn(uint32_t NodeID, uint64_t Freq, uint64_t *CallFreqs,
105616a497c6SRafael Auler                            const FunctionDescription &D,
105716a497c6SRafael Auler                            const uint64_t *Counters,
105816a497c6SRafael Auler                            ProfileWriterContext &Ctx) const {
1059c7306cc2SAmir Ayupov     const MapEntry &Entry = Entries[NodeID];
106016a497c6SRafael Auler     uint64_t MaxValue = 0ull;
106116a497c6SRafael Auler     for (int I = 0, E = Entry.NumCalls; I != E; ++I) {
1062c7306cc2SAmir Ayupov       const uint32_t CallID = Entry.Calls[I];
106316a497c6SRafael Auler       DEBUG(reportNumber("  Setting freq for call ID: ", CallID, 10));
1064c7306cc2SAmir Ayupov       const CallDescription &CallDesc = D.Calls[CallID];
106516a497c6SRafael Auler       if (CallDesc.Counter == 0xffffffff) {
106616a497c6SRafael Auler         CallFreqs[CallID] = Freq;
106716a497c6SRafael Auler         DEBUG(reportNumber("  with : ", Freq, 10));
106816a497c6SRafael Auler       } else {
1069c7306cc2SAmir Ayupov         const uint64_t CounterVal = Counters[CallDesc.Counter];
107016a497c6SRafael Auler         CallFreqs[CallID] = CounterVal;
107116a497c6SRafael Auler         MaxValue = CounterVal > MaxValue ? CounterVal : MaxValue;
107216a497c6SRafael Auler         DEBUG(reportNumber("  with (private counter) : ", CounterVal, 10));
107316a497c6SRafael Auler       }
107416a497c6SRafael Auler       DEBUG(reportNumber("  Address: 0x", CallDesc.TargetAddress, 16));
107516a497c6SRafael Auler       if (CallFreqs[CallID] > 0)
107616a497c6SRafael Auler         Ctx.CallFlowTable->get(CallDesc.TargetAddress).Calls +=
107716a497c6SRafael Auler             CallFreqs[CallID];
107816a497c6SRafael Auler     }
107916a497c6SRafael Auler     return MaxValue;
108016a497c6SRafael Auler   }
108116a497c6SRafael Auler 
108216a497c6SRafael Auler   ~NodeToCallsMap() {
1083883bf0e8SAmir Ayupov     for (int I = NumNodes - 1; I >= 0; --I)
108416a497c6SRafael Auler       if (Entries[I].Calls)
108516a497c6SRafael Auler         Alloc.deallocate(Entries[I].Calls);
108616a497c6SRafael Auler     Alloc.deallocate(Entries);
108716a497c6SRafael Auler   }
108816a497c6SRafael Auler };
108916a497c6SRafael Auler 
109016a497c6SRafael Auler /// Fill an array with the frequency of each edge in the function represented
109116a497c6SRafael Auler /// by G, as well as another array for each call.
109216a497c6SRafael Auler void Graph::computeEdgeFrequencies(const uint64_t *Counters,
109316a497c6SRafael Auler                                    ProfileWriterContext &Ctx) {
109416a497c6SRafael Auler   if (NumNodes == 0)
109516a497c6SRafael Auler     return;
109616a497c6SRafael Auler 
109716a497c6SRafael Auler   EdgeFreqs = D.NumEdges ? new (Alloc, 0) uint64_t [D.NumEdges] : nullptr;
109816a497c6SRafael Auler   CallFreqs = D.NumCalls ? new (Alloc, 0) uint64_t [D.NumCalls] : nullptr;
109916a497c6SRafael Auler 
110016a497c6SRafael Auler   // Setup a lookup for calls present in each node (BB)
110116a497c6SRafael Auler   NodeToCallsMap *CallMap = new (Alloc) NodeToCallsMap(Alloc, D, NumNodes);
1102cc4b2fb6SRafael Auler 
1103cc4b2fb6SRafael Auler   // Perform a bottom-up, BFS traversal of the spanning tree in G. Edges in the
1104cc4b2fb6SRafael Auler   // spanning tree don't have explicit counters. We must infer their value using
1105cc4b2fb6SRafael Auler   // a linear combination of other counters (sum of counters of the outgoing
1106cc4b2fb6SRafael Auler   // edges minus sum of counters of the incoming edges).
110716a497c6SRafael Auler   uint32_t *Stack = new (Alloc) uint32_t [NumNodes];
1108cc4b2fb6SRafael Auler   uint32_t StackTop = 0;
1109cc4b2fb6SRafael Auler   enum Status : uint8_t { S_NEW = 0, S_VISITING, S_VISITED };
111016a497c6SRafael Auler   Status *Visited = new (Alloc, 0) Status[NumNodes];
111116a497c6SRafael Auler   uint64_t *LeafFrequency = new (Alloc, 0) uint64_t[NumNodes];
111216a497c6SRafael Auler   uint64_t *EntryAddress = new (Alloc, 0) uint64_t[NumNodes];
1113cc4b2fb6SRafael Auler 
1114cc4b2fb6SRafael Auler   // Setup a fast lookup for frequency of leaf nodes, which have special
1115cc4b2fb6SRafael Auler   // basic block frequency instrumentation (they are not edge profiled).
111616a497c6SRafael Auler   for (int I = 0; I < D.NumLeafNodes; ++I) {
111716a497c6SRafael Auler     LeafFrequency[D.LeafNodes[I].Node] = Counters[D.LeafNodes[I].Counter];
1118cc4b2fb6SRafael Auler     DEBUG({
111916a497c6SRafael Auler       if (Counters[D.LeafNodes[I].Counter] > 0) {
112016a497c6SRafael Auler         reportNumber("Leaf Node# ", D.LeafNodes[I].Node, 10);
112116a497c6SRafael Auler         reportNumber("     Counter: ", Counters[D.LeafNodes[I].Counter], 10);
1122cc4b2fb6SRafael Auler       }
1123cc4b2fb6SRafael Auler     });
112416a497c6SRafael Auler   }
112516a497c6SRafael Auler   for (int I = 0; I < D.NumEntryNodes; ++I) {
112616a497c6SRafael Auler     EntryAddress[D.EntryNodes[I].Node] = D.EntryNodes[I].Address;
112716a497c6SRafael Auler     DEBUG({
112816a497c6SRafael Auler         reportNumber("Entry Node# ", D.EntryNodes[I].Node, 10);
112916a497c6SRafael Auler         reportNumber("      Address: ", D.EntryNodes[I].Address, 16);
113016a497c6SRafael Auler     });
1131cc4b2fb6SRafael Auler   }
1132cc4b2fb6SRafael Auler   // Add all root nodes to the stack
1133883bf0e8SAmir Ayupov   for (int I = 0; I < NumNodes; ++I)
113416a497c6SRafael Auler     if (SpanningTreeNodes[I].NumInEdges == 0)
1135cc4b2fb6SRafael Auler       Stack[StackTop++] = I;
1136883bf0e8SAmir Ayupov 
1137cc4b2fb6SRafael Auler   // Empty stack?
1138cc4b2fb6SRafael Auler   if (StackTop == 0) {
113916a497c6SRafael Auler     DEBUG(report("Empty stack!\n"));
114016a497c6SRafael Auler     Alloc.deallocate(EntryAddress);
1141cc4b2fb6SRafael Auler     Alloc.deallocate(LeafFrequency);
1142cc4b2fb6SRafael Auler     Alloc.deallocate(Visited);
1143cc4b2fb6SRafael Auler     Alloc.deallocate(Stack);
114416a497c6SRafael Auler     CallMap->~NodeToCallsMap();
114516a497c6SRafael Auler     Alloc.deallocate(CallMap);
114616a497c6SRafael Auler     if (CallFreqs)
114716a497c6SRafael Auler       Alloc.deallocate(CallFreqs);
114816a497c6SRafael Auler     if (EdgeFreqs)
114916a497c6SRafael Auler       Alloc.deallocate(EdgeFreqs);
115016a497c6SRafael Auler     EdgeFreqs = nullptr;
115116a497c6SRafael Auler     CallFreqs = nullptr;
115216a497c6SRafael Auler     return;
1153cc4b2fb6SRafael Auler   }
1154cc4b2fb6SRafael Auler   // Add all known edge counts, will infer the rest
115516a497c6SRafael Auler   for (int I = 0; I < D.NumEdges; ++I) {
115616a497c6SRafael Auler     const uint32_t C = D.Edges[I].Counter;
1157cc4b2fb6SRafael Auler     if (C == 0xffffffff) // inferred counter - we will compute its value
1158cc4b2fb6SRafael Auler       continue;
115916a497c6SRafael Auler     EdgeFreqs[I] = Counters[C];
1160cc4b2fb6SRafael Auler   }
1161cc4b2fb6SRafael Auler 
1162cc4b2fb6SRafael Auler   while (StackTop > 0) {
1163cc4b2fb6SRafael Auler     const uint32_t Cur = Stack[--StackTop];
1164cc4b2fb6SRafael Auler     DEBUG({
1165cc4b2fb6SRafael Auler       if (Visited[Cur] == S_VISITING)
1166cc4b2fb6SRafael Auler         report("(visiting) ");
1167cc4b2fb6SRafael Auler       else
1168cc4b2fb6SRafael Auler         report("(new) ");
1169cc4b2fb6SRafael Auler       reportNumber("Cur: ", Cur, 10);
1170cc4b2fb6SRafael Auler     });
1171cc4b2fb6SRafael Auler 
1172cc4b2fb6SRafael Auler     // This shouldn't happen in a tree
1173cc4b2fb6SRafael Auler     assert(Visited[Cur] != S_VISITED, "should not have visited nodes in stack");
1174cc4b2fb6SRafael Auler     if (Visited[Cur] == S_NEW) {
1175cc4b2fb6SRafael Auler       Visited[Cur] = S_VISITING;
1176cc4b2fb6SRafael Auler       Stack[StackTop++] = Cur;
117716a497c6SRafael Auler       assert(StackTop <= NumNodes, "stack grew too large");
117816a497c6SRafael Auler       for (int I = 0, E = SpanningTreeNodes[Cur].NumOutEdges; I < E; ++I) {
117916a497c6SRafael Auler         const uint32_t Succ = SpanningTreeNodes[Cur].OutEdges[I].Node;
1180cc4b2fb6SRafael Auler         Stack[StackTop++] = Succ;
118116a497c6SRafael Auler         assert(StackTop <= NumNodes, "stack grew too large");
1182cc4b2fb6SRafael Auler       }
1183cc4b2fb6SRafael Auler       continue;
1184cc4b2fb6SRafael Auler     }
1185cc4b2fb6SRafael Auler     Visited[Cur] = S_VISITED;
1186cc4b2fb6SRafael Auler 
1187cc4b2fb6SRafael Auler     // Establish our node frequency based on outgoing edges, which should all be
1188cc4b2fb6SRafael Auler     // resolved by now.
1189cc4b2fb6SRafael Auler     int64_t CurNodeFreq = LeafFrequency[Cur];
1190cc4b2fb6SRafael Auler     // Not a leaf?
1191cc4b2fb6SRafael Auler     if (!CurNodeFreq) {
119216a497c6SRafael Auler       for (int I = 0, E = CFGNodes[Cur].NumOutEdges; I != E; ++I) {
119316a497c6SRafael Auler         const uint32_t SuccEdge = CFGNodes[Cur].OutEdges[I].ID;
119416a497c6SRafael Auler         CurNodeFreq += EdgeFreqs[SuccEdge];
1195cc4b2fb6SRafael Auler       }
1196cc4b2fb6SRafael Auler     }
119716a497c6SRafael Auler     if (CurNodeFreq < 0)
119816a497c6SRafael Auler       CurNodeFreq = 0;
119916a497c6SRafael Auler 
120016a497c6SRafael Auler     const uint64_t CallFreq = CallMap->visitAllCallsIn(
120116a497c6SRafael Auler         Cur, CurNodeFreq > 0 ? CurNodeFreq : 0, CallFreqs, D, Counters, Ctx);
120216a497c6SRafael Auler 
120316a497c6SRafael Auler     // Exception handling affected our output flow? Fix with calls info
120416a497c6SRafael Auler     DEBUG({
120516a497c6SRafael Auler       if (CallFreq > CurNodeFreq)
120616a497c6SRafael Auler         report("Bumping node frequency with call info\n");
120716a497c6SRafael Auler     });
120816a497c6SRafael Auler     CurNodeFreq = CallFreq > CurNodeFreq ? CallFreq : CurNodeFreq;
120916a497c6SRafael Auler 
121016a497c6SRafael Auler     if (CurNodeFreq > 0) {
121116a497c6SRafael Auler       if (uint64_t Addr = EntryAddress[Cur]) {
121216a497c6SRafael Auler         DEBUG(
121316a497c6SRafael Auler             reportNumber("  Setting flow at entry point address 0x", Addr, 16));
121416a497c6SRafael Auler         DEBUG(reportNumber("  with: ", CurNodeFreq, 10));
121516a497c6SRafael Auler         Ctx.CallFlowTable->get(Addr).Val = CurNodeFreq;
121616a497c6SRafael Auler       }
121716a497c6SRafael Auler     }
121816a497c6SRafael Auler 
121916a497c6SRafael Auler     // No parent? Reached a tree root, limit to call frequency updating.
1220883bf0e8SAmir Ayupov     if (SpanningTreeNodes[Cur].NumInEdges == 0)
122116a497c6SRafael Auler       continue;
122216a497c6SRafael Auler 
122316a497c6SRafael Auler     assert(SpanningTreeNodes[Cur].NumInEdges == 1, "must have 1 parent");
122416a497c6SRafael Auler     const uint32_t Parent = SpanningTreeNodes[Cur].InEdges[0].Node;
122516a497c6SRafael Auler     const uint32_t ParentEdge = SpanningTreeNodes[Cur].InEdges[0].ID;
122616a497c6SRafael Auler 
1227cc4b2fb6SRafael Auler     // Calculate parent edge freq.
122816a497c6SRafael Auler     int64_t ParentEdgeFreq = CurNodeFreq;
122916a497c6SRafael Auler     for (int I = 0, E = CFGNodes[Cur].NumInEdges; I != E; ++I) {
123016a497c6SRafael Auler       const uint32_t PredEdge = CFGNodes[Cur].InEdges[I].ID;
123116a497c6SRafael Auler       ParentEdgeFreq -= EdgeFreqs[PredEdge];
1232cc4b2fb6SRafael Auler     }
123316a497c6SRafael Auler 
1234cc4b2fb6SRafael Auler     // Sometimes the conservative CFG that BOLT builds will lead to incorrect
1235cc4b2fb6SRafael Auler     // flow computation. For example, in a BB that transitively calls the exit
1236cc4b2fb6SRafael Auler     // syscall, BOLT will add a fall-through successor even though it should not
1237cc4b2fb6SRafael Auler     // have any successors. So this block execution will likely be wrong. We
1238cc4b2fb6SRafael Auler     // tolerate this imperfection since this case should be quite infrequent.
1239cc4b2fb6SRafael Auler     if (ParentEdgeFreq < 0) {
124016a497c6SRafael Auler       DEBUG(dumpEdgeFreqs());
1241cc4b2fb6SRafael Auler       DEBUG(report("WARNING: incorrect flow"));
1242cc4b2fb6SRafael Auler       ParentEdgeFreq = 0;
1243cc4b2fb6SRafael Auler     }
1244cc4b2fb6SRafael Auler     DEBUG(reportNumber("  Setting freq for ParentEdge: ", ParentEdge, 10));
1245cc4b2fb6SRafael Auler     DEBUG(reportNumber("  with ParentEdgeFreq: ", ParentEdgeFreq, 10));
124616a497c6SRafael Auler     EdgeFreqs[ParentEdge] = ParentEdgeFreq;
1247cc4b2fb6SRafael Auler   }
1248cc4b2fb6SRafael Auler 
124916a497c6SRafael Auler   Alloc.deallocate(EntryAddress);
1250cc4b2fb6SRafael Auler   Alloc.deallocate(LeafFrequency);
1251cc4b2fb6SRafael Auler   Alloc.deallocate(Visited);
1252cc4b2fb6SRafael Auler   Alloc.deallocate(Stack);
125316a497c6SRafael Auler   CallMap->~NodeToCallsMap();
125416a497c6SRafael Auler   Alloc.deallocate(CallMap);
125516a497c6SRafael Auler   DEBUG(dumpEdgeFreqs());
1256cc4b2fb6SRafael Auler }
1257cc4b2fb6SRafael Auler 
125816a497c6SRafael Auler /// Write to \p FD all of the edge profiles for function \p FuncDesc. Uses
125916a497c6SRafael Auler /// \p Alloc to allocate helper dynamic structures used to compute profile for
126016a497c6SRafael Auler /// edges that we do not explictly instrument.
126116a497c6SRafael Auler const uint8_t *writeFunctionProfile(int FD, ProfileWriterContext &Ctx,
126216a497c6SRafael Auler                                     const uint8_t *FuncDesc,
126316a497c6SRafael Auler                                     BumpPtrAllocator &Alloc) {
126416a497c6SRafael Auler   const FunctionDescription F(FuncDesc);
126516a497c6SRafael Auler   const uint8_t *next = FuncDesc + F.getSize();
1266cc4b2fb6SRafael Auler 
1267a0dd5b05SAlexander Shaposhnikov #if !defined(__APPLE__)
1268a0dd5b05SAlexander Shaposhnikov   uint64_t *bolt_instr_locations = __bolt_instr_locations;
1269a0dd5b05SAlexander Shaposhnikov #else
1270a0dd5b05SAlexander Shaposhnikov   uint64_t *bolt_instr_locations = _bolt_instr_locations_getter();
1271a0dd5b05SAlexander Shaposhnikov #endif
1272a0dd5b05SAlexander Shaposhnikov 
1273cc4b2fb6SRafael Auler   // Skip funcs we know are cold
1274cc4b2fb6SRafael Auler #ifndef ENABLE_DEBUG
127516a497c6SRafael Auler   uint64_t CountersFreq = 0;
1276883bf0e8SAmir Ayupov   for (int I = 0; I < F.NumLeafNodes; ++I)
1277a0dd5b05SAlexander Shaposhnikov     CountersFreq += bolt_instr_locations[F.LeafNodes[I].Counter];
1278883bf0e8SAmir Ayupov 
127916a497c6SRafael Auler   if (CountersFreq == 0) {
128016a497c6SRafael Auler     for (int I = 0; I < F.NumEdges; ++I) {
128116a497c6SRafael Auler       const uint32_t C = F.Edges[I].Counter;
128216a497c6SRafael Auler       if (C == 0xffffffff)
128316a497c6SRafael Auler         continue;
1284a0dd5b05SAlexander Shaposhnikov       CountersFreq += bolt_instr_locations[C];
128516a497c6SRafael Auler     }
128616a497c6SRafael Auler     if (CountersFreq == 0) {
128716a497c6SRafael Auler       for (int I = 0; I < F.NumCalls; ++I) {
128816a497c6SRafael Auler         const uint32_t C = F.Calls[I].Counter;
128916a497c6SRafael Auler         if (C == 0xffffffff)
129016a497c6SRafael Auler           continue;
1291a0dd5b05SAlexander Shaposhnikov         CountersFreq += bolt_instr_locations[C];
129216a497c6SRafael Auler       }
129316a497c6SRafael Auler       if (CountersFreq == 0)
1294cc4b2fb6SRafael Auler         return next;
129516a497c6SRafael Auler     }
129616a497c6SRafael Auler   }
1297cc4b2fb6SRafael Auler #endif
1298cc4b2fb6SRafael Auler 
1299a0dd5b05SAlexander Shaposhnikov   Graph *G = new (Alloc) Graph(Alloc, F, bolt_instr_locations, Ctx);
1300cc4b2fb6SRafael Auler   DEBUG(G->dump());
1301a0dd5b05SAlexander Shaposhnikov 
130216a497c6SRafael Auler   if (!G->EdgeFreqs && !G->CallFreqs) {
1303cc4b2fb6SRafael Auler     G->~Graph();
1304cc4b2fb6SRafael Auler     Alloc.deallocate(G);
1305cc4b2fb6SRafael Auler     return next;
1306cc4b2fb6SRafael Auler   }
1307cc4b2fb6SRafael Auler 
130816a497c6SRafael Auler   for (int I = 0; I < F.NumEdges; ++I) {
130916a497c6SRafael Auler     const uint64_t Freq = G->EdgeFreqs[I];
1310cc4b2fb6SRafael Auler     if (Freq == 0)
1311cc4b2fb6SRafael Auler       continue;
131216a497c6SRafael Auler     const EdgeDescription *Desc = &F.Edges[I];
1313cc4b2fb6SRafael Auler     char LineBuf[BufSize];
1314cc4b2fb6SRafael Auler     char *Ptr = LineBuf;
131516a497c6SRafael Auler     Ptr = serializeLoc(Ctx, Ptr, Desc->From, BufSize);
131616a497c6SRafael Auler     Ptr = serializeLoc(Ctx, Ptr, Desc->To, BufSize - (Ptr - LineBuf));
1317cc4b2fb6SRafael Auler     Ptr = strCopy(Ptr, "0 ", BufSize - (Ptr - LineBuf) - 22);
1318cc4b2fb6SRafael Auler     Ptr = intToStr(Ptr, Freq, 10);
1319cc4b2fb6SRafael Auler     *Ptr++ = '\n';
1320cc4b2fb6SRafael Auler     __write(FD, LineBuf, Ptr - LineBuf);
1321cc4b2fb6SRafael Auler   }
1322cc4b2fb6SRafael Auler 
132316a497c6SRafael Auler   for (int I = 0; I < F.NumCalls; ++I) {
132416a497c6SRafael Auler     const uint64_t Freq = G->CallFreqs[I];
132516a497c6SRafael Auler     if (Freq == 0)
132616a497c6SRafael Auler       continue;
132716a497c6SRafael Auler     char LineBuf[BufSize];
132816a497c6SRafael Auler     char *Ptr = LineBuf;
132916a497c6SRafael Auler     const CallDescription *Desc = &F.Calls[I];
133016a497c6SRafael Auler     Ptr = serializeLoc(Ctx, Ptr, Desc->From, BufSize);
133116a497c6SRafael Auler     Ptr = serializeLoc(Ctx, Ptr, Desc->To, BufSize - (Ptr - LineBuf));
133216a497c6SRafael Auler     Ptr = strCopy(Ptr, "0 ", BufSize - (Ptr - LineBuf) - 25);
133316a497c6SRafael Auler     Ptr = intToStr(Ptr, Freq, 10);
133416a497c6SRafael Auler     *Ptr++ = '\n';
133516a497c6SRafael Auler     __write(FD, LineBuf, Ptr - LineBuf);
133616a497c6SRafael Auler   }
133716a497c6SRafael Auler 
1338cc4b2fb6SRafael Auler   G->~Graph();
1339cc4b2fb6SRafael Auler   Alloc.deallocate(G);
1340cc4b2fb6SRafael Auler   return next;
1341cc4b2fb6SRafael Auler }
1342cc4b2fb6SRafael Auler 
1343a0dd5b05SAlexander Shaposhnikov #if !defined(__APPLE__)
134416a497c6SRafael Auler const IndCallTargetDescription *
134516a497c6SRafael Auler ProfileWriterContext::lookupIndCallTarget(uint64_t Target) const {
134616a497c6SRafael Auler   uint32_t B = 0;
134716a497c6SRafael Auler   uint32_t E = __bolt_instr_num_ind_targets;
134816a497c6SRafael Auler   if (E == 0)
134916a497c6SRafael Auler     return nullptr;
135016a497c6SRafael Auler   do {
135116a497c6SRafael Auler     uint32_t I = (E - B) / 2 + B;
135216a497c6SRafael Auler     if (IndCallTargets[I].Address == Target)
135316a497c6SRafael Auler       return &IndCallTargets[I];
135416a497c6SRafael Auler     if (IndCallTargets[I].Address < Target)
135516a497c6SRafael Auler       B = I + 1;
135616a497c6SRafael Auler     else
135716a497c6SRafael Auler       E = I;
135816a497c6SRafael Auler   } while (B < E);
135916a497c6SRafael Auler   return nullptr;
1360cc4b2fb6SRafael Auler }
136162aa74f8SRafael Auler 
136216a497c6SRafael Auler /// Write a single indirect call <src, target> pair to the fdata file
136316a497c6SRafael Auler void visitIndCallCounter(IndirectCallHashTable::MapEntry &Entry,
136416a497c6SRafael Auler                          int FD, int CallsiteID,
136516a497c6SRafael Auler                          ProfileWriterContext *Ctx) {
136616a497c6SRafael Auler   if (Entry.Val == 0)
136716a497c6SRafael Auler     return;
136816a497c6SRafael Auler   DEBUG(reportNumber("Target func 0x", Entry.Key, 16));
136916a497c6SRafael Auler   DEBUG(reportNumber("Target freq: ", Entry.Val, 10));
137016a497c6SRafael Auler   const IndCallDescription *CallsiteDesc =
137116a497c6SRafael Auler       &Ctx->IndCallDescriptions[CallsiteID];
137216a497c6SRafael Auler   const IndCallTargetDescription *TargetDesc =
137316a497c6SRafael Auler       Ctx->lookupIndCallTarget(Entry.Key);
137416a497c6SRafael Auler   if (!TargetDesc) {
137516a497c6SRafael Auler     DEBUG(report("Failed to lookup indirect call target\n"));
1376cc4b2fb6SRafael Auler     char LineBuf[BufSize];
137762aa74f8SRafael Auler     char *Ptr = LineBuf;
137816a497c6SRafael Auler     Ptr = serializeLoc(*Ctx, Ptr, *CallsiteDesc, BufSize);
137916a497c6SRafael Auler     Ptr = strCopy(Ptr, "0 [unknown] 0 0 ", BufSize - (Ptr - LineBuf) - 40);
138016a497c6SRafael Auler     Ptr = intToStr(Ptr, Entry.Val, 10);
138116a497c6SRafael Auler     *Ptr++ = '\n';
138216a497c6SRafael Auler     __write(FD, LineBuf, Ptr - LineBuf);
138316a497c6SRafael Auler     return;
138416a497c6SRafael Auler   }
138516a497c6SRafael Auler   Ctx->CallFlowTable->get(TargetDesc->Address).Calls += Entry.Val;
138616a497c6SRafael Auler   char LineBuf[BufSize];
138716a497c6SRafael Auler   char *Ptr = LineBuf;
138816a497c6SRafael Auler   Ptr = serializeLoc(*Ctx, Ptr, *CallsiteDesc, BufSize);
138916a497c6SRafael Auler   Ptr = serializeLoc(*Ctx, Ptr, TargetDesc->Loc, BufSize - (Ptr - LineBuf));
1390cc4b2fb6SRafael Auler   Ptr = strCopy(Ptr, "0 ", BufSize - (Ptr - LineBuf) - 25);
139116a497c6SRafael Auler   Ptr = intToStr(Ptr, Entry.Val, 10);
139262aa74f8SRafael Auler   *Ptr++ = '\n';
1393821480d2SRafael Auler   __write(FD, LineBuf, Ptr - LineBuf);
139462aa74f8SRafael Auler }
1395cc4b2fb6SRafael Auler 
139616a497c6SRafael Auler /// Write to \p FD all of the indirect call profiles.
139716a497c6SRafael Auler void writeIndirectCallProfile(int FD, ProfileWriterContext &Ctx) {
139816a497c6SRafael Auler   for (int I = 0; I < __bolt_instr_num_ind_calls; ++I) {
139916a497c6SRafael Auler     DEBUG(reportNumber("IndCallsite #", I, 10));
140016a497c6SRafael Auler     GlobalIndCallCounters[I].forEachElement(visitIndCallCounter, FD, I, &Ctx);
140116a497c6SRafael Auler   }
140216a497c6SRafael Auler }
140316a497c6SRafael Auler 
140416a497c6SRafael Auler /// Check a single call flow for a callee versus all known callers. If there are
140516a497c6SRafael Auler /// less callers than what the callee expects, write the difference with source
140616a497c6SRafael Auler /// [unknown] in the profile.
140716a497c6SRafael Auler void visitCallFlowEntry(CallFlowHashTable::MapEntry &Entry, int FD,
140816a497c6SRafael Auler                         ProfileWriterContext *Ctx) {
140916a497c6SRafael Auler   DEBUG(reportNumber("Call flow entry address: 0x", Entry.Key, 16));
141016a497c6SRafael Auler   DEBUG(reportNumber("Calls: ", Entry.Calls, 10));
141116a497c6SRafael Auler   DEBUG(reportNumber("Reported entry frequency: ", Entry.Val, 10));
141216a497c6SRafael Auler   DEBUG({
141316a497c6SRafael Auler     if (Entry.Calls > Entry.Val)
141416a497c6SRafael Auler       report("  More calls than expected!\n");
141516a497c6SRafael Auler   });
141616a497c6SRafael Auler   if (Entry.Val <= Entry.Calls)
141716a497c6SRafael Auler     return;
141816a497c6SRafael Auler   DEBUG(reportNumber(
141916a497c6SRafael Auler       "  Balancing calls with traffic: ", Entry.Val - Entry.Calls, 10));
142016a497c6SRafael Auler   const IndCallTargetDescription *TargetDesc =
142116a497c6SRafael Auler       Ctx->lookupIndCallTarget(Entry.Key);
142216a497c6SRafael Auler   if (!TargetDesc) {
142316a497c6SRafael Auler     // There is probably something wrong with this callee and this should be
142416a497c6SRafael Auler     // investigated, but I don't want to assert and lose all data collected.
142516a497c6SRafael Auler     DEBUG(report("WARNING: failed to look up call target!\n"));
142616a497c6SRafael Auler     return;
142716a497c6SRafael Auler   }
142816a497c6SRafael Auler   char LineBuf[BufSize];
142916a497c6SRafael Auler   char *Ptr = LineBuf;
143016a497c6SRafael Auler   Ptr = strCopy(Ptr, "0 [unknown] 0 ", BufSize);
143116a497c6SRafael Auler   Ptr = serializeLoc(*Ctx, Ptr, TargetDesc->Loc, BufSize - (Ptr - LineBuf));
143216a497c6SRafael Auler   Ptr = strCopy(Ptr, "0 ", BufSize - (Ptr - LineBuf) - 25);
143316a497c6SRafael Auler   Ptr = intToStr(Ptr, Entry.Val - Entry.Calls, 10);
143416a497c6SRafael Auler   *Ptr++ = '\n';
143516a497c6SRafael Auler   __write(FD, LineBuf, Ptr - LineBuf);
143616a497c6SRafael Auler }
143716a497c6SRafael Auler 
143816a497c6SRafael Auler /// Open fdata file for writing and return a valid file descriptor, aborting
143916a497c6SRafael Auler /// program upon failure.
144016a497c6SRafael Auler int openProfile() {
144116a497c6SRafael Auler   // Build the profile name string by appending our PID
144216a497c6SRafael Auler   char Buf[BufSize];
144316a497c6SRafael Auler   char *Ptr = Buf;
144416a497c6SRafael Auler   uint64_t PID = __getpid();
144516a497c6SRafael Auler   Ptr = strCopy(Buf, __bolt_instr_filename, BufSize);
144616a497c6SRafael Auler   if (__bolt_instr_use_pid) {
144716a497c6SRafael Auler     Ptr = strCopy(Ptr, ".", BufSize - (Ptr - Buf + 1));
144816a497c6SRafael Auler     Ptr = intToStr(Ptr, PID, 10);
144916a497c6SRafael Auler     Ptr = strCopy(Ptr, ".fdata", BufSize - (Ptr - Buf + 1));
145016a497c6SRafael Auler   }
145116a497c6SRafael Auler   *Ptr++ = '\0';
145216a497c6SRafael Auler   uint64_t FD = __open(Buf,
145316a497c6SRafael Auler                        /*flags=*/0x241 /*O_WRONLY|O_TRUNC|O_CREAT*/,
145416a497c6SRafael Auler                        /*mode=*/0666);
145516a497c6SRafael Auler   if (static_cast<int64_t>(FD) < 0) {
145616a497c6SRafael Auler     report("Error while trying to open profile file for writing: ");
145716a497c6SRafael Auler     report(Buf);
145816a497c6SRafael Auler     reportNumber("\nFailed with error number: 0x",
145916a497c6SRafael Auler                  0 - static_cast<int64_t>(FD), 16);
146016a497c6SRafael Auler     __exit(1);
146116a497c6SRafael Auler   }
146216a497c6SRafael Auler   return FD;
146316a497c6SRafael Auler }
1464a0dd5b05SAlexander Shaposhnikov 
1465a0dd5b05SAlexander Shaposhnikov #endif
1466a0dd5b05SAlexander Shaposhnikov 
146716a497c6SRafael Auler } // anonymous namespace
146816a497c6SRafael Auler 
1469a0dd5b05SAlexander Shaposhnikov #if !defined(__APPLE__)
1470a0dd5b05SAlexander Shaposhnikov 
147116a497c6SRafael Auler /// Reset all counters in case you want to start profiling a new phase of your
147216a497c6SRafael Auler /// program independently of prior phases.
147316a497c6SRafael Auler /// The address of this function is printed by BOLT and this can be called by
147416a497c6SRafael Auler /// any attached debugger during runtime. There is a useful oneliner for gdb:
147516a497c6SRafael Auler ///
147616a497c6SRafael Auler ///   gdb -p $(pgrep -xo PROCESSNAME) -ex 'p ((void(*)())0xdeadbeef)()' \
147716a497c6SRafael Auler ///     -ex 'set confirm off' -ex quit
147816a497c6SRafael Auler ///
147916a497c6SRafael Auler /// Where 0xdeadbeef is this function address and PROCESSNAME your binary file
148016a497c6SRafael Auler /// name.
148116a497c6SRafael Auler extern "C" void __bolt_instr_clear_counters() {
1482ea2182feSMaksim Panchenko   memset(reinterpret_cast<char *>(__bolt_instr_locations), 0,
148316a497c6SRafael Auler          __bolt_num_counters * 8);
1484883bf0e8SAmir Ayupov   for (int I = 0; I < __bolt_instr_num_ind_calls; ++I)
148516a497c6SRafael Auler     GlobalIndCallCounters[I].resetCounters();
148616a497c6SRafael Auler }
148716a497c6SRafael Auler 
148816a497c6SRafael Auler /// This is the entry point for profile writing.
148916a497c6SRafael Auler /// There are three ways of getting here:
149016a497c6SRafael Auler ///
149116a497c6SRafael Auler ///  * Program execution ended, finalization methods are running and BOLT
149216a497c6SRafael Auler ///    hooked into FINI from your binary dynamic section;
149316a497c6SRafael Auler ///  * You used the sleep timer option and during initialization we forked
149416a497c6SRafael Auler ///    a separete process that will call this function periodically;
149516a497c6SRafael Auler ///  * BOLT prints this function address so you can attach a debugger and
149616a497c6SRafael Auler ///    call this function directly to get your profile written to disk
149716a497c6SRafael Auler ///    on demand.
149816a497c6SRafael Auler ///
1499ad79d517SVasily Leonenko extern "C" void __attribute((force_align_arg_pointer))
1500ad79d517SVasily Leonenko __bolt_instr_data_dump() {
150116a497c6SRafael Auler   // Already dumping
150216a497c6SRafael Auler   if (!GlobalWriteProfileMutex->acquire())
150316a497c6SRafael Auler     return;
150416a497c6SRafael Auler 
150516a497c6SRafael Auler   BumpPtrAllocator HashAlloc;
150616a497c6SRafael Auler   HashAlloc.setMaxSize(0x6400000);
150716a497c6SRafael Auler   ProfileWriterContext Ctx = readDescriptions();
150816a497c6SRafael Auler   Ctx.CallFlowTable = new (HashAlloc, 0) CallFlowHashTable(HashAlloc);
150916a497c6SRafael Auler 
151016a497c6SRafael Auler   DEBUG(printStats(Ctx));
151116a497c6SRafael Auler 
151216a497c6SRafael Auler   int FD = openProfile();
151316a497c6SRafael Auler 
1514cc4b2fb6SRafael Auler   BumpPtrAllocator Alloc;
1515eaf1b566SJakub Beránek   Alloc.setMaxSize(0x6400000);
151616a497c6SRafael Auler   const uint8_t *FuncDesc = Ctx.FuncDescriptions;
1517cc4b2fb6SRafael Auler   for (int I = 0, E = __bolt_instr_num_funcs; I < E; ++I) {
151816a497c6SRafael Auler     FuncDesc = writeFunctionProfile(FD, Ctx, FuncDesc, Alloc);
151916a497c6SRafael Auler     Alloc.clear();
1520cc4b2fb6SRafael Auler     DEBUG(reportNumber("FuncDesc now: ", (uint64_t)FuncDesc, 16));
1521cc4b2fb6SRafael Auler   }
152216a497c6SRafael Auler   assert(FuncDesc == (void *)Ctx.Strings,
1523cc4b2fb6SRafael Auler          "FuncDesc ptr must be equal to stringtable");
1524cc4b2fb6SRafael Auler 
152516a497c6SRafael Auler   writeIndirectCallProfile(FD, Ctx);
152616a497c6SRafael Auler   Ctx.CallFlowTable->forEachElement(visitCallFlowEntry, FD, &Ctx);
152716a497c6SRafael Auler 
1528dcdd37fdSVladislav Khmelevsky   __fsync(FD);
1529821480d2SRafael Auler   __close(FD);
153016a497c6SRafael Auler   __munmap(Ctx.MMapPtr, Ctx.MMapSize);
153116a497c6SRafael Auler   __close(Ctx.FileDesc);
153216a497c6SRafael Auler   HashAlloc.destroy();
153316a497c6SRafael Auler   GlobalWriteProfileMutex->release();
153416a497c6SRafael Auler   DEBUG(report("Finished writing profile.\n"));
153516a497c6SRafael Auler }
153616a497c6SRafael Auler 
153716a497c6SRafael Auler /// Event loop for our child process spawned during setup to dump profile data
153816a497c6SRafael Auler /// at user-specified intervals
153916a497c6SRafael Auler void watchProcess() {
154016a497c6SRafael Auler   timespec ts, rem;
154116a497c6SRafael Auler   uint64_t Ellapsed = 0ull;
154276d346caSVladislav Khmelevsky   uint64_t ppid;
154376d346caSVladislav Khmelevsky   if (__bolt_instr_wait_forks) {
154476d346caSVladislav Khmelevsky     // Store parent pgid
154576d346caSVladislav Khmelevsky     ppid = -__getpgid(0);
154676d346caSVladislav Khmelevsky     // And leave parent process group
154776d346caSVladislav Khmelevsky     __setpgid(0, 0);
154876d346caSVladislav Khmelevsky   } else {
154976d346caSVladislav Khmelevsky     // Store parent pid
155076d346caSVladislav Khmelevsky     ppid = __getppid();
155176d346caSVladislav Khmelevsky     if (ppid == 1) {
155276d346caSVladislav Khmelevsky       // Parent already dead
1553dcdd37fdSVladislav Khmelevsky       __bolt_instr_data_dump();
155476d346caSVladislav Khmelevsky       goto out;
155576d346caSVladislav Khmelevsky     }
155676d346caSVladislav Khmelevsky   }
155776d346caSVladislav Khmelevsky 
155816a497c6SRafael Auler   ts.tv_sec = 1;
155916a497c6SRafael Auler   ts.tv_nsec = 0;
156016a497c6SRafael Auler   while (1) {
156116a497c6SRafael Auler     __nanosleep(&ts, &rem);
156276d346caSVladislav Khmelevsky     // This means our parent process or all its forks are dead,
156376d346caSVladislav Khmelevsky     // so no need for us to keep dumping.
156476d346caSVladislav Khmelevsky     if (__kill(ppid, 0) < 0) {
156576d346caSVladislav Khmelevsky       if (__bolt_instr_no_counters_clear)
156676d346caSVladislav Khmelevsky         __bolt_instr_data_dump();
156716a497c6SRafael Auler       break;
156816a497c6SRafael Auler     }
156976d346caSVladislav Khmelevsky 
157016a497c6SRafael Auler     if (++Ellapsed < __bolt_instr_sleep_time)
157116a497c6SRafael Auler       continue;
157276d346caSVladislav Khmelevsky 
157316a497c6SRafael Auler     Ellapsed = 0;
157416a497c6SRafael Auler     __bolt_instr_data_dump();
157576d346caSVladislav Khmelevsky     if (__bolt_instr_no_counters_clear == false)
157616a497c6SRafael Auler       __bolt_instr_clear_counters();
157716a497c6SRafael Auler   }
157876d346caSVladislav Khmelevsky 
157976d346caSVladislav Khmelevsky out:;
158016a497c6SRafael Auler   DEBUG(report("My parent process is dead, bye!\n"));
158116a497c6SRafael Auler   __exit(0);
158216a497c6SRafael Auler }
158316a497c6SRafael Auler 
158416a497c6SRafael Auler extern "C" void __bolt_instr_indirect_call();
158516a497c6SRafael Auler extern "C" void __bolt_instr_indirect_tailcall();
158616a497c6SRafael Auler 
158716a497c6SRafael Auler /// Initialization code
1588ad79d517SVasily Leonenko extern "C" void __attribute((force_align_arg_pointer)) __bolt_instr_setup() {
158902c3724dSDenis Revunov   __bolt_ind_call_counter_func_pointer = __bolt_instr_indirect_call;
159002c3724dSDenis Revunov   __bolt_ind_tailcall_counter_func_pointer = __bolt_instr_indirect_tailcall;
159102c3724dSDenis Revunov 
159216a497c6SRafael Auler   const uint64_t CountersStart =
159316a497c6SRafael Auler       reinterpret_cast<uint64_t>(&__bolt_instr_locations[0]);
159416a497c6SRafael Auler   const uint64_t CountersEnd = alignTo(
159516a497c6SRafael Auler       reinterpret_cast<uint64_t>(&__bolt_instr_locations[__bolt_num_counters]),
159616a497c6SRafael Auler       0x1000);
159716a497c6SRafael Auler   DEBUG(reportNumber("replace mmap start: ", CountersStart, 16));
159816a497c6SRafael Auler   DEBUG(reportNumber("replace mmap stop: ", CountersEnd, 16));
159916a497c6SRafael Auler   assert(CountersEnd > CountersStart, "no counters");
160002c3724dSDenis Revunov 
160102c3724dSDenis Revunov   const bool Shared = !__bolt_instr_use_pid;
160202c3724dSDenis Revunov   const uint64_t MapPrivateOrShared = Shared ? MAP_SHARED : MAP_PRIVATE;
160302c3724dSDenis Revunov 
1604f0b45fbaSDenis Revunov   void *Ret =
1605f0b45fbaSDenis Revunov       __mmap(CountersStart, CountersEnd - CountersStart, PROT_READ | PROT_WRITE,
160602c3724dSDenis Revunov              MAP_ANONYMOUS | MapPrivateOrShared | MAP_FIXED, -1, 0);
16078f7c53efSDenis Revunov   assert(Ret != MAP_FAILED, "__bolt_instr_setup: Failed to mmap counters!");
160802c3724dSDenis Revunov 
1609*4314f4ceSAmir Ayupov   // Conservatively reserve 100MiB shared pages
1610*4314f4ceSAmir Ayupov   GlobalAlloc.setMaxSize(0x6400000);
1611*4314f4ceSAmir Ayupov   GlobalAlloc.setShared(Shared);
1612*4314f4ceSAmir Ayupov   GlobalWriteProfileMutex = new (GlobalAlloc, 0) Mutex();
161316a497c6SRafael Auler   if (__bolt_instr_num_ind_calls > 0)
161416a497c6SRafael Auler     GlobalIndCallCounters =
1615*4314f4ceSAmir Ayupov         new (GlobalAlloc, 0) IndirectCallHashTable[__bolt_instr_num_ind_calls];
161616a497c6SRafael Auler 
161716a497c6SRafael Auler   if (__bolt_instr_sleep_time != 0) {
161876d346caSVladislav Khmelevsky     // Separate instrumented process to the own process group
161976d346caSVladislav Khmelevsky     if (__bolt_instr_wait_forks)
162076d346caSVladislav Khmelevsky       __setpgid(0, 0);
162176d346caSVladislav Khmelevsky 
1622c7306cc2SAmir Ayupov     if (long PID = __fork())
162316a497c6SRafael Auler       return;
162416a497c6SRafael Auler     watchProcess();
162516a497c6SRafael Auler   }
162616a497c6SRafael Auler }
162716a497c6SRafael Auler 
1628361f3b55SVladislav Khmelevsky extern "C" __attribute((force_align_arg_pointer)) void
1629361f3b55SVladislav Khmelevsky instrumentIndirectCall(uint64_t Target, uint64_t IndCallID) {
1630*4314f4ceSAmir Ayupov   GlobalIndCallCounters[IndCallID].incrementVal(Target, GlobalAlloc);
163116a497c6SRafael Auler }
163216a497c6SRafael Auler 
163316a497c6SRafael Auler /// We receive as in-stack arguments the identifier of the indirect call site
163416a497c6SRafael Auler /// as well as the target address for the call
163516a497c6SRafael Auler extern "C" __attribute((naked)) void __bolt_instr_indirect_call()
163616a497c6SRafael Auler {
163716a497c6SRafael Auler   __asm__ __volatile__(SAVE_ALL
1638361f3b55SVladislav Khmelevsky                        "mov 0xa0(%%rsp), %%rdi\n"
1639361f3b55SVladislav Khmelevsky                        "mov 0x98(%%rsp), %%rsi\n"
164016a497c6SRafael Auler                        "call instrumentIndirectCall\n"
164116a497c6SRafael Auler                        RESTORE_ALL
1642361f3b55SVladislav Khmelevsky                        "ret\n"
164316a497c6SRafael Auler                        :::);
164416a497c6SRafael Auler }
164516a497c6SRafael Auler 
164616a497c6SRafael Auler extern "C" __attribute((naked)) void __bolt_instr_indirect_tailcall()
164716a497c6SRafael Auler {
164816a497c6SRafael Auler   __asm__ __volatile__(SAVE_ALL
1649361f3b55SVladislav Khmelevsky                        "mov 0x98(%%rsp), %%rdi\n"
1650361f3b55SVladislav Khmelevsky                        "mov 0x90(%%rsp), %%rsi\n"
165116a497c6SRafael Auler                        "call instrumentIndirectCall\n"
165216a497c6SRafael Auler                        RESTORE_ALL
1653361f3b55SVladislav Khmelevsky                        "ret\n"
165416a497c6SRafael Auler                        :::);
165516a497c6SRafael Auler }
165616a497c6SRafael Auler 
165716a497c6SRafael Auler /// This is hooking ELF's entry, it needs to save all machine state.
165816a497c6SRafael Auler extern "C" __attribute((naked)) void __bolt_instr_start()
165916a497c6SRafael Auler {
166016a497c6SRafael Auler   __asm__ __volatile__(SAVE_ALL
166116a497c6SRafael Auler                        "call __bolt_instr_setup\n"
166216a497c6SRafael Auler                        RESTORE_ALL
1663ad79d517SVasily Leonenko                        "jmp __bolt_start_trampoline\n"
166416a497c6SRafael Auler                        :::);
166516a497c6SRafael Auler }
166616a497c6SRafael Auler 
166716a497c6SRafael Auler /// This is hooking into ELF's DT_FINI
166816a497c6SRafael Auler extern "C" void __bolt_instr_fini() {
1669553f28e9SVladislav Khmelevsky   __bolt_fini_trampoline();
167016a497c6SRafael Auler   if (__bolt_instr_sleep_time == 0)
167116a497c6SRafael Auler     __bolt_instr_data_dump();
167216a497c6SRafael Auler   DEBUG(report("Finished.\n"));
167362aa74f8SRafael Auler }
1674bbd9d610SAlexander Shaposhnikov 
16753b876cc3SAlexander Shaposhnikov #endif
16763b876cc3SAlexander Shaposhnikov 
16773b876cc3SAlexander Shaposhnikov #if defined(__APPLE__)
1678bbd9d610SAlexander Shaposhnikov 
1679a0dd5b05SAlexander Shaposhnikov extern "C" void __bolt_instr_data_dump() {
1680a0dd5b05SAlexander Shaposhnikov   ProfileWriterContext Ctx = readDescriptions();
1681a0dd5b05SAlexander Shaposhnikov 
1682a0dd5b05SAlexander Shaposhnikov   int FD = 2;
1683a0dd5b05SAlexander Shaposhnikov   BumpPtrAllocator Alloc;
1684a0dd5b05SAlexander Shaposhnikov   const uint8_t *FuncDesc = Ctx.FuncDescriptions;
1685a0dd5b05SAlexander Shaposhnikov   uint32_t bolt_instr_num_funcs = _bolt_instr_num_funcs_getter();
1686a0dd5b05SAlexander Shaposhnikov 
1687a0dd5b05SAlexander Shaposhnikov   for (int I = 0, E = bolt_instr_num_funcs; I < E; ++I) {
1688a0dd5b05SAlexander Shaposhnikov     FuncDesc = writeFunctionProfile(FD, Ctx, FuncDesc, Alloc);
1689a0dd5b05SAlexander Shaposhnikov     Alloc.clear();
1690a0dd5b05SAlexander Shaposhnikov     DEBUG(reportNumber("FuncDesc now: ", (uint64_t)FuncDesc, 16));
1691a0dd5b05SAlexander Shaposhnikov   }
1692a0dd5b05SAlexander Shaposhnikov   assert(FuncDesc == (void *)Ctx.Strings,
1693a0dd5b05SAlexander Shaposhnikov          "FuncDesc ptr must be equal to stringtable");
1694a0dd5b05SAlexander Shaposhnikov }
1695a0dd5b05SAlexander Shaposhnikov 
1696bbd9d610SAlexander Shaposhnikov // On OSX/iOS the final symbol name of an extern "C" function/variable contains
1697bbd9d610SAlexander Shaposhnikov // one extra leading underscore: _bolt_instr_setup -> __bolt_instr_setup.
16983b876cc3SAlexander Shaposhnikov extern "C"
16993b876cc3SAlexander Shaposhnikov __attribute__((section("__TEXT,__setup")))
17003b876cc3SAlexander Shaposhnikov __attribute__((force_align_arg_pointer))
17013b876cc3SAlexander Shaposhnikov void _bolt_instr_setup() {
1702a0dd5b05SAlexander Shaposhnikov   __asm__ __volatile__(SAVE_ALL :::);
17033b876cc3SAlexander Shaposhnikov 
1704a0dd5b05SAlexander Shaposhnikov   report("Hello!\n");
17053b876cc3SAlexander Shaposhnikov 
1706a0dd5b05SAlexander Shaposhnikov   __asm__ __volatile__(RESTORE_ALL :::);
17071cf23e5eSAlexander Shaposhnikov }
1708bbd9d610SAlexander Shaposhnikov 
17093b876cc3SAlexander Shaposhnikov extern "C"
17103b876cc3SAlexander Shaposhnikov __attribute__((section("__TEXT,__fini")))
17113b876cc3SAlexander Shaposhnikov __attribute__((force_align_arg_pointer))
17123b876cc3SAlexander Shaposhnikov void _bolt_instr_fini() {
1713a0dd5b05SAlexander Shaposhnikov   report("Bye!\n");
1714a0dd5b05SAlexander Shaposhnikov   __bolt_instr_data_dump();
1715e067f2adSAlexander Shaposhnikov }
1716e067f2adSAlexander Shaposhnikov 
1717bbd9d610SAlexander Shaposhnikov #endif
1718cb8d701bSVladislav Khmelevsky #endif
1719