162aa74f8SRafael Auler //===-- instr.cpp -----------------------------------------------*- C++ -*-===//
262aa74f8SRafael Auler //
3*da752c9cSRafael Auler // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*da752c9cSRafael Auler // See https://llvm.org/LICENSE.txt for license information.
5*da752c9cSRafael Auler // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
662aa74f8SRafael Auler //
762aa74f8SRafael Auler //===----------------------------------------------------------------------===//
862aa74f8SRafael Auler //
916a497c6SRafael Auler // BOLT runtime instrumentation library for x86 Linux. Currently, BOLT does
1016a497c6SRafael Auler // not support linking modules with dependencies on one another into the final
1116a497c6SRafael Auler // binary (TODO?), which means this library has to be self-contained in a single
1216a497c6SRafael Auler // module.
1316a497c6SRafael Auler //
1416a497c6SRafael Auler // All extern declarations here need to be defined by BOLT itself. Those will be
1516a497c6SRafael Auler // undefined symbols that BOLT needs to resolve by emitting these symbols with
1616a497c6SRafael Auler // MCStreamer. Currently, Passes/Instrumentation.cpp is the pass responsible
1716a497c6SRafael Auler // for defining the symbols here and these two files have a tight coupling: one
1816a497c6SRafael Auler // working statically when you run BOLT and another during program runtime when
1916a497c6SRafael Auler // you run an instrumented binary. The main goal here is to output an fdata file
2016a497c6SRafael Auler // (BOLT profile) with the instrumentation counters inserted by the static pass.
2116a497c6SRafael Auler // Counters for indirect calls are an exception, as we can't know them
2216a497c6SRafael Auler // statically. These counters are created and managed here. To allow this, we
2316a497c6SRafael Auler // need a minimal framework for allocating memory dynamically. We provide this
2416a497c6SRafael Auler // with the BumpPtrAllocator class (not LLVM's, but our own version of it).
2516a497c6SRafael Auler //
2616a497c6SRafael Auler // Since this code is intended to be inserted into any executable, we decided to
2716a497c6SRafael Auler // make it standalone and do not depend on any external libraries (i.e. language
2816a497c6SRafael Auler // support libraries, such as glibc or stdc++). To allow this, we provide a few
2916a497c6SRafael Auler // light implementations of common OS interacting functionalities using direct
3016a497c6SRafael Auler // syscall wrappers. Our simple allocator doesn't manage deallocations that
3116a497c6SRafael Auler // fragment the memory space, so it's stack based. This is the minimal framework
3216a497c6SRafael Auler // provided here to allow processing instrumented counters and writing fdata.
3316a497c6SRafael Auler //
3416a497c6SRafael Auler // In the C++ idiom used here, we never use or rely on constructors or
3516a497c6SRafael Auler // destructors for global objects. That's because those need support from the
3616a497c6SRafael Auler // linker in initialization/finalization code, and we want to keep our linker
3716a497c6SRafael Auler // very simple. Similarly, we don't create any global objects that are zero
3816a497c6SRafael Auler // initialized, since those would need to go .bss, which our simple linker also
3916a497c6SRafael Auler // don't support (TODO?).
4062aa74f8SRafael Auler //
4162aa74f8SRafael Auler //===----------------------------------------------------------------------===//
4262aa74f8SRafael Auler 
439bd71615SXun Li #include "common.h"
4462aa74f8SRafael Auler 
4516a497c6SRafael Auler // Enables a very verbose logging to stderr useful when debugging
46cc4b2fb6SRafael Auler //#define ENABLE_DEBUG
47cc4b2fb6SRafael Auler 
48cc4b2fb6SRafael Auler #ifdef ENABLE_DEBUG
49cc4b2fb6SRafael Auler #define DEBUG(X)                                                               \
50cc4b2fb6SRafael Auler   { X; }
51cc4b2fb6SRafael Auler #else
52cc4b2fb6SRafael Auler #define DEBUG(X)                                                               \
53cc4b2fb6SRafael Auler   {}
54cc4b2fb6SRafael Auler #endif
55cc4b2fb6SRafael Auler 
563b876cc3SAlexander Shaposhnikov 
573b876cc3SAlexander Shaposhnikov #if defined(__APPLE__)
583b876cc3SAlexander Shaposhnikov extern "C" {
593b876cc3SAlexander Shaposhnikov extern uint64_t* _bolt_instr_locations_getter();
603b876cc3SAlexander Shaposhnikov extern uint32_t _bolt_num_counters_getter();
613b876cc3SAlexander Shaposhnikov 
62a0dd5b05SAlexander Shaposhnikov extern uint8_t* _bolt_instr_tables_getter();
63a0dd5b05SAlexander Shaposhnikov extern uint32_t _bolt_instr_num_funcs_getter();
643b876cc3SAlexander Shaposhnikov }
653b876cc3SAlexander Shaposhnikov 
663b876cc3SAlexander Shaposhnikov #else
67bbd9d610SAlexander Shaposhnikov 
6816a497c6SRafael Auler // Main counters inserted by instrumentation, incremented during runtime when
6916a497c6SRafael Auler // points of interest (locations) in the program are reached. Those are direct
7016a497c6SRafael Auler // calls and direct and indirect branches (local ones). There are also counters
7116a497c6SRafael Auler // for basic block execution if they are a spanning tree leaf and need to be
7216a497c6SRafael Auler // counted in order to infer the execution count of other edges of the CFG.
7362aa74f8SRafael Auler extern uint64_t __bolt_instr_locations[];
7416a497c6SRafael Auler extern uint32_t __bolt_num_counters;
7516a497c6SRafael Auler // Descriptions are serialized metadata about binary functions written by BOLT,
7616a497c6SRafael Auler // so we have a minimal understanding about the program structure. For a
7716a497c6SRafael Auler // reference on the exact format of this metadata, see *Description structs,
7816a497c6SRafael Auler // Location, IntrumentedNode and EntryNode.
7916a497c6SRafael Auler // Number of indirect call site descriptions
8016a497c6SRafael Auler extern uint32_t __bolt_instr_num_ind_calls;
8116a497c6SRafael Auler // Number of indirect call target descriptions
8216a497c6SRafael Auler extern uint32_t __bolt_instr_num_ind_targets;
83cc4b2fb6SRafael Auler // Number of function descriptions
84cc4b2fb6SRafael Auler extern uint32_t __bolt_instr_num_funcs;
8516a497c6SRafael Auler // Time to sleep across dumps (when we write the fdata profile to disk)
8616a497c6SRafael Auler extern uint32_t __bolt_instr_sleep_time;
87cc4b2fb6SRafael Auler // Filename to dump data to
8862aa74f8SRafael Auler extern char __bolt_instr_filename[];
8916a497c6SRafael Auler // If true, append current PID to the fdata filename when creating it so
9016a497c6SRafael Auler // different invocations of the same program can be differentiated.
9116a497c6SRafael Auler extern bool __bolt_instr_use_pid;
9216a497c6SRafael Auler // Functions that will be used to instrument indirect calls. BOLT static pass
9316a497c6SRafael Auler // will identify indirect calls and modify them to load the address in these
9416a497c6SRafael Auler // trampolines and call this address instead. BOLT can't use direct calls to
9516a497c6SRafael Auler // our handlers because our addresses here are not known at analysis time. We
9616a497c6SRafael Auler // only support resolving dependencies from this file to the output of BOLT,
9716a497c6SRafael Auler // *not* the other way around.
9816a497c6SRafael Auler // TODO: We need better linking support to make that happen.
9916a497c6SRafael Auler extern void (*__bolt_trampoline_ind_call)();
10016a497c6SRafael Auler extern void (*__bolt_trampoline_ind_tailcall)();
10116a497c6SRafael Auler // Function pointers to init/fini routines in the binary, so we can resume
10216a497c6SRafael Auler // regular execution of these functions that we hooked
10316a497c6SRafael Auler extern void (*__bolt_instr_init_ptr)();
10416a497c6SRafael Auler extern void (*__bolt_instr_fini_ptr)();
10562aa74f8SRafael Auler 
106a0dd5b05SAlexander Shaposhnikov #endif
107a0dd5b05SAlexander Shaposhnikov 
108cc4b2fb6SRafael Auler namespace {
109cc4b2fb6SRafael Auler 
110cc4b2fb6SRafael Auler /// A simple allocator that mmaps a fixed size region and manages this space
111cc4b2fb6SRafael Auler /// in a stack fashion, meaning you always deallocate the last element that
11216a497c6SRafael Auler /// was allocated. In practice, we don't need to deallocate individual elements.
11316a497c6SRafael Auler /// We monotonically increase our usage and then deallocate everything once we
11416a497c6SRafael Auler /// are done processing something.
115cc4b2fb6SRafael Auler class BumpPtrAllocator {
11616a497c6SRafael Auler   /// This is written before each allocation and act as a canary to detect when
11716a497c6SRafael Auler   /// a bug caused our program to cross allocation boundaries.
118cc4b2fb6SRafael Auler   struct EntryMetadata {
119cc4b2fb6SRafael Auler     uint64_t Magic;
120cc4b2fb6SRafael Auler     uint64_t AllocSize;
121cc4b2fb6SRafael Auler   };
1229bd71615SXun Li 
123cc4b2fb6SRafael Auler public:
124faaefff6SAlexander Shaposhnikov   void *allocate(size_t Size) {
12516a497c6SRafael Auler     Lock L(M);
126a0dd5b05SAlexander Shaposhnikov 
127cc4b2fb6SRafael Auler     if (StackBase == nullptr) {
128a0dd5b05SAlexander Shaposhnikov #if defined(__APPLE__)
129a0dd5b05SAlexander Shaposhnikov     int MAP_PRIVATE_MAP_ANONYMOUS = 0x1002;
130a0dd5b05SAlexander Shaposhnikov #else
131a0dd5b05SAlexander Shaposhnikov     int MAP_PRIVATE_MAP_ANONYMOUS = 0x22;
132a0dd5b05SAlexander Shaposhnikov #endif
13316a497c6SRafael Auler       StackBase = reinterpret_cast<uint8_t *>(
13416a497c6SRafael Auler           __mmap(0, MaxSize, 0x3 /* PROT_READ | PROT_WRITE*/,
13516a497c6SRafael Auler                  Shared ? 0x21 /*MAP_SHARED | MAP_ANONYMOUS*/
136a0dd5b05SAlexander Shaposhnikov                         : MAP_PRIVATE_MAP_ANONYMOUS /* MAP_PRIVATE | MAP_ANONYMOUS*/,
13716a497c6SRafael Auler                  -1, 0));
138cc4b2fb6SRafael Auler       StackSize = 0;
139cc4b2fb6SRafael Auler     }
140a0dd5b05SAlexander Shaposhnikov 
141cc4b2fb6SRafael Auler     Size = alignTo(Size + sizeof(EntryMetadata), 16);
142cc4b2fb6SRafael Auler     uint8_t *AllocAddress = StackBase + StackSize + sizeof(EntryMetadata);
143cc4b2fb6SRafael Auler     auto *M = reinterpret_cast<EntryMetadata *>(StackBase + StackSize);
14416a497c6SRafael Auler     M->Magic = Magic;
145cc4b2fb6SRafael Auler     M->AllocSize = Size;
146cc4b2fb6SRafael Auler     StackSize += Size;
14716a497c6SRafael Auler     assert(StackSize < MaxSize, "allocator ran out of memory");
148cc4b2fb6SRafael Auler     return AllocAddress;
149cc4b2fb6SRafael Auler   }
150cc4b2fb6SRafael Auler 
15116a497c6SRafael Auler #ifdef DEBUG
15216a497c6SRafael Auler   /// Element-wise deallocation is only used for debugging to catch memory
15316a497c6SRafael Auler   /// bugs by checking magic bytes. Ordinarily, we reset the allocator once
15416a497c6SRafael Auler   /// we are done with it. Reset is done with clear(). There's no need
15516a497c6SRafael Auler   /// to deallocate each element individually.
156cc4b2fb6SRafael Auler   void deallocate(void *Ptr) {
15716a497c6SRafael Auler     Lock L(M);
158cc4b2fb6SRafael Auler     uint8_t MetadataOffset = sizeof(EntryMetadata);
159cc4b2fb6SRafael Auler     auto *M = reinterpret_cast<EntryMetadata *>(
160cc4b2fb6SRafael Auler         reinterpret_cast<uint8_t *>(Ptr) - MetadataOffset);
161cc4b2fb6SRafael Auler     const uint8_t *StackTop = StackBase + StackSize + MetadataOffset;
162cc4b2fb6SRafael Auler     // Validate size
163cc4b2fb6SRafael Auler     if (Ptr != StackTop - M->AllocSize) {
16416a497c6SRafael Auler       // Failed validation, check if it is a pointer returned by operator new []
165cc4b2fb6SRafael Auler       MetadataOffset +=
166cc4b2fb6SRafael Auler           sizeof(uint64_t); // Space for number of elements alloc'ed
167cc4b2fb6SRafael Auler       M = reinterpret_cast<EntryMetadata *>(reinterpret_cast<uint8_t *>(Ptr) -
168cc4b2fb6SRafael Auler                                             MetadataOffset);
16916a497c6SRafael Auler       // Ok, it failed both checks if this assertion fails. Stop the program, we
17016a497c6SRafael Auler       // have a memory bug.
171cc4b2fb6SRafael Auler       assert(Ptr == StackTop - M->AllocSize,
172cc4b2fb6SRafael Auler              "must deallocate the last element alloc'ed");
173cc4b2fb6SRafael Auler     }
17416a497c6SRafael Auler     assert(M->Magic == Magic, "allocator magic is corrupt");
175cc4b2fb6SRafael Auler     StackSize -= M->AllocSize;
176cc4b2fb6SRafael Auler   }
17716a497c6SRafael Auler #else
17816a497c6SRafael Auler   void deallocate(void *) {}
17916a497c6SRafael Auler #endif
18016a497c6SRafael Auler 
18116a497c6SRafael Auler   void clear() {
18216a497c6SRafael Auler     Lock L(M);
18316a497c6SRafael Auler     StackSize = 0;
18416a497c6SRafael Auler   }
18516a497c6SRafael Auler 
18616a497c6SRafael Auler   /// Set mmap reservation size (only relevant before first allocation)
1879bd71615SXun Li   void setMaxSize(uint64_t Size) { MaxSize = Size; }
18816a497c6SRafael Auler 
18916a497c6SRafael Auler   /// Set mmap reservation privacy (only relevant before first allocation)
1909bd71615SXun Li   void setShared(bool S) { Shared = S; }
19116a497c6SRafael Auler 
19216a497c6SRafael Auler   void destroy() {
19316a497c6SRafael Auler     if (StackBase == nullptr)
19416a497c6SRafael Auler       return;
19516a497c6SRafael Auler     __munmap(StackBase, MaxSize);
19616a497c6SRafael Auler   }
197cc4b2fb6SRafael Auler 
198cc4b2fb6SRafael Auler private:
19916a497c6SRafael Auler   static constexpr uint64_t Magic = 0x1122334455667788ull;
20016a497c6SRafael Auler   uint64_t MaxSize = 0xa00000;
201cc4b2fb6SRafael Auler   uint8_t *StackBase{nullptr};
202cc4b2fb6SRafael Auler   uint64_t StackSize{0};
20316a497c6SRafael Auler   bool Shared{false};
20416a497c6SRafael Auler   Mutex M;
205cc4b2fb6SRafael Auler };
206cc4b2fb6SRafael Auler 
20716a497c6SRafael Auler /// Used for allocating indirect call instrumentation counters. Initialized by
20816a497c6SRafael Auler /// __bolt_instr_setup, our initialization routine.
20916a497c6SRafael Auler BumpPtrAllocator GlobalAlloc;
210cc4b2fb6SRafael Auler } // anonymous namespace
211cc4b2fb6SRafael Auler 
212cc4b2fb6SRafael Auler // User-defined placement new operators. We only use those (as opposed to
213cc4b2fb6SRafael Auler // overriding the regular operator new) so we can keep our allocator in the
214cc4b2fb6SRafael Auler // stack instead of in a data section (global).
215faaefff6SAlexander Shaposhnikov void *operator new(size_t Sz, BumpPtrAllocator &A) { return A.allocate(Sz); }
216faaefff6SAlexander Shaposhnikov void *operator new(size_t Sz, BumpPtrAllocator &A, char C) {
217cc4b2fb6SRafael Auler   auto *Ptr = reinterpret_cast<char *>(A.allocate(Sz));
218cc4b2fb6SRafael Auler   memSet(Ptr, C, Sz);
219cc4b2fb6SRafael Auler   return Ptr;
220cc4b2fb6SRafael Auler }
221faaefff6SAlexander Shaposhnikov void *operator new[](size_t Sz, BumpPtrAllocator &A) {
222cc4b2fb6SRafael Auler   return A.allocate(Sz);
223cc4b2fb6SRafael Auler }
224faaefff6SAlexander Shaposhnikov void *operator new[](size_t Sz, BumpPtrAllocator &A, char C) {
225cc4b2fb6SRafael Auler   auto *Ptr = reinterpret_cast<char *>(A.allocate(Sz));
226cc4b2fb6SRafael Auler   memSet(Ptr, C, Sz);
227cc4b2fb6SRafael Auler   return Ptr;
228cc4b2fb6SRafael Auler }
229cc4b2fb6SRafael Auler // Only called during exception unwinding (useless). We must manually dealloc.
230cc4b2fb6SRafael Auler // C++ language weirdness
2319bd71615SXun Li void operator delete(void *Ptr, BumpPtrAllocator &A) { A.deallocate(Ptr); }
232cc4b2fb6SRafael Auler 
233cc4b2fb6SRafael Auler namespace {
234cc4b2fb6SRafael Auler 
23516a497c6SRafael Auler /// Basic key-val atom stored in our hash
23616a497c6SRafael Auler struct SimpleHashTableEntryBase {
23716a497c6SRafael Auler   uint64_t Key;
23816a497c6SRafael Auler   uint64_t Val;
23916a497c6SRafael Auler };
24016a497c6SRafael Auler 
24116a497c6SRafael Auler /// This hash table implementation starts by allocating a table of size
24216a497c6SRafael Auler /// InitialSize. When conflicts happen in this main table, it resolves
24316a497c6SRafael Auler /// them by chaining a new table of size IncSize. It never reallocs as our
24416a497c6SRafael Auler /// allocator doesn't support it. The key is intended to be function pointers.
24516a497c6SRafael Auler /// There's no clever hash function (it's just x mod size, size being prime).
24616a497c6SRafael Auler /// I never tuned the coefficientes in the modular equation (TODO)
24716a497c6SRafael Auler /// This is used for indirect calls (each call site has one of this, so it
24816a497c6SRafael Auler /// should have a small footprint) and for tallying call counts globally for
24916a497c6SRafael Auler /// each target to check if we missed the origin of some calls (this one is a
25016a497c6SRafael Auler /// large instantiation of this template, since it is global for all call sites)
25116a497c6SRafael Auler template <typename T = SimpleHashTableEntryBase, uint32_t InitialSize = 7,
25216a497c6SRafael Auler           uint32_t IncSize = 7>
25316a497c6SRafael Auler class SimpleHashTable {
25416a497c6SRafael Auler public:
25516a497c6SRafael Auler   using MapEntry = T;
25616a497c6SRafael Auler 
25716a497c6SRafael Auler   /// Increment by 1 the value of \p Key. If it is not in this table, it will be
25816a497c6SRafael Auler   /// added to the table and its value set to 1.
25916a497c6SRafael Auler   void incrementVal(uint64_t Key, BumpPtrAllocator &Alloc) {
26016a497c6SRafael Auler     ++get(Key, Alloc).Val;
26116a497c6SRafael Auler   }
26216a497c6SRafael Auler 
26316a497c6SRafael Auler   /// Basic member accessing interface. Here we pass the allocator explicitly to
26416a497c6SRafael Auler   /// avoid storing a pointer to it as part of this table (remember there is one
26516a497c6SRafael Auler   /// hash for each indirect call site, so we wan't to minimize our footprint).
26616a497c6SRafael Auler   MapEntry &get(uint64_t Key, BumpPtrAllocator &Alloc) {
26716a497c6SRafael Auler     Lock L(M);
26816a497c6SRafael Auler     if (TableRoot)
26916a497c6SRafael Auler       return getEntry(TableRoot, Key, Key, Alloc, 0);
27016a497c6SRafael Auler     return firstAllocation(Key, Alloc);
27116a497c6SRafael Auler   }
27216a497c6SRafael Auler 
27316a497c6SRafael Auler   /// Traverses all elements in the table
27416a497c6SRafael Auler   template <typename... Args>
27516a497c6SRafael Auler   void forEachElement(void (*Callback)(MapEntry &, Args...), Args... args) {
27616a497c6SRafael Auler     if (!TableRoot)
27716a497c6SRafael Auler       return;
27816a497c6SRafael Auler     return forEachElement(Callback, InitialSize, TableRoot, args...);
27916a497c6SRafael Auler   }
28016a497c6SRafael Auler 
28116a497c6SRafael Auler   void resetCounters();
28216a497c6SRafael Auler 
28316a497c6SRafael Auler private:
28416a497c6SRafael Auler   constexpr static uint64_t VacantMarker = 0;
28516a497c6SRafael Auler   constexpr static uint64_t FollowUpTableMarker = 0x8000000000000000ull;
28616a497c6SRafael Auler 
28716a497c6SRafael Auler   MapEntry *TableRoot{nullptr};
28816a497c6SRafael Auler   Mutex M;
28916a497c6SRafael Auler 
29016a497c6SRafael Auler   template <typename... Args>
29116a497c6SRafael Auler   void forEachElement(void (*Callback)(MapEntry &, Args...),
29216a497c6SRafael Auler                       uint32_t NumEntries, MapEntry *Entries, Args... args) {
29316a497c6SRafael Auler     for (int I = 0; I < NumEntries; ++I) {
29416a497c6SRafael Auler       auto &Entry = Entries[I];
29516a497c6SRafael Auler       if (Entry.Key == VacantMarker)
29616a497c6SRafael Auler         continue;
29716a497c6SRafael Auler       if (Entry.Key & FollowUpTableMarker) {
29816a497c6SRafael Auler         forEachElement(Callback, IncSize,
29916a497c6SRafael Auler                        reinterpret_cast<MapEntry *>(Entry.Key &
30016a497c6SRafael Auler                                                     ~FollowUpTableMarker),
30116a497c6SRafael Auler                        args...);
30216a497c6SRafael Auler         continue;
30316a497c6SRafael Auler       }
30416a497c6SRafael Auler       Callback(Entry, args...);
30516a497c6SRafael Auler     }
30616a497c6SRafael Auler   }
30716a497c6SRafael Auler 
30816a497c6SRafael Auler   MapEntry &firstAllocation(uint64_t Key, BumpPtrAllocator &Alloc) {
30916a497c6SRafael Auler     TableRoot = new (Alloc, 0) MapEntry[InitialSize];
31016a497c6SRafael Auler     auto &Entry = TableRoot[Key % InitialSize];
31116a497c6SRafael Auler     Entry.Key = Key;
31216a497c6SRafael Auler     return Entry;
31316a497c6SRafael Auler   }
31416a497c6SRafael Auler 
31516a497c6SRafael Auler   MapEntry &getEntry(MapEntry *Entries, uint64_t Key, uint64_t Selector,
31616a497c6SRafael Auler                      BumpPtrAllocator &Alloc, int CurLevel) {
31716a497c6SRafael Auler     const uint32_t NumEntries = CurLevel == 0 ? InitialSize : IncSize;
31816a497c6SRafael Auler     uint64_t Remainder = Selector / NumEntries;
31916a497c6SRafael Auler     Selector = Selector % NumEntries;
32016a497c6SRafael Auler     auto &Entry = Entries[Selector];
32116a497c6SRafael Auler 
32216a497c6SRafael Auler     // A hit
32316a497c6SRafael Auler     if (Entry.Key == Key) {
32416a497c6SRafael Auler       return Entry;
32516a497c6SRafael Auler     }
32616a497c6SRafael Auler 
32716a497c6SRafael Auler     // Vacant - add new entry
32816a497c6SRafael Auler     if (Entry.Key == VacantMarker) {
32916a497c6SRafael Auler       Entry.Key = Key;
33016a497c6SRafael Auler       return Entry;
33116a497c6SRafael Auler     }
33216a497c6SRafael Auler 
33316a497c6SRafael Auler     // Defer to the next level
33416a497c6SRafael Auler     if (Entry.Key & FollowUpTableMarker) {
33516a497c6SRafael Auler       return getEntry(
33616a497c6SRafael Auler           reinterpret_cast<MapEntry *>(Entry.Key & ~FollowUpTableMarker),
33716a497c6SRafael Auler           Key, Remainder, Alloc, CurLevel + 1);
33816a497c6SRafael Auler     }
33916a497c6SRafael Auler 
34016a497c6SRafael Auler     // Conflict - create the next level
34116a497c6SRafael Auler     MapEntry *NextLevelTbl = new (Alloc, 0) MapEntry[IncSize];
34216a497c6SRafael Auler     uint64_t CurEntrySelector = Entry.Key / InitialSize;
34316a497c6SRafael Auler     for (int I = 0; I < CurLevel; ++I)
34416a497c6SRafael Auler       CurEntrySelector /= IncSize;
34516a497c6SRafael Auler     CurEntrySelector = CurEntrySelector % IncSize;
34616a497c6SRafael Auler     NextLevelTbl[CurEntrySelector] = Entry;
34716a497c6SRafael Auler     Entry.Key = reinterpret_cast<uint64_t>(NextLevelTbl) | FollowUpTableMarker;
34816a497c6SRafael Auler     return getEntry(NextLevelTbl, Key, Remainder, Alloc, CurLevel + 1);
34916a497c6SRafael Auler   }
35016a497c6SRafael Auler };
35116a497c6SRafael Auler 
35216a497c6SRafael Auler template <typename T> void resetIndCallCounter(T &Entry) {
35316a497c6SRafael Auler   Entry.Val = 0;
35416a497c6SRafael Auler }
35516a497c6SRafael Auler 
35616a497c6SRafael Auler template <typename T, uint32_t X, uint32_t Y>
35716a497c6SRafael Auler void SimpleHashTable<T, X, Y>::resetCounters() {
35816a497c6SRafael Auler   Lock L(M);
35916a497c6SRafael Auler   forEachElement(resetIndCallCounter);
36016a497c6SRafael Auler }
36116a497c6SRafael Auler 
36216a497c6SRafael Auler /// Represents a hash table mapping a function target address to its counter.
36316a497c6SRafael Auler using IndirectCallHashTable = SimpleHashTable<>;
36416a497c6SRafael Auler 
36516a497c6SRafael Auler /// Initialize with number 1 instead of 0 so we don't go into .bss. This is the
36616a497c6SRafael Auler /// global array of all hash tables storing indirect call destinations happening
36716a497c6SRafael Auler /// during runtime, one table per call site.
36816a497c6SRafael Auler IndirectCallHashTable *GlobalIndCallCounters{
36916a497c6SRafael Auler     reinterpret_cast<IndirectCallHashTable *>(1)};
37016a497c6SRafael Auler 
37116a497c6SRafael Auler /// Don't allow reentrancy in the fdata writing phase - only one thread writes
37216a497c6SRafael Auler /// it
37316a497c6SRafael Auler Mutex *GlobalWriteProfileMutex{reinterpret_cast<Mutex *>(1)};
37416a497c6SRafael Auler 
37516a497c6SRafael Auler /// Store number of calls in additional to target address (Key) and frequency
37616a497c6SRafael Auler /// as perceived by the basic block counter (Val).
37716a497c6SRafael Auler struct CallFlowEntryBase : public SimpleHashTableEntryBase {
37816a497c6SRafael Auler   uint64_t Calls;
37916a497c6SRafael Auler };
38016a497c6SRafael Auler 
38116a497c6SRafael Auler using CallFlowHashTableBase = SimpleHashTable<CallFlowEntryBase, 11939, 233>;
38216a497c6SRafael Auler 
38316a497c6SRafael Auler /// This is a large table indexing all possible call targets (indirect and
38416a497c6SRafael Auler /// direct ones). The goal is to find mismatches between number of calls (for
38516a497c6SRafael Auler /// those calls we were able to track) and the entry basic block counter of the
38616a497c6SRafael Auler /// callee. In most cases, these two should be equal. If not, there are two
38716a497c6SRafael Auler /// possible scenarios here:
38816a497c6SRafael Auler ///
38916a497c6SRafael Auler ///  * Entry BB has higher frequency than all known calls to this function.
39016a497c6SRafael Auler ///    In this case, we have dynamic library code or any uninstrumented code
39116a497c6SRafael Auler ///    calling this function. We will write the profile for these untracked
39216a497c6SRafael Auler ///    calls as having source "0 [unknown] 0" in the fdata file.
39316a497c6SRafael Auler ///
39416a497c6SRafael Auler ///  * Number of known calls is higher than the frequency of entry BB
39516a497c6SRafael Auler ///    This only happens when there is no counter for the entry BB / callee
39616a497c6SRafael Auler ///    function is not simple (in BOLT terms). We don't do anything special
39716a497c6SRafael Auler ///    here and just ignore those (we still report all calls to the non-simple
39816a497c6SRafael Auler ///    function, though).
39916a497c6SRafael Auler ///
40016a497c6SRafael Auler class CallFlowHashTable : public CallFlowHashTableBase {
40116a497c6SRafael Auler public:
40216a497c6SRafael Auler   CallFlowHashTable(BumpPtrAllocator &Alloc) : Alloc(Alloc) {}
40316a497c6SRafael Auler 
40416a497c6SRafael Auler   MapEntry &get(uint64_t Key) { return CallFlowHashTableBase::get(Key, Alloc); }
40516a497c6SRafael Auler 
40616a497c6SRafael Auler private:
40716a497c6SRafael Auler   // Different than the hash table for indirect call targets, we do store the
40816a497c6SRafael Auler   // allocator here since there is only one call flow hash and space overhead
40916a497c6SRafael Auler   // is negligible.
41016a497c6SRafael Auler   BumpPtrAllocator &Alloc;
41116a497c6SRafael Auler };
41216a497c6SRafael Auler 
41316a497c6SRafael Auler ///
41416a497c6SRafael Auler /// Description metadata emitted by BOLT to describe the program - refer to
41516a497c6SRafael Auler /// Passes/Instrumentation.cpp - Instrumentation::emitTablesAsELFNote()
41616a497c6SRafael Auler ///
41716a497c6SRafael Auler struct Location {
41816a497c6SRafael Auler   uint32_t FunctionName;
41916a497c6SRafael Auler   uint32_t Offset;
42016a497c6SRafael Auler };
42116a497c6SRafael Auler 
42216a497c6SRafael Auler struct CallDescription {
42316a497c6SRafael Auler   Location From;
42416a497c6SRafael Auler   uint32_t FromNode;
42516a497c6SRafael Auler   Location To;
42616a497c6SRafael Auler   uint32_t Counter;
42716a497c6SRafael Auler   uint64_t TargetAddress;
42816a497c6SRafael Auler };
42916a497c6SRafael Auler 
43016a497c6SRafael Auler using IndCallDescription = Location;
43116a497c6SRafael Auler 
43216a497c6SRafael Auler struct IndCallTargetDescription {
43316a497c6SRafael Auler   Location Loc;
43416a497c6SRafael Auler   uint64_t Address;
43516a497c6SRafael Auler };
43616a497c6SRafael Auler 
43716a497c6SRafael Auler struct EdgeDescription {
43816a497c6SRafael Auler   Location From;
43916a497c6SRafael Auler   uint32_t FromNode;
44016a497c6SRafael Auler   Location To;
44116a497c6SRafael Auler   uint32_t ToNode;
44216a497c6SRafael Auler   uint32_t Counter;
44316a497c6SRafael Auler };
44416a497c6SRafael Auler 
44516a497c6SRafael Auler struct InstrumentedNode {
44616a497c6SRafael Auler   uint32_t Node;
44716a497c6SRafael Auler   uint32_t Counter;
44816a497c6SRafael Auler };
44916a497c6SRafael Auler 
45016a497c6SRafael Auler struct EntryNode {
45116a497c6SRafael Auler   uint64_t Node;
45216a497c6SRafael Auler   uint64_t Address;
45316a497c6SRafael Auler };
45416a497c6SRafael Auler 
45516a497c6SRafael Auler struct FunctionDescription {
45616a497c6SRafael Auler   uint32_t NumLeafNodes;
45716a497c6SRafael Auler   const InstrumentedNode *LeafNodes;
45816a497c6SRafael Auler   uint32_t NumEdges;
45916a497c6SRafael Auler   const EdgeDescription *Edges;
46016a497c6SRafael Auler   uint32_t NumCalls;
46116a497c6SRafael Auler   const CallDescription *Calls;
46216a497c6SRafael Auler   uint32_t NumEntryNodes;
46316a497c6SRafael Auler   const EntryNode *EntryNodes;
46416a497c6SRafael Auler 
46516a497c6SRafael Auler   /// Constructor will parse the serialized function metadata written by BOLT
46616a497c6SRafael Auler   FunctionDescription(const uint8_t *FuncDesc);
46716a497c6SRafael Auler 
46816a497c6SRafael Auler   uint64_t getSize() const {
46916a497c6SRafael Auler     return 16 + NumLeafNodes * sizeof(InstrumentedNode) +
47016a497c6SRafael Auler            NumEdges * sizeof(EdgeDescription) +
47116a497c6SRafael Auler            NumCalls * sizeof(CallDescription) +
47216a497c6SRafael Auler            NumEntryNodes * sizeof(EntryNode);
47316a497c6SRafael Auler   }
47416a497c6SRafael Auler };
47516a497c6SRafael Auler 
47616a497c6SRafael Auler /// The context is created when the fdata profile needs to be written to disk
47716a497c6SRafael Auler /// and we need to interpret our runtime counters. It contains pointers to the
47816a497c6SRafael Auler /// mmaped binary (only the BOLT written metadata section). Deserialization
47916a497c6SRafael Auler /// should be straightforward as most data is POD or an array of POD elements.
48016a497c6SRafael Auler /// This metadata is used to reconstruct function CFGs.
48116a497c6SRafael Auler struct ProfileWriterContext {
48216a497c6SRafael Auler   IndCallDescription *IndCallDescriptions;
48316a497c6SRafael Auler   IndCallTargetDescription *IndCallTargets;
48416a497c6SRafael Auler   uint8_t *FuncDescriptions;
48516a497c6SRafael Auler   char *Strings;  // String table with function names used in this binary
48616a497c6SRafael Auler   int FileDesc;   // File descriptor for the file on disk backing this
48716a497c6SRafael Auler                   // information in memory via mmap
48816a497c6SRafael Auler   void *MMapPtr;  // The mmap ptr
48916a497c6SRafael Auler   int MMapSize;   // The mmap size
49016a497c6SRafael Auler 
49116a497c6SRafael Auler   /// Hash table storing all possible call destinations to detect untracked
49216a497c6SRafael Auler   /// calls and correctly report them as [unknown] in output fdata.
49316a497c6SRafael Auler   CallFlowHashTable *CallFlowTable;
49416a497c6SRafael Auler 
49516a497c6SRafael Auler   /// Lookup the sorted indirect call target vector to fetch function name and
49616a497c6SRafael Auler   /// offset for an arbitrary function pointer.
49716a497c6SRafael Auler   const IndCallTargetDescription *lookupIndCallTarget(uint64_t Target) const;
49816a497c6SRafael Auler };
49916a497c6SRafael Auler 
50016a497c6SRafael Auler /// Perform a string comparison and returns zero if Str1 matches Str2. Compares
50116a497c6SRafael Auler /// at most Size characters.
502cc4b2fb6SRafael Auler int compareStr(const char *Str1, const char *Str2, int Size) {
503821480d2SRafael Auler   while (*Str1 == *Str2) {
504821480d2SRafael Auler     if (*Str1 == '\0' || --Size == 0)
505821480d2SRafael Auler       return 0;
506821480d2SRafael Auler     ++Str1;
507821480d2SRafael Auler     ++Str2;
508821480d2SRafael Auler   }
509821480d2SRafael Auler   return 1;
510821480d2SRafael Auler }
511821480d2SRafael Auler 
51216a497c6SRafael Auler /// Output Location to the fdata file
51316a497c6SRafael Auler char *serializeLoc(const ProfileWriterContext &Ctx, char *OutBuf,
514cc4b2fb6SRafael Auler                    const Location Loc, uint32_t BufSize) {
515821480d2SRafael Auler   // fdata location format: Type Name Offset
516821480d2SRafael Auler   // Type 1 - regular symbol
517821480d2SRafael Auler   OutBuf = strCopy(OutBuf, "1 ");
51816a497c6SRafael Auler   const char *Str = Ctx.Strings + Loc.FunctionName;
519cc4b2fb6SRafael Auler   uint32_t Size = 25;
52062aa74f8SRafael Auler   while (*Str) {
52162aa74f8SRafael Auler     *OutBuf++ = *Str++;
522cc4b2fb6SRafael Auler     if (++Size >= BufSize)
523cc4b2fb6SRafael Auler       break;
52462aa74f8SRafael Auler   }
525cc4b2fb6SRafael Auler   assert(!*Str, "buffer overflow, function name too large");
52662aa74f8SRafael Auler   *OutBuf++ = ' ';
527821480d2SRafael Auler   OutBuf = intToStr(OutBuf, Loc.Offset, 16);
52862aa74f8SRafael Auler   *OutBuf++ = ' ';
52962aa74f8SRafael Auler   return OutBuf;
53062aa74f8SRafael Auler }
53162aa74f8SRafael Auler 
53216a497c6SRafael Auler /// Read and deserialize a function description written by BOLT. \p FuncDesc
53316a497c6SRafael Auler /// points at the beginning of the function metadata structure in the file.
53416a497c6SRafael Auler /// See Instrumentation::emitTablesAsELFNote()
53516a497c6SRafael Auler FunctionDescription::FunctionDescription(const uint8_t *FuncDesc) {
53616a497c6SRafael Auler   NumLeafNodes = *reinterpret_cast<const uint32_t *>(FuncDesc);
53716a497c6SRafael Auler   DEBUG(reportNumber("NumLeafNodes = ", NumLeafNodes, 10));
53816a497c6SRafael Auler   LeafNodes = reinterpret_cast<const InstrumentedNode *>(FuncDesc + 4);
53916a497c6SRafael Auler 
54016a497c6SRafael Auler   NumEdges = *reinterpret_cast<const uint32_t *>(
54116a497c6SRafael Auler       FuncDesc + 4 + NumLeafNodes * sizeof(InstrumentedNode));
54216a497c6SRafael Auler   DEBUG(reportNumber("NumEdges = ", NumEdges, 10));
54316a497c6SRafael Auler   Edges = reinterpret_cast<const EdgeDescription *>(
54416a497c6SRafael Auler       FuncDesc + 8 + NumLeafNodes * sizeof(InstrumentedNode));
54516a497c6SRafael Auler 
54616a497c6SRafael Auler   NumCalls = *reinterpret_cast<const uint32_t *>(
54716a497c6SRafael Auler       FuncDesc + 8 + NumLeafNodes * sizeof(InstrumentedNode) +
54816a497c6SRafael Auler       NumEdges * sizeof(EdgeDescription));
54916a497c6SRafael Auler   DEBUG(reportNumber("NumCalls = ", NumCalls, 10));
55016a497c6SRafael Auler   Calls = reinterpret_cast<const CallDescription *>(
55116a497c6SRafael Auler       FuncDesc + 12 + NumLeafNodes * sizeof(InstrumentedNode) +
55216a497c6SRafael Auler       NumEdges * sizeof(EdgeDescription));
55316a497c6SRafael Auler   NumEntryNodes = *reinterpret_cast<const uint32_t *>(
55416a497c6SRafael Auler       FuncDesc + 12 + NumLeafNodes * sizeof(InstrumentedNode) +
55516a497c6SRafael Auler       NumEdges * sizeof(EdgeDescription) + NumCalls * sizeof(CallDescription));
55616a497c6SRafael Auler   DEBUG(reportNumber("NumEntryNodes = ", NumEntryNodes, 10));
55716a497c6SRafael Auler   EntryNodes = reinterpret_cast<const EntryNode *>(
55816a497c6SRafael Auler       FuncDesc + 16 + NumLeafNodes * sizeof(InstrumentedNode) +
55916a497c6SRafael Auler       NumEdges * sizeof(EdgeDescription) + NumCalls * sizeof(CallDescription));
56016a497c6SRafael Auler }
56116a497c6SRafael Auler 
56216a497c6SRafael Auler /// Read and mmap descriptions written by BOLT from the executable's notes
56316a497c6SRafael Auler /// section
564a0dd5b05SAlexander Shaposhnikov #if defined(HAVE_ELF_H) and !defined(__APPLE__)
56516a497c6SRafael Auler ProfileWriterContext readDescriptions() {
56616a497c6SRafael Auler   ProfileWriterContext Result;
567821480d2SRafael Auler   uint64_t FD = __open("/proc/self/exe",
568821480d2SRafael Auler                        /*flags=*/0 /*O_RDONLY*/,
569821480d2SRafael Auler                        /*mode=*/0666);
570cc4b2fb6SRafael Auler   assert(static_cast<int64_t>(FD) > 0, "Failed to open /proc/self/exe");
571821480d2SRafael Auler   Result.FileDesc = FD;
572821480d2SRafael Auler 
573821480d2SRafael Auler   // mmap our binary to memory
574821480d2SRafael Auler   uint64_t Size = __lseek(FD, 0, 2 /*SEEK_END*/);
575821480d2SRafael Auler   uint8_t *BinContents = reinterpret_cast<uint8_t *>(
576821480d2SRafael Auler       __mmap(0, Size, 0x1 /* PROT_READ*/, 0x2 /* MAP_PRIVATE*/, FD, 0));
577821480d2SRafael Auler   Result.MMapPtr = BinContents;
578821480d2SRafael Auler   Result.MMapSize = Size;
579821480d2SRafael Auler   Elf64_Ehdr *Hdr = reinterpret_cast<Elf64_Ehdr *>(BinContents);
580821480d2SRafael Auler   Elf64_Shdr *Shdr = reinterpret_cast<Elf64_Shdr *>(BinContents + Hdr->e_shoff);
581821480d2SRafael Auler   Elf64_Shdr *StringTblHeader = reinterpret_cast<Elf64_Shdr *>(
582821480d2SRafael Auler       BinContents + Hdr->e_shoff + Hdr->e_shstrndx * Hdr->e_shentsize);
583821480d2SRafael Auler 
584821480d2SRafael Auler   // Find .bolt.instr.tables with the data we need and set pointers to it
585821480d2SRafael Auler   for (int I = 0; I < Hdr->e_shnum; ++I) {
586821480d2SRafael Auler     char *SecName = reinterpret_cast<char *>(
587821480d2SRafael Auler         BinContents + StringTblHeader->sh_offset + Shdr->sh_name);
588821480d2SRafael Auler     if (compareStr(SecName, ".bolt.instr.tables", 64) != 0) {
589821480d2SRafael Auler       Shdr = reinterpret_cast<Elf64_Shdr *>(BinContents + Hdr->e_shoff +
590821480d2SRafael Auler                                             (I + 1) * Hdr->e_shentsize);
591821480d2SRafael Auler       continue;
592821480d2SRafael Auler     }
593821480d2SRafael Auler     // Actual contents of the ELF note start after offset 20 decimal:
594821480d2SRafael Auler     // Offset 0: Producer name size (4 bytes)
595821480d2SRafael Auler     // Offset 4: Contents size (4 bytes)
596821480d2SRafael Auler     // Offset 8: Note type (4 bytes)
597821480d2SRafael Auler     // Offset 12: Producer name (BOLT\0) (5 bytes + align to 4-byte boundary)
598821480d2SRafael Auler     // Offset 20: Contents
59916a497c6SRafael Auler     uint32_t IndCallDescSize =
600cc4b2fb6SRafael Auler         *reinterpret_cast<uint32_t *>(BinContents + Shdr->sh_offset + 20);
60116a497c6SRafael Auler     uint32_t IndCallTargetDescSize = *reinterpret_cast<uint32_t *>(
60216a497c6SRafael Auler         BinContents + Shdr->sh_offset + 24 + IndCallDescSize);
60316a497c6SRafael Auler     uint32_t FuncDescSize =
60416a497c6SRafael Auler         *reinterpret_cast<uint32_t *>(BinContents + Shdr->sh_offset + 28 +
60516a497c6SRafael Auler                                       IndCallDescSize + IndCallTargetDescSize);
60616a497c6SRafael Auler     Result.IndCallDescriptions = reinterpret_cast<IndCallDescription *>(
60716a497c6SRafael Auler         BinContents + Shdr->sh_offset + 24);
60816a497c6SRafael Auler     Result.IndCallTargets = reinterpret_cast<IndCallTargetDescription *>(
60916a497c6SRafael Auler         BinContents + Shdr->sh_offset + 28 + IndCallDescSize);
61016a497c6SRafael Auler     Result.FuncDescriptions = BinContents + Shdr->sh_offset + 32 +
61116a497c6SRafael Auler                               IndCallDescSize + IndCallTargetDescSize;
61216a497c6SRafael Auler     Result.Strings = reinterpret_cast<char *>(
61316a497c6SRafael Auler         BinContents + Shdr->sh_offset + 32 + IndCallDescSize +
61416a497c6SRafael Auler         IndCallTargetDescSize + FuncDescSize);
615821480d2SRafael Auler     return Result;
616821480d2SRafael Auler   }
617821480d2SRafael Auler   const char ErrMsg[] =
618821480d2SRafael Auler       "BOLT instrumentation runtime error: could not find section "
619821480d2SRafael Auler       ".bolt.instr.tables\n";
620821480d2SRafael Auler   reportError(ErrMsg, sizeof(ErrMsg));
621821480d2SRafael Auler   return Result;
622821480d2SRafael Auler }
623a0dd5b05SAlexander Shaposhnikov 
624ba31344fSRafael Auler #else
625a0dd5b05SAlexander Shaposhnikov 
62616a497c6SRafael Auler ProfileWriterContext readDescriptions() {
62716a497c6SRafael Auler   ProfileWriterContext Result;
628a0dd5b05SAlexander Shaposhnikov   uint8_t *Tables = _bolt_instr_tables_getter();
629a0dd5b05SAlexander Shaposhnikov   uint32_t IndCallDescSize = *reinterpret_cast<uint32_t *>(Tables);
630a0dd5b05SAlexander Shaposhnikov   uint32_t IndCallTargetDescSize =
631a0dd5b05SAlexander Shaposhnikov       *reinterpret_cast<uint32_t *>(Tables + 4 + IndCallDescSize);
632a0dd5b05SAlexander Shaposhnikov   uint32_t FuncDescSize = *reinterpret_cast<uint32_t *>(
633a0dd5b05SAlexander Shaposhnikov       Tables + 8 + IndCallDescSize + IndCallTargetDescSize);
634a0dd5b05SAlexander Shaposhnikov   Result.IndCallDescriptions =
635a0dd5b05SAlexander Shaposhnikov       reinterpret_cast<IndCallDescription *>(Tables + 4);
636a0dd5b05SAlexander Shaposhnikov   Result.IndCallTargets = reinterpret_cast<IndCallTargetDescription *>(
637a0dd5b05SAlexander Shaposhnikov       Tables + 8 + IndCallDescSize);
638a0dd5b05SAlexander Shaposhnikov   Result.FuncDescriptions =
639a0dd5b05SAlexander Shaposhnikov       Tables + 12 + IndCallDescSize + IndCallTargetDescSize;
640a0dd5b05SAlexander Shaposhnikov   Result.Strings = reinterpret_cast<char *>(
641a0dd5b05SAlexander Shaposhnikov       Tables + 12 + IndCallDescSize + IndCallTargetDescSize + FuncDescSize);
642ba31344fSRafael Auler   return Result;
643ba31344fSRafael Auler }
644a0dd5b05SAlexander Shaposhnikov 
645ba31344fSRafael Auler #endif
646821480d2SRafael Auler 
647a0dd5b05SAlexander Shaposhnikov #if !defined(__APPLE__)
64816a497c6SRafael Auler /// Debug by printing overall metadata global numbers to check it is sane
64916a497c6SRafael Auler void printStats(const ProfileWriterContext &Ctx) {
650cc4b2fb6SRafael Auler   char StatMsg[BufSize];
651cc4b2fb6SRafael Auler   char *StatPtr = StatMsg;
65216a497c6SRafael Auler   StatPtr =
65316a497c6SRafael Auler       strCopy(StatPtr,
65416a497c6SRafael Auler               "\nBOLT INSTRUMENTATION RUNTIME STATISTICS\n\nIndCallDescSize: ");
655cc4b2fb6SRafael Auler   StatPtr = intToStr(StatPtr,
65616a497c6SRafael Auler                      Ctx.FuncDescriptions -
65716a497c6SRafael Auler                          reinterpret_cast<uint8_t *>(Ctx.IndCallDescriptions),
658cc4b2fb6SRafael Auler                      10);
659cc4b2fb6SRafael Auler   StatPtr = strCopy(StatPtr, "\nFuncDescSize: ");
660cc4b2fb6SRafael Auler   StatPtr = intToStr(
661cc4b2fb6SRafael Auler       StatPtr,
66216a497c6SRafael Auler       reinterpret_cast<uint8_t *>(Ctx.Strings) - Ctx.FuncDescriptions, 10);
66316a497c6SRafael Auler   StatPtr = strCopy(StatPtr, "\n__bolt_instr_num_ind_calls: ");
66416a497c6SRafael Auler   StatPtr = intToStr(StatPtr, __bolt_instr_num_ind_calls, 10);
665cc4b2fb6SRafael Auler   StatPtr = strCopy(StatPtr, "\n__bolt_instr_num_funcs: ");
666cc4b2fb6SRafael Auler   StatPtr = intToStr(StatPtr, __bolt_instr_num_funcs, 10);
667cc4b2fb6SRafael Auler   StatPtr = strCopy(StatPtr, "\n");
668cc4b2fb6SRafael Auler   __write(2, StatMsg, StatPtr - StatMsg);
669cc4b2fb6SRafael Auler }
670a0dd5b05SAlexander Shaposhnikov #endif
671a0dd5b05SAlexander Shaposhnikov 
672cc4b2fb6SRafael Auler 
673cc4b2fb6SRafael Auler /// This is part of a simple CFG representation in memory, where we store
674cc4b2fb6SRafael Auler /// a dynamically sized array of input and output edges per node, and store
675cc4b2fb6SRafael Auler /// a dynamically sized array of nodes per graph. We also store the spanning
676cc4b2fb6SRafael Auler /// tree edges for that CFG in a separate array of nodes in
677cc4b2fb6SRafael Auler /// \p SpanningTreeNodes, while the regular nodes live in \p CFGNodes.
678cc4b2fb6SRafael Auler struct Edge {
679cc4b2fb6SRafael Auler   uint32_t Node; // Index in nodes array regarding the destination of this edge
680cc4b2fb6SRafael Auler   uint32_t ID;   // Edge index in an array comprising all edges of the graph
681cc4b2fb6SRafael Auler };
682cc4b2fb6SRafael Auler 
683cc4b2fb6SRafael Auler /// A regular graph node or a spanning tree node
684cc4b2fb6SRafael Auler struct Node {
685cc4b2fb6SRafael Auler   uint32_t NumInEdges{0};  // Input edge count used to size InEdge
686cc4b2fb6SRafael Auler   uint32_t NumOutEdges{0}; // Output edge count used to size OutEdges
687cc4b2fb6SRafael Auler   Edge *InEdges{nullptr};  // Created and managed by \p Graph
688cc4b2fb6SRafael Auler   Edge *OutEdges{nullptr}; // ditto
689cc4b2fb6SRafael Auler };
690cc4b2fb6SRafael Auler 
691cc4b2fb6SRafael Auler /// Main class for CFG representation in memory. Manages object creation and
692cc4b2fb6SRafael Auler /// destruction, populates an array of CFG nodes as well as corresponding
693cc4b2fb6SRafael Auler /// spanning tree nodes.
694cc4b2fb6SRafael Auler struct Graph {
695cc4b2fb6SRafael Auler   uint32_t NumNodes;
696cc4b2fb6SRafael Auler   Node *CFGNodes;
697cc4b2fb6SRafael Auler   Node *SpanningTreeNodes;
69816a497c6SRafael Auler   uint64_t *EdgeFreqs;
69916a497c6SRafael Auler   uint64_t *CallFreqs;
700cc4b2fb6SRafael Auler   BumpPtrAllocator &Alloc;
70116a497c6SRafael Auler   const FunctionDescription &D;
702cc4b2fb6SRafael Auler 
70316a497c6SRafael Auler   /// Reads a list of edges from function description \p D and builds
704cc4b2fb6SRafael Auler   /// the graph from it. Allocates several internal dynamic structures that are
70516a497c6SRafael Auler   /// later destroyed by ~Graph() and uses \p Alloc. D.LeafNodes contain all
706cc4b2fb6SRafael Auler   /// spanning tree leaf nodes descriptions (their counters). They are the seed
707cc4b2fb6SRafael Auler   /// used to compute the rest of the missing edge counts in a bottom-up
708cc4b2fb6SRafael Auler   /// traversal of the spanning tree.
70916a497c6SRafael Auler   Graph(BumpPtrAllocator &Alloc, const FunctionDescription &D,
71016a497c6SRafael Auler         const uint64_t *Counters, ProfileWriterContext &Ctx);
711cc4b2fb6SRafael Auler   ~Graph();
712cc4b2fb6SRafael Auler   void dump() const;
71316a497c6SRafael Auler 
71416a497c6SRafael Auler private:
71516a497c6SRafael Auler   void computeEdgeFrequencies(const uint64_t *Counters,
71616a497c6SRafael Auler                               ProfileWriterContext &Ctx);
71716a497c6SRafael Auler   void dumpEdgeFreqs() const;
718cc4b2fb6SRafael Auler };
719cc4b2fb6SRafael Auler 
72016a497c6SRafael Auler Graph::Graph(BumpPtrAllocator &Alloc, const FunctionDescription &D,
72116a497c6SRafael Auler              const uint64_t *Counters, ProfileWriterContext &Ctx)
72216a497c6SRafael Auler     : Alloc(Alloc), D(D) {
723cc4b2fb6SRafael Auler   DEBUG(reportNumber("G = 0x", (uint64_t)this, 16));
724cc4b2fb6SRafael Auler   // First pass to determine number of nodes
72516a497c6SRafael Auler   int32_t MaxNodes = -1;
72616a497c6SRafael Auler   CallFreqs = nullptr;
72716a497c6SRafael Auler   EdgeFreqs = nullptr;
72816a497c6SRafael Auler   for (int I = 0; I < D.NumEdges; ++I) {
72916a497c6SRafael Auler     if (static_cast<int32_t>(D.Edges[I].FromNode) > MaxNodes)
73016a497c6SRafael Auler       MaxNodes = D.Edges[I].FromNode;
73116a497c6SRafael Auler     if (static_cast<int32_t>(D.Edges[I].ToNode) > MaxNodes)
73216a497c6SRafael Auler       MaxNodes = D.Edges[I].ToNode;
733cc4b2fb6SRafael Auler   }
734a0dd5b05SAlexander Shaposhnikov 
73516a497c6SRafael Auler   for (int I = 0; I < D.NumLeafNodes; ++I) {
73616a497c6SRafael Auler     if (static_cast<int32_t>(D.LeafNodes[I].Node) > MaxNodes)
73716a497c6SRafael Auler       MaxNodes = D.LeafNodes[I].Node;
738cc4b2fb6SRafael Auler   }
73916a497c6SRafael Auler   for (int I = 0; I < D.NumCalls; ++I) {
74016a497c6SRafael Auler     if (static_cast<int32_t>(D.Calls[I].FromNode) > MaxNodes)
74116a497c6SRafael Auler       MaxNodes = D.Calls[I].FromNode;
74216a497c6SRafael Auler   }
74316a497c6SRafael Auler   // No nodes? Nothing to do
74416a497c6SRafael Auler   if (MaxNodes < 0) {
74516a497c6SRafael Auler     DEBUG(report("No nodes!\n"));
746cc4b2fb6SRafael Auler     CFGNodes = nullptr;
747cc4b2fb6SRafael Auler     SpanningTreeNodes = nullptr;
748cc4b2fb6SRafael Auler     NumNodes = 0;
749cc4b2fb6SRafael Auler     return;
750cc4b2fb6SRafael Auler   }
751cc4b2fb6SRafael Auler   ++MaxNodes;
752cc4b2fb6SRafael Auler   DEBUG(reportNumber("NumNodes = ", MaxNodes, 10));
75316a497c6SRafael Auler   NumNodes = static_cast<uint32_t>(MaxNodes);
754cc4b2fb6SRafael Auler 
755cc4b2fb6SRafael Auler   // Initial allocations
756cc4b2fb6SRafael Auler   CFGNodes = new (Alloc) Node[MaxNodes];
757a0dd5b05SAlexander Shaposhnikov 
758cc4b2fb6SRafael Auler   DEBUG(reportNumber("G->CFGNodes = 0x", (uint64_t)CFGNodes, 16));
759cc4b2fb6SRafael Auler   SpanningTreeNodes = new (Alloc) Node[MaxNodes];
760cc4b2fb6SRafael Auler   DEBUG(reportNumber("G->SpanningTreeNodes = 0x",
761cc4b2fb6SRafael Auler                      (uint64_t)SpanningTreeNodes, 16));
762cc4b2fb6SRafael Auler 
763cc4b2fb6SRafael Auler   // Figure out how much to allocate to each vector (in/out edge sets)
76416a497c6SRafael Auler   for (int I = 0; I < D.NumEdges; ++I) {
76516a497c6SRafael Auler     CFGNodes[D.Edges[I].FromNode].NumOutEdges++;
76616a497c6SRafael Auler     CFGNodes[D.Edges[I].ToNode].NumInEdges++;
76716a497c6SRafael Auler     if (D.Edges[I].Counter != 0xffffffff)
768cc4b2fb6SRafael Auler       continue;
769cc4b2fb6SRafael Auler 
77016a497c6SRafael Auler     SpanningTreeNodes[D.Edges[I].FromNode].NumOutEdges++;
77116a497c6SRafael Auler     SpanningTreeNodes[D.Edges[I].ToNode].NumInEdges++;
772cc4b2fb6SRafael Auler   }
773cc4b2fb6SRafael Auler 
774cc4b2fb6SRafael Auler   // Allocate in/out edge sets
775cc4b2fb6SRafael Auler   for (int I = 0; I < MaxNodes; ++I) {
776cc4b2fb6SRafael Auler     if (CFGNodes[I].NumInEdges > 0)
777cc4b2fb6SRafael Auler       CFGNodes[I].InEdges = new (Alloc) Edge[CFGNodes[I].NumInEdges];
778cc4b2fb6SRafael Auler     if (CFGNodes[I].NumOutEdges > 0)
779cc4b2fb6SRafael Auler       CFGNodes[I].OutEdges = new (Alloc) Edge[CFGNodes[I].NumOutEdges];
780cc4b2fb6SRafael Auler     if (SpanningTreeNodes[I].NumInEdges > 0)
781cc4b2fb6SRafael Auler       SpanningTreeNodes[I].InEdges =
782cc4b2fb6SRafael Auler           new (Alloc) Edge[SpanningTreeNodes[I].NumInEdges];
783cc4b2fb6SRafael Auler     if (SpanningTreeNodes[I].NumOutEdges > 0)
784cc4b2fb6SRafael Auler       SpanningTreeNodes[I].OutEdges =
785cc4b2fb6SRafael Auler           new (Alloc) Edge[SpanningTreeNodes[I].NumOutEdges];
786cc4b2fb6SRafael Auler     CFGNodes[I].NumInEdges = 0;
787cc4b2fb6SRafael Auler     CFGNodes[I].NumOutEdges = 0;
788cc4b2fb6SRafael Auler     SpanningTreeNodes[I].NumInEdges = 0;
789cc4b2fb6SRafael Auler     SpanningTreeNodes[I].NumOutEdges = 0;
790cc4b2fb6SRafael Auler   }
791cc4b2fb6SRafael Auler 
792cc4b2fb6SRafael Auler   // Fill in/out edge sets
79316a497c6SRafael Auler   for (int I = 0; I < D.NumEdges; ++I) {
79416a497c6SRafael Auler     const uint32_t Src = D.Edges[I].FromNode;
79516a497c6SRafael Auler     const uint32_t Dst = D.Edges[I].ToNode;
796cc4b2fb6SRafael Auler     Edge *E = &CFGNodes[Src].OutEdges[CFGNodes[Src].NumOutEdges++];
797cc4b2fb6SRafael Auler     E->Node = Dst;
798cc4b2fb6SRafael Auler     E->ID = I;
799cc4b2fb6SRafael Auler 
800cc4b2fb6SRafael Auler     E = &CFGNodes[Dst].InEdges[CFGNodes[Dst].NumInEdges++];
801cc4b2fb6SRafael Auler     E->Node = Src;
802cc4b2fb6SRafael Auler     E->ID = I;
803cc4b2fb6SRafael Auler 
80416a497c6SRafael Auler     if (D.Edges[I].Counter != 0xffffffff)
805cc4b2fb6SRafael Auler       continue;
806cc4b2fb6SRafael Auler 
807cc4b2fb6SRafael Auler     E = &SpanningTreeNodes[Src]
808cc4b2fb6SRafael Auler              .OutEdges[SpanningTreeNodes[Src].NumOutEdges++];
809cc4b2fb6SRafael Auler     E->Node = Dst;
810cc4b2fb6SRafael Auler     E->ID = I;
811cc4b2fb6SRafael Auler 
812cc4b2fb6SRafael Auler     E = &SpanningTreeNodes[Dst]
813cc4b2fb6SRafael Auler              .InEdges[SpanningTreeNodes[Dst].NumInEdges++];
814cc4b2fb6SRafael Auler     E->Node = Src;
815cc4b2fb6SRafael Auler     E->ID = I;
816cc4b2fb6SRafael Auler   }
81716a497c6SRafael Auler 
81816a497c6SRafael Auler   computeEdgeFrequencies(Counters, Ctx);
819cc4b2fb6SRafael Auler }
820cc4b2fb6SRafael Auler 
821cc4b2fb6SRafael Auler Graph::~Graph() {
82216a497c6SRafael Auler   if (CallFreqs)
82316a497c6SRafael Auler     Alloc.deallocate(CallFreqs);
82416a497c6SRafael Auler   if (EdgeFreqs)
82516a497c6SRafael Auler     Alloc.deallocate(EdgeFreqs);
826cc4b2fb6SRafael Auler   for (int I = NumNodes - 1; I >= 0; --I) {
827cc4b2fb6SRafael Auler     if (SpanningTreeNodes[I].OutEdges)
828cc4b2fb6SRafael Auler       Alloc.deallocate(SpanningTreeNodes[I].OutEdges);
829cc4b2fb6SRafael Auler     if (SpanningTreeNodes[I].InEdges)
830cc4b2fb6SRafael Auler       Alloc.deallocate(SpanningTreeNodes[I].InEdges);
831cc4b2fb6SRafael Auler     if (CFGNodes[I].OutEdges)
832cc4b2fb6SRafael Auler       Alloc.deallocate(CFGNodes[I].OutEdges);
833cc4b2fb6SRafael Auler     if (CFGNodes[I].InEdges)
834cc4b2fb6SRafael Auler       Alloc.deallocate(CFGNodes[I].InEdges);
835cc4b2fb6SRafael Auler   }
836cc4b2fb6SRafael Auler   if (SpanningTreeNodes)
837cc4b2fb6SRafael Auler     Alloc.deallocate(SpanningTreeNodes);
838cc4b2fb6SRafael Auler   if (CFGNodes)
839cc4b2fb6SRafael Auler     Alloc.deallocate(CFGNodes);
840cc4b2fb6SRafael Auler }
841cc4b2fb6SRafael Auler 
842cc4b2fb6SRafael Auler void Graph::dump() const {
843cc4b2fb6SRafael Auler   reportNumber("Dumping graph with number of nodes: ", NumNodes, 10);
844cc4b2fb6SRafael Auler   report("  Full graph:\n");
845cc4b2fb6SRafael Auler   for (int I = 0; I < NumNodes; ++I) {
846cc4b2fb6SRafael Auler     const Node *N = &CFGNodes[I];
847cc4b2fb6SRafael Auler     reportNumber("    Node #", I, 10);
848cc4b2fb6SRafael Auler     reportNumber("      InEdges total ", N->NumInEdges, 10);
849cc4b2fb6SRafael Auler     for (int J = 0; J < N->NumInEdges; ++J)
850cc4b2fb6SRafael Auler       reportNumber("        ", N->InEdges[J].Node, 10);
851cc4b2fb6SRafael Auler     reportNumber("      OutEdges total ", N->NumOutEdges, 10);
852cc4b2fb6SRafael Auler     for (int J = 0; J < N->NumOutEdges; ++J)
853cc4b2fb6SRafael Auler       reportNumber("        ", N->OutEdges[J].Node, 10);
854cc4b2fb6SRafael Auler     report("\n");
855cc4b2fb6SRafael Auler   }
856cc4b2fb6SRafael Auler   report("  Spanning tree:\n");
857cc4b2fb6SRafael Auler   for (int I = 0; I < NumNodes; ++I) {
858cc4b2fb6SRafael Auler     const Node *N = &SpanningTreeNodes[I];
859cc4b2fb6SRafael Auler     reportNumber("    Node #", I, 10);
860cc4b2fb6SRafael Auler     reportNumber("      InEdges total ", N->NumInEdges, 10);
861cc4b2fb6SRafael Auler     for (int J = 0; J < N->NumInEdges; ++J)
862cc4b2fb6SRafael Auler       reportNumber("        ", N->InEdges[J].Node, 10);
863cc4b2fb6SRafael Auler     reportNumber("      OutEdges total ", N->NumOutEdges, 10);
864cc4b2fb6SRafael Auler     for (int J = 0; J < N->NumOutEdges; ++J)
865cc4b2fb6SRafael Auler       reportNumber("        ", N->OutEdges[J].Node, 10);
866cc4b2fb6SRafael Auler     report("\n");
867cc4b2fb6SRafael Auler   }
868cc4b2fb6SRafael Auler }
869cc4b2fb6SRafael Auler 
87016a497c6SRafael Auler void Graph::dumpEdgeFreqs() const {
87116a497c6SRafael Auler   reportNumber(
87216a497c6SRafael Auler       "Dumping edge frequencies for graph with num edges: ", D.NumEdges, 10);
87316a497c6SRafael Auler   for (int I = 0; I < D.NumEdges; ++I) {
87416a497c6SRafael Auler     reportNumber("* Src: ", D.Edges[I].FromNode, 10);
87516a497c6SRafael Auler     reportNumber("  Dst: ", D.Edges[I].ToNode, 10);
876cc4b2fb6SRafael Auler     reportNumber("    Cnt: ", EdgeFreqs[I], 10);
877cc4b2fb6SRafael Auler   }
878cc4b2fb6SRafael Auler }
879cc4b2fb6SRafael Auler 
88016a497c6SRafael Auler /// Auxiliary map structure for fast lookups of which calls map to each node of
88116a497c6SRafael Auler /// the function CFG
88216a497c6SRafael Auler struct NodeToCallsMap {
88316a497c6SRafael Auler   struct MapEntry {
88416a497c6SRafael Auler     uint32_t NumCalls;
88516a497c6SRafael Auler     uint32_t *Calls;
88616a497c6SRafael Auler   };
88716a497c6SRafael Auler   MapEntry *Entries;
88816a497c6SRafael Auler   BumpPtrAllocator &Alloc;
88916a497c6SRafael Auler   const uint32_t NumNodes;
890cc4b2fb6SRafael Auler 
89116a497c6SRafael Auler   NodeToCallsMap(BumpPtrAllocator &Alloc, const FunctionDescription &D,
89216a497c6SRafael Auler                  uint32_t NumNodes)
89316a497c6SRafael Auler       : Alloc(Alloc), NumNodes(NumNodes) {
89416a497c6SRafael Auler     Entries = new (Alloc, 0) MapEntry[NumNodes];
89516a497c6SRafael Auler     for (int I = 0; I < D.NumCalls; ++I) {
89616a497c6SRafael Auler       DEBUG(reportNumber("Registering call in node ", D.Calls[I].FromNode, 10));
89716a497c6SRafael Auler       ++Entries[D.Calls[I].FromNode].NumCalls;
89816a497c6SRafael Auler     }
89916a497c6SRafael Auler     for (int I = 0; I < NumNodes; ++I) {
90016a497c6SRafael Auler       Entries[I].Calls = Entries[I].NumCalls ? new (Alloc)
90116a497c6SRafael Auler                                                    uint32_t[Entries[I].NumCalls]
90216a497c6SRafael Auler                                              : nullptr;
90316a497c6SRafael Auler       Entries[I].NumCalls = 0;
90416a497c6SRafael Auler     }
90516a497c6SRafael Auler     for (int I = 0; I < D.NumCalls; ++I) {
90616a497c6SRafael Auler       auto &Entry = Entries[D.Calls[I].FromNode];
90716a497c6SRafael Auler       Entry.Calls[Entry.NumCalls++] = I;
90816a497c6SRafael Auler     }
90916a497c6SRafael Auler   }
91016a497c6SRafael Auler 
91116a497c6SRafael Auler   /// Set the frequency of all calls in node \p NodeID to Freq. However, if
91216a497c6SRafael Auler   /// the calls have their own counters and do not depend on the basic block
91316a497c6SRafael Auler   /// counter, this means they have landing pads and throw exceptions. In this
91416a497c6SRafael Auler   /// case, set their frequency with their counters and return the maximum
91516a497c6SRafael Auler   /// value observed in such counters. This will be used as the new frequency
91616a497c6SRafael Auler   /// at basic block entry. This is used to fix the CFG edge frequencies in the
91716a497c6SRafael Auler   /// presence of exceptions.
91816a497c6SRafael Auler   uint64_t visitAllCallsIn(uint32_t NodeID, uint64_t Freq, uint64_t *CallFreqs,
91916a497c6SRafael Auler                            const FunctionDescription &D,
92016a497c6SRafael Auler                            const uint64_t *Counters,
92116a497c6SRafael Auler                            ProfileWriterContext &Ctx) const {
92216a497c6SRafael Auler     const auto &Entry = Entries[NodeID];
92316a497c6SRafael Auler     uint64_t MaxValue = 0ull;
92416a497c6SRafael Auler     for (int I = 0, E = Entry.NumCalls; I != E; ++I) {
92516a497c6SRafael Auler       const auto CallID = Entry.Calls[I];
92616a497c6SRafael Auler       DEBUG(reportNumber("  Setting freq for call ID: ", CallID, 10));
92716a497c6SRafael Auler       auto &CallDesc = D.Calls[CallID];
92816a497c6SRafael Auler       if (CallDesc.Counter == 0xffffffff) {
92916a497c6SRafael Auler         CallFreqs[CallID] = Freq;
93016a497c6SRafael Auler         DEBUG(reportNumber("  with : ", Freq, 10));
93116a497c6SRafael Auler       } else {
93216a497c6SRafael Auler         const auto CounterVal = Counters[CallDesc.Counter];
93316a497c6SRafael Auler         CallFreqs[CallID] = CounterVal;
93416a497c6SRafael Auler         MaxValue = CounterVal > MaxValue ? CounterVal : MaxValue;
93516a497c6SRafael Auler         DEBUG(reportNumber("  with (private counter) : ", CounterVal, 10));
93616a497c6SRafael Auler       }
93716a497c6SRafael Auler       DEBUG(reportNumber("  Address: 0x", CallDesc.TargetAddress, 16));
93816a497c6SRafael Auler       if (CallFreqs[CallID] > 0)
93916a497c6SRafael Auler         Ctx.CallFlowTable->get(CallDesc.TargetAddress).Calls +=
94016a497c6SRafael Auler             CallFreqs[CallID];
94116a497c6SRafael Auler     }
94216a497c6SRafael Auler     return MaxValue;
94316a497c6SRafael Auler   }
94416a497c6SRafael Auler 
94516a497c6SRafael Auler   ~NodeToCallsMap() {
94616a497c6SRafael Auler     for (int I = NumNodes - 1; I >= 0; --I) {
94716a497c6SRafael Auler       if (Entries[I].Calls)
94816a497c6SRafael Auler         Alloc.deallocate(Entries[I].Calls);
94916a497c6SRafael Auler     }
95016a497c6SRafael Auler     Alloc.deallocate(Entries);
95116a497c6SRafael Auler   }
95216a497c6SRafael Auler };
95316a497c6SRafael Auler 
95416a497c6SRafael Auler /// Fill an array with the frequency of each edge in the function represented
95516a497c6SRafael Auler /// by G, as well as another array for each call.
95616a497c6SRafael Auler void Graph::computeEdgeFrequencies(const uint64_t *Counters,
95716a497c6SRafael Auler                                    ProfileWriterContext &Ctx) {
95816a497c6SRafael Auler   if (NumNodes == 0)
95916a497c6SRafael Auler     return;
96016a497c6SRafael Auler 
96116a497c6SRafael Auler   EdgeFreqs = D.NumEdges ? new (Alloc, 0) uint64_t [D.NumEdges] : nullptr;
96216a497c6SRafael Auler   CallFreqs = D.NumCalls ? new (Alloc, 0) uint64_t [D.NumCalls] : nullptr;
96316a497c6SRafael Auler 
96416a497c6SRafael Auler   // Setup a lookup for calls present in each node (BB)
96516a497c6SRafael Auler   NodeToCallsMap *CallMap = new (Alloc) NodeToCallsMap(Alloc, D, NumNodes);
966cc4b2fb6SRafael Auler 
967cc4b2fb6SRafael Auler   // Perform a bottom-up, BFS traversal of the spanning tree in G. Edges in the
968cc4b2fb6SRafael Auler   // spanning tree don't have explicit counters. We must infer their value using
969cc4b2fb6SRafael Auler   // a linear combination of other counters (sum of counters of the outgoing
970cc4b2fb6SRafael Auler   // edges minus sum of counters of the incoming edges).
97116a497c6SRafael Auler   uint32_t *Stack = new (Alloc) uint32_t [NumNodes];
972cc4b2fb6SRafael Auler   uint32_t StackTop = 0;
973cc4b2fb6SRafael Auler   enum Status : uint8_t { S_NEW = 0, S_VISITING, S_VISITED };
97416a497c6SRafael Auler   Status *Visited = new (Alloc, 0) Status[NumNodes];
97516a497c6SRafael Auler   uint64_t *LeafFrequency = new (Alloc, 0) uint64_t[NumNodes];
97616a497c6SRafael Auler   uint64_t *EntryAddress = new (Alloc, 0) uint64_t[NumNodes];
977cc4b2fb6SRafael Auler 
978cc4b2fb6SRafael Auler   // Setup a fast lookup for frequency of leaf nodes, which have special
979cc4b2fb6SRafael Auler   // basic block frequency instrumentation (they are not edge profiled).
98016a497c6SRafael Auler   for (int I = 0; I < D.NumLeafNodes; ++I) {
98116a497c6SRafael Auler     LeafFrequency[D.LeafNodes[I].Node] = Counters[D.LeafNodes[I].Counter];
982cc4b2fb6SRafael Auler     DEBUG({
98316a497c6SRafael Auler       if (Counters[D.LeafNodes[I].Counter] > 0) {
98416a497c6SRafael Auler         reportNumber("Leaf Node# ", D.LeafNodes[I].Node, 10);
98516a497c6SRafael Auler         reportNumber("     Counter: ", Counters[D.LeafNodes[I].Counter], 10);
986cc4b2fb6SRafael Auler       }
987cc4b2fb6SRafael Auler     });
98816a497c6SRafael Auler   }
98916a497c6SRafael Auler   for (int I = 0; I < D.NumEntryNodes; ++I) {
99016a497c6SRafael Auler     EntryAddress[D.EntryNodes[I].Node] = D.EntryNodes[I].Address;
99116a497c6SRafael Auler     DEBUG({
99216a497c6SRafael Auler         reportNumber("Entry Node# ", D.EntryNodes[I].Node, 10);
99316a497c6SRafael Auler         reportNumber("      Address: ", D.EntryNodes[I].Address, 16);
99416a497c6SRafael Auler     });
995cc4b2fb6SRafael Auler   }
996cc4b2fb6SRafael Auler   // Add all root nodes to the stack
99716a497c6SRafael Auler   for (int I = 0; I < NumNodes; ++I) {
99816a497c6SRafael Auler     if (SpanningTreeNodes[I].NumInEdges == 0)
999cc4b2fb6SRafael Auler       Stack[StackTop++] = I;
1000cc4b2fb6SRafael Auler   }
1001cc4b2fb6SRafael Auler   // Empty stack?
1002cc4b2fb6SRafael Auler   if (StackTop == 0) {
100316a497c6SRafael Auler     DEBUG(report("Empty stack!\n"));
100416a497c6SRafael Auler     Alloc.deallocate(EntryAddress);
1005cc4b2fb6SRafael Auler     Alloc.deallocate(LeafFrequency);
1006cc4b2fb6SRafael Auler     Alloc.deallocate(Visited);
1007cc4b2fb6SRafael Auler     Alloc.deallocate(Stack);
100816a497c6SRafael Auler     CallMap->~NodeToCallsMap();
100916a497c6SRafael Auler     Alloc.deallocate(CallMap);
101016a497c6SRafael Auler     if (CallFreqs)
101116a497c6SRafael Auler       Alloc.deallocate(CallFreqs);
101216a497c6SRafael Auler     if (EdgeFreqs)
101316a497c6SRafael Auler       Alloc.deallocate(EdgeFreqs);
101416a497c6SRafael Auler     EdgeFreqs = nullptr;
101516a497c6SRafael Auler     CallFreqs = nullptr;
101616a497c6SRafael Auler     return;
1017cc4b2fb6SRafael Auler   }
1018cc4b2fb6SRafael Auler   // Add all known edge counts, will infer the rest
101916a497c6SRafael Auler   for (int I = 0; I < D.NumEdges; ++I) {
102016a497c6SRafael Auler     const uint32_t C = D.Edges[I].Counter;
1021cc4b2fb6SRafael Auler     if (C == 0xffffffff) // inferred counter - we will compute its value
1022cc4b2fb6SRafael Auler       continue;
102316a497c6SRafael Auler     EdgeFreqs[I] = Counters[C];
1024cc4b2fb6SRafael Auler   }
1025cc4b2fb6SRafael Auler 
1026cc4b2fb6SRafael Auler   while (StackTop > 0) {
1027cc4b2fb6SRafael Auler     const uint32_t Cur = Stack[--StackTop];
1028cc4b2fb6SRafael Auler     DEBUG({
1029cc4b2fb6SRafael Auler       if (Visited[Cur] == S_VISITING)
1030cc4b2fb6SRafael Auler         report("(visiting) ");
1031cc4b2fb6SRafael Auler       else
1032cc4b2fb6SRafael Auler         report("(new) ");
1033cc4b2fb6SRafael Auler       reportNumber("Cur: ", Cur, 10);
1034cc4b2fb6SRafael Auler     });
1035cc4b2fb6SRafael Auler 
1036cc4b2fb6SRafael Auler     // This shouldn't happen in a tree
1037cc4b2fb6SRafael Auler     assert(Visited[Cur] != S_VISITED, "should not have visited nodes in stack");
1038cc4b2fb6SRafael Auler     if (Visited[Cur] == S_NEW) {
1039cc4b2fb6SRafael Auler       Visited[Cur] = S_VISITING;
1040cc4b2fb6SRafael Auler       Stack[StackTop++] = Cur;
104116a497c6SRafael Auler       assert(StackTop <= NumNodes, "stack grew too large");
104216a497c6SRafael Auler       for (int I = 0, E = SpanningTreeNodes[Cur].NumOutEdges; I < E; ++I) {
104316a497c6SRafael Auler         const uint32_t Succ = SpanningTreeNodes[Cur].OutEdges[I].Node;
1044cc4b2fb6SRafael Auler         Stack[StackTop++] = Succ;
104516a497c6SRafael Auler         assert(StackTop <= NumNodes, "stack grew too large");
1046cc4b2fb6SRafael Auler      }
1047cc4b2fb6SRafael Auler       continue;
1048cc4b2fb6SRafael Auler     }
1049cc4b2fb6SRafael Auler     Visited[Cur] = S_VISITED;
1050cc4b2fb6SRafael Auler 
1051cc4b2fb6SRafael Auler     // Establish our node frequency based on outgoing edges, which should all be
1052cc4b2fb6SRafael Auler     // resolved by now.
1053cc4b2fb6SRafael Auler     int64_t CurNodeFreq = LeafFrequency[Cur];
1054cc4b2fb6SRafael Auler     // Not a leaf?
1055cc4b2fb6SRafael Auler     if (!CurNodeFreq) {
105616a497c6SRafael Auler       for (int I = 0, E = CFGNodes[Cur].NumOutEdges; I != E; ++I) {
105716a497c6SRafael Auler         const uint32_t SuccEdge = CFGNodes[Cur].OutEdges[I].ID;
105816a497c6SRafael Auler         CurNodeFreq += EdgeFreqs[SuccEdge];
1059cc4b2fb6SRafael Auler       }
1060cc4b2fb6SRafael Auler     }
106116a497c6SRafael Auler     if (CurNodeFreq < 0)
106216a497c6SRafael Auler       CurNodeFreq = 0;
106316a497c6SRafael Auler 
106416a497c6SRafael Auler     const uint64_t CallFreq = CallMap->visitAllCallsIn(
106516a497c6SRafael Auler         Cur, CurNodeFreq > 0 ? CurNodeFreq : 0, CallFreqs, D, Counters, Ctx);
106616a497c6SRafael Auler 
106716a497c6SRafael Auler     // Exception handling affected our output flow? Fix with calls info
106816a497c6SRafael Auler     DEBUG({
106916a497c6SRafael Auler       if (CallFreq > CurNodeFreq)
107016a497c6SRafael Auler         report("Bumping node frequency with call info\n");
107116a497c6SRafael Auler     });
107216a497c6SRafael Auler     CurNodeFreq = CallFreq > CurNodeFreq ? CallFreq : CurNodeFreq;
107316a497c6SRafael Auler 
107416a497c6SRafael Auler     if (CurNodeFreq > 0) {
107516a497c6SRafael Auler       if (uint64_t Addr = EntryAddress[Cur]) {
107616a497c6SRafael Auler         DEBUG(
107716a497c6SRafael Auler             reportNumber("  Setting flow at entry point address 0x", Addr, 16));
107816a497c6SRafael Auler         DEBUG(reportNumber("  with: ", CurNodeFreq, 10));
107916a497c6SRafael Auler         Ctx.CallFlowTable->get(Addr).Val = CurNodeFreq;
108016a497c6SRafael Auler       }
108116a497c6SRafael Auler     }
108216a497c6SRafael Auler 
108316a497c6SRafael Auler     // No parent? Reached a tree root, limit to call frequency updating.
108416a497c6SRafael Auler     if (SpanningTreeNodes[Cur].NumInEdges == 0) {
108516a497c6SRafael Auler       continue;
108616a497c6SRafael Auler     }
108716a497c6SRafael Auler 
108816a497c6SRafael Auler     assert(SpanningTreeNodes[Cur].NumInEdges == 1, "must have 1 parent");
108916a497c6SRafael Auler     const uint32_t Parent = SpanningTreeNodes[Cur].InEdges[0].Node;
109016a497c6SRafael Auler     const uint32_t ParentEdge = SpanningTreeNodes[Cur].InEdges[0].ID;
109116a497c6SRafael Auler 
1092cc4b2fb6SRafael Auler     // Calculate parent edge freq.
109316a497c6SRafael Auler     int64_t ParentEdgeFreq = CurNodeFreq;
109416a497c6SRafael Auler     for (int I = 0, E = CFGNodes[Cur].NumInEdges; I != E; ++I) {
109516a497c6SRafael Auler       const uint32_t PredEdge = CFGNodes[Cur].InEdges[I].ID;
109616a497c6SRafael Auler       ParentEdgeFreq -= EdgeFreqs[PredEdge];
1097cc4b2fb6SRafael Auler     }
109816a497c6SRafael Auler 
1099cc4b2fb6SRafael Auler     // Sometimes the conservative CFG that BOLT builds will lead to incorrect
1100cc4b2fb6SRafael Auler     // flow computation. For example, in a BB that transitively calls the exit
1101cc4b2fb6SRafael Auler     // syscall, BOLT will add a fall-through successor even though it should not
1102cc4b2fb6SRafael Auler     // have any successors. So this block execution will likely be wrong. We
1103cc4b2fb6SRafael Auler     // tolerate this imperfection since this case should be quite infrequent.
1104cc4b2fb6SRafael Auler     if (ParentEdgeFreq < 0) {
110516a497c6SRafael Auler       DEBUG(dumpEdgeFreqs());
1106cc4b2fb6SRafael Auler       DEBUG(report("WARNING: incorrect flow"));
1107cc4b2fb6SRafael Auler       ParentEdgeFreq = 0;
1108cc4b2fb6SRafael Auler     }
1109cc4b2fb6SRafael Auler     DEBUG(reportNumber("  Setting freq for ParentEdge: ", ParentEdge, 10));
1110cc4b2fb6SRafael Auler     DEBUG(reportNumber("  with ParentEdgeFreq: ", ParentEdgeFreq, 10));
111116a497c6SRafael Auler     EdgeFreqs[ParentEdge] = ParentEdgeFreq;
1112cc4b2fb6SRafael Auler   }
1113cc4b2fb6SRafael Auler 
111416a497c6SRafael Auler   Alloc.deallocate(EntryAddress);
1115cc4b2fb6SRafael Auler   Alloc.deallocate(LeafFrequency);
1116cc4b2fb6SRafael Auler   Alloc.deallocate(Visited);
1117cc4b2fb6SRafael Auler   Alloc.deallocate(Stack);
111816a497c6SRafael Auler   CallMap->~NodeToCallsMap();
111916a497c6SRafael Auler   Alloc.deallocate(CallMap);
112016a497c6SRafael Auler   DEBUG(dumpEdgeFreqs());
1121cc4b2fb6SRafael Auler }
1122cc4b2fb6SRafael Auler 
112316a497c6SRafael Auler /// Write to \p FD all of the edge profiles for function \p FuncDesc. Uses
112416a497c6SRafael Auler /// \p Alloc to allocate helper dynamic structures used to compute profile for
112516a497c6SRafael Auler /// edges that we do not explictly instrument.
112616a497c6SRafael Auler const uint8_t *writeFunctionProfile(int FD, ProfileWriterContext &Ctx,
112716a497c6SRafael Auler                                     const uint8_t *FuncDesc,
112816a497c6SRafael Auler                                     BumpPtrAllocator &Alloc) {
112916a497c6SRafael Auler   const FunctionDescription F(FuncDesc);
113016a497c6SRafael Auler   const uint8_t *next = FuncDesc + F.getSize();
1131cc4b2fb6SRafael Auler 
1132a0dd5b05SAlexander Shaposhnikov #if !defined(__APPLE__)
1133a0dd5b05SAlexander Shaposhnikov   uint64_t *bolt_instr_locations = __bolt_instr_locations;
1134a0dd5b05SAlexander Shaposhnikov #else
1135a0dd5b05SAlexander Shaposhnikov   uint64_t *bolt_instr_locations = _bolt_instr_locations_getter();
1136a0dd5b05SAlexander Shaposhnikov #endif
1137a0dd5b05SAlexander Shaposhnikov 
1138cc4b2fb6SRafael Auler   // Skip funcs we know are cold
1139cc4b2fb6SRafael Auler #ifndef ENABLE_DEBUG
114016a497c6SRafael Auler   uint64_t CountersFreq = 0;
114116a497c6SRafael Auler   for (int I = 0; I < F.NumLeafNodes; ++I) {
1142a0dd5b05SAlexander Shaposhnikov     CountersFreq += bolt_instr_locations[F.LeafNodes[I].Counter];
1143cc4b2fb6SRafael Auler   }
114416a497c6SRafael Auler   if (CountersFreq == 0) {
114516a497c6SRafael Auler     for (int I = 0; I < F.NumEdges; ++I) {
114616a497c6SRafael Auler       const uint32_t C = F.Edges[I].Counter;
114716a497c6SRafael Auler       if (C == 0xffffffff)
114816a497c6SRafael Auler         continue;
1149a0dd5b05SAlexander Shaposhnikov       CountersFreq += bolt_instr_locations[C];
115016a497c6SRafael Auler     }
115116a497c6SRafael Auler     if (CountersFreq == 0) {
115216a497c6SRafael Auler       for (int I = 0; I < F.NumCalls; ++I) {
115316a497c6SRafael Auler         const uint32_t C = F.Calls[I].Counter;
115416a497c6SRafael Auler         if (C == 0xffffffff)
115516a497c6SRafael Auler           continue;
1156a0dd5b05SAlexander Shaposhnikov         CountersFreq += bolt_instr_locations[C];
115716a497c6SRafael Auler       }
115816a497c6SRafael Auler       if (CountersFreq == 0)
1159cc4b2fb6SRafael Auler         return next;
116016a497c6SRafael Auler     }
116116a497c6SRafael Auler   }
1162cc4b2fb6SRafael Auler #endif
1163cc4b2fb6SRafael Auler 
1164a0dd5b05SAlexander Shaposhnikov   Graph *G = new (Alloc) Graph(Alloc, F, bolt_instr_locations, Ctx);
1165cc4b2fb6SRafael Auler   DEBUG(G->dump());
1166a0dd5b05SAlexander Shaposhnikov 
116716a497c6SRafael Auler   if (!G->EdgeFreqs && !G->CallFreqs) {
1168cc4b2fb6SRafael Auler     G->~Graph();
1169cc4b2fb6SRafael Auler     Alloc.deallocate(G);
1170cc4b2fb6SRafael Auler     return next;
1171cc4b2fb6SRafael Auler   }
1172cc4b2fb6SRafael Auler 
117316a497c6SRafael Auler   for (int I = 0; I < F.NumEdges; ++I) {
117416a497c6SRafael Auler     const uint64_t Freq = G->EdgeFreqs[I];
1175cc4b2fb6SRafael Auler     if (Freq == 0)
1176cc4b2fb6SRafael Auler       continue;
117716a497c6SRafael Auler     const EdgeDescription *Desc = &F.Edges[I];
1178cc4b2fb6SRafael Auler     char LineBuf[BufSize];
1179cc4b2fb6SRafael Auler     char *Ptr = LineBuf;
118016a497c6SRafael Auler     Ptr = serializeLoc(Ctx, Ptr, Desc->From, BufSize);
118116a497c6SRafael Auler     Ptr = serializeLoc(Ctx, Ptr, Desc->To, BufSize - (Ptr - LineBuf));
1182cc4b2fb6SRafael Auler     Ptr = strCopy(Ptr, "0 ", BufSize - (Ptr - LineBuf) - 22);
1183cc4b2fb6SRafael Auler     Ptr = intToStr(Ptr, Freq, 10);
1184cc4b2fb6SRafael Auler     *Ptr++ = '\n';
1185cc4b2fb6SRafael Auler     __write(FD, LineBuf, Ptr - LineBuf);
1186cc4b2fb6SRafael Auler   }
1187cc4b2fb6SRafael Auler 
118816a497c6SRafael Auler   for (int I = 0; I < F.NumCalls; ++I) {
118916a497c6SRafael Auler     const uint64_t Freq = G->CallFreqs[I];
119016a497c6SRafael Auler     if (Freq == 0)
119116a497c6SRafael Auler       continue;
119216a497c6SRafael Auler     char LineBuf[BufSize];
119316a497c6SRafael Auler     char *Ptr = LineBuf;
119416a497c6SRafael Auler     const CallDescription *Desc = &F.Calls[I];
119516a497c6SRafael Auler     Ptr = serializeLoc(Ctx, Ptr, Desc->From, BufSize);
119616a497c6SRafael Auler     Ptr = serializeLoc(Ctx, Ptr, Desc->To, BufSize - (Ptr - LineBuf));
119716a497c6SRafael Auler     Ptr = strCopy(Ptr, "0 ", BufSize - (Ptr - LineBuf) - 25);
119816a497c6SRafael Auler     Ptr = intToStr(Ptr, Freq, 10);
119916a497c6SRafael Auler     *Ptr++ = '\n';
120016a497c6SRafael Auler     __write(FD, LineBuf, Ptr - LineBuf);
120116a497c6SRafael Auler   }
120216a497c6SRafael Auler 
1203cc4b2fb6SRafael Auler   G->~Graph();
1204cc4b2fb6SRafael Auler   Alloc.deallocate(G);
1205cc4b2fb6SRafael Auler   return next;
1206cc4b2fb6SRafael Auler }
1207cc4b2fb6SRafael Auler 
1208a0dd5b05SAlexander Shaposhnikov #if !defined(__APPLE__)
120916a497c6SRafael Auler const IndCallTargetDescription *
121016a497c6SRafael Auler ProfileWriterContext::lookupIndCallTarget(uint64_t Target) const {
121116a497c6SRafael Auler   uint32_t B = 0;
121216a497c6SRafael Auler   uint32_t E = __bolt_instr_num_ind_targets;
121316a497c6SRafael Auler   if (E == 0)
121416a497c6SRafael Auler     return nullptr;
121516a497c6SRafael Auler   do {
121616a497c6SRafael Auler     uint32_t I = (E - B) / 2 + B;
121716a497c6SRafael Auler     if (IndCallTargets[I].Address == Target)
121816a497c6SRafael Auler       return &IndCallTargets[I];
121916a497c6SRafael Auler     if (IndCallTargets[I].Address < Target)
122016a497c6SRafael Auler       B = I + 1;
122116a497c6SRafael Auler     else
122216a497c6SRafael Auler       E = I;
122316a497c6SRafael Auler   } while (B < E);
122416a497c6SRafael Auler   return nullptr;
1225cc4b2fb6SRafael Auler }
122662aa74f8SRafael Auler 
122716a497c6SRafael Auler /// Write a single indirect call <src, target> pair to the fdata file
122816a497c6SRafael Auler void visitIndCallCounter(IndirectCallHashTable::MapEntry &Entry,
122916a497c6SRafael Auler                          int FD, int CallsiteID,
123016a497c6SRafael Auler                          ProfileWriterContext *Ctx) {
123116a497c6SRafael Auler   if (Entry.Val == 0)
123216a497c6SRafael Auler     return;
123316a497c6SRafael Auler   DEBUG(reportNumber("Target func 0x", Entry.Key, 16));
123416a497c6SRafael Auler   DEBUG(reportNumber("Target freq: ", Entry.Val, 10));
123516a497c6SRafael Auler   const IndCallDescription *CallsiteDesc =
123616a497c6SRafael Auler       &Ctx->IndCallDescriptions[CallsiteID];
123716a497c6SRafael Auler   const IndCallTargetDescription *TargetDesc =
123816a497c6SRafael Auler       Ctx->lookupIndCallTarget(Entry.Key);
123916a497c6SRafael Auler   if (!TargetDesc) {
124016a497c6SRafael Auler     DEBUG(report("Failed to lookup indirect call target\n"));
1241cc4b2fb6SRafael Auler     char LineBuf[BufSize];
124262aa74f8SRafael Auler     char *Ptr = LineBuf;
124316a497c6SRafael Auler     Ptr = serializeLoc(*Ctx, Ptr, *CallsiteDesc, BufSize);
124416a497c6SRafael Auler     Ptr = strCopy(Ptr, "0 [unknown] 0 0 ", BufSize - (Ptr - LineBuf) - 40);
124516a497c6SRafael Auler     Ptr = intToStr(Ptr, Entry.Val, 10);
124616a497c6SRafael Auler     *Ptr++ = '\n';
124716a497c6SRafael Auler     __write(FD, LineBuf, Ptr - LineBuf);
124816a497c6SRafael Auler     return;
124916a497c6SRafael Auler   }
125016a497c6SRafael Auler   Ctx->CallFlowTable->get(TargetDesc->Address).Calls += Entry.Val;
125116a497c6SRafael Auler   char LineBuf[BufSize];
125216a497c6SRafael Auler   char *Ptr = LineBuf;
125316a497c6SRafael Auler   Ptr = serializeLoc(*Ctx, Ptr, *CallsiteDesc, BufSize);
125416a497c6SRafael Auler   Ptr = serializeLoc(*Ctx, Ptr, TargetDesc->Loc, BufSize - (Ptr - LineBuf));
1255cc4b2fb6SRafael Auler   Ptr = strCopy(Ptr, "0 ", BufSize - (Ptr - LineBuf) - 25);
125616a497c6SRafael Auler   Ptr = intToStr(Ptr, Entry.Val, 10);
125762aa74f8SRafael Auler   *Ptr++ = '\n';
1258821480d2SRafael Auler   __write(FD, LineBuf, Ptr - LineBuf);
125962aa74f8SRafael Auler }
1260cc4b2fb6SRafael Auler 
126116a497c6SRafael Auler /// Write to \p FD all of the indirect call profiles.
126216a497c6SRafael Auler void writeIndirectCallProfile(int FD, ProfileWriterContext &Ctx) {
126316a497c6SRafael Auler   for (int I = 0; I < __bolt_instr_num_ind_calls; ++I) {
126416a497c6SRafael Auler     DEBUG(reportNumber("IndCallsite #", I, 10));
126516a497c6SRafael Auler     GlobalIndCallCounters[I].forEachElement(visitIndCallCounter, FD, I, &Ctx);
126616a497c6SRafael Auler   }
126716a497c6SRafael Auler }
126816a497c6SRafael Auler 
126916a497c6SRafael Auler /// Check a single call flow for a callee versus all known callers. If there are
127016a497c6SRafael Auler /// less callers than what the callee expects, write the difference with source
127116a497c6SRafael Auler /// [unknown] in the profile.
127216a497c6SRafael Auler void visitCallFlowEntry(CallFlowHashTable::MapEntry &Entry, int FD,
127316a497c6SRafael Auler                         ProfileWriterContext *Ctx) {
127416a497c6SRafael Auler   DEBUG(reportNumber("Call flow entry address: 0x", Entry.Key, 16));
127516a497c6SRafael Auler   DEBUG(reportNumber("Calls: ", Entry.Calls, 10));
127616a497c6SRafael Auler   DEBUG(reportNumber("Reported entry frequency: ", Entry.Val, 10));
127716a497c6SRafael Auler   DEBUG({
127816a497c6SRafael Auler     if (Entry.Calls > Entry.Val)
127916a497c6SRafael Auler       report("  More calls than expected!\n");
128016a497c6SRafael Auler   });
128116a497c6SRafael Auler   if (Entry.Val <= Entry.Calls)
128216a497c6SRafael Auler     return;
128316a497c6SRafael Auler   DEBUG(reportNumber(
128416a497c6SRafael Auler       "  Balancing calls with traffic: ", Entry.Val - Entry.Calls, 10));
128516a497c6SRafael Auler   const IndCallTargetDescription *TargetDesc =
128616a497c6SRafael Auler       Ctx->lookupIndCallTarget(Entry.Key);
128716a497c6SRafael Auler   if (!TargetDesc) {
128816a497c6SRafael Auler     // There is probably something wrong with this callee and this should be
128916a497c6SRafael Auler     // investigated, but I don't want to assert and lose all data collected.
129016a497c6SRafael Auler     DEBUG(report("WARNING: failed to look up call target!\n"));
129116a497c6SRafael Auler     return;
129216a497c6SRafael Auler   }
129316a497c6SRafael Auler   char LineBuf[BufSize];
129416a497c6SRafael Auler   char *Ptr = LineBuf;
129516a497c6SRafael Auler   Ptr = strCopy(Ptr, "0 [unknown] 0 ", BufSize);
129616a497c6SRafael Auler   Ptr = serializeLoc(*Ctx, Ptr, TargetDesc->Loc, BufSize - (Ptr - LineBuf));
129716a497c6SRafael Auler   Ptr = strCopy(Ptr, "0 ", BufSize - (Ptr - LineBuf) - 25);
129816a497c6SRafael Auler   Ptr = intToStr(Ptr, Entry.Val - Entry.Calls, 10);
129916a497c6SRafael Auler   *Ptr++ = '\n';
130016a497c6SRafael Auler   __write(FD, LineBuf, Ptr - LineBuf);
130116a497c6SRafael Auler }
130216a497c6SRafael Auler 
130316a497c6SRafael Auler /// Open fdata file for writing and return a valid file descriptor, aborting
130416a497c6SRafael Auler /// program upon failure.
130516a497c6SRafael Auler int openProfile() {
130616a497c6SRafael Auler   // Build the profile name string by appending our PID
130716a497c6SRafael Auler   char Buf[BufSize];
130816a497c6SRafael Auler   char *Ptr = Buf;
130916a497c6SRafael Auler   uint64_t PID = __getpid();
131016a497c6SRafael Auler   Ptr = strCopy(Buf, __bolt_instr_filename, BufSize);
131116a497c6SRafael Auler   if (__bolt_instr_use_pid) {
131216a497c6SRafael Auler     Ptr = strCopy(Ptr, ".", BufSize - (Ptr - Buf + 1));
131316a497c6SRafael Auler     Ptr = intToStr(Ptr, PID, 10);
131416a497c6SRafael Auler     Ptr = strCopy(Ptr, ".fdata", BufSize - (Ptr - Buf + 1));
131516a497c6SRafael Auler   }
131616a497c6SRafael Auler   *Ptr++ = '\0';
131716a497c6SRafael Auler   uint64_t FD = __open(Buf,
131816a497c6SRafael Auler                        /*flags=*/0x241 /*O_WRONLY|O_TRUNC|O_CREAT*/,
131916a497c6SRafael Auler                        /*mode=*/0666);
132016a497c6SRafael Auler   if (static_cast<int64_t>(FD) < 0) {
132116a497c6SRafael Auler     report("Error while trying to open profile file for writing: ");
132216a497c6SRafael Auler     report(Buf);
132316a497c6SRafael Auler     reportNumber("\nFailed with error number: 0x",
132416a497c6SRafael Auler                  0 - static_cast<int64_t>(FD), 16);
132516a497c6SRafael Auler     __exit(1);
132616a497c6SRafael Auler   }
132716a497c6SRafael Auler   return FD;
132816a497c6SRafael Auler }
1329a0dd5b05SAlexander Shaposhnikov 
1330a0dd5b05SAlexander Shaposhnikov #endif
1331a0dd5b05SAlexander Shaposhnikov 
133216a497c6SRafael Auler } // anonymous namespace
133316a497c6SRafael Auler 
1334a0dd5b05SAlexander Shaposhnikov #if !defined(__APPLE__)
1335a0dd5b05SAlexander Shaposhnikov 
133616a497c6SRafael Auler /// Reset all counters in case you want to start profiling a new phase of your
133716a497c6SRafael Auler /// program independently of prior phases.
133816a497c6SRafael Auler /// The address of this function is printed by BOLT and this can be called by
133916a497c6SRafael Auler /// any attached debugger during runtime. There is a useful oneliner for gdb:
134016a497c6SRafael Auler ///
134116a497c6SRafael Auler ///   gdb -p $(pgrep -xo PROCESSNAME) -ex 'p ((void(*)())0xdeadbeef)()' \
134216a497c6SRafael Auler ///     -ex 'set confirm off' -ex quit
134316a497c6SRafael Auler ///
134416a497c6SRafael Auler /// Where 0xdeadbeef is this function address and PROCESSNAME your binary file
134516a497c6SRafael Auler /// name.
134616a497c6SRafael Auler extern "C" void __bolt_instr_clear_counters() {
134716a497c6SRafael Auler   memSet(reinterpret_cast<char *>(__bolt_instr_locations), 0,
134816a497c6SRafael Auler          __bolt_num_counters * 8);
134916a497c6SRafael Auler   for (int I = 0; I < __bolt_instr_num_ind_calls; ++I) {
135016a497c6SRafael Auler     GlobalIndCallCounters[I].resetCounters();
135116a497c6SRafael Auler   }
135216a497c6SRafael Auler }
135316a497c6SRafael Auler 
135416a497c6SRafael Auler /// This is the entry point for profile writing.
135516a497c6SRafael Auler /// There are three ways of getting here:
135616a497c6SRafael Auler ///
135716a497c6SRafael Auler ///  * Program execution ended, finalization methods are running and BOLT
135816a497c6SRafael Auler ///    hooked into FINI from your binary dynamic section;
135916a497c6SRafael Auler ///  * You used the sleep timer option and during initialization we forked
136016a497c6SRafael Auler ///    a separete process that will call this function periodically;
136116a497c6SRafael Auler ///  * BOLT prints this function address so you can attach a debugger and
136216a497c6SRafael Auler ///    call this function directly to get your profile written to disk
136316a497c6SRafael Auler ///    on demand.
136416a497c6SRafael Auler ///
136516a497c6SRafael Auler extern "C" void __bolt_instr_data_dump() {
136616a497c6SRafael Auler   // Already dumping
136716a497c6SRafael Auler   if (!GlobalWriteProfileMutex->acquire())
136816a497c6SRafael Auler     return;
136916a497c6SRafael Auler 
137016a497c6SRafael Auler   BumpPtrAllocator HashAlloc;
137116a497c6SRafael Auler   HashAlloc.setMaxSize(0x6400000);
137216a497c6SRafael Auler   ProfileWriterContext Ctx = readDescriptions();
137316a497c6SRafael Auler   Ctx.CallFlowTable = new (HashAlloc, 0) CallFlowHashTable(HashAlloc);
137416a497c6SRafael Auler 
137516a497c6SRafael Auler   DEBUG(printStats(Ctx));
137616a497c6SRafael Auler 
137716a497c6SRafael Auler   int FD = openProfile();
137816a497c6SRafael Auler 
1379cc4b2fb6SRafael Auler   BumpPtrAllocator Alloc;
138016a497c6SRafael Auler   const uint8_t *FuncDesc = Ctx.FuncDescriptions;
1381cc4b2fb6SRafael Auler   for (int I = 0, E = __bolt_instr_num_funcs; I < E; ++I) {
138216a497c6SRafael Auler     FuncDesc = writeFunctionProfile(FD, Ctx, FuncDesc, Alloc);
138316a497c6SRafael Auler     Alloc.clear();
1384cc4b2fb6SRafael Auler     DEBUG(reportNumber("FuncDesc now: ", (uint64_t)FuncDesc, 16));
1385cc4b2fb6SRafael Auler   }
138616a497c6SRafael Auler   assert(FuncDesc == (void *)Ctx.Strings,
1387cc4b2fb6SRafael Auler          "FuncDesc ptr must be equal to stringtable");
1388cc4b2fb6SRafael Auler 
138916a497c6SRafael Auler   writeIndirectCallProfile(FD, Ctx);
139016a497c6SRafael Auler   Ctx.CallFlowTable->forEachElement(visitCallFlowEntry, FD, &Ctx);
139116a497c6SRafael Auler 
1392821480d2SRafael Auler   __close(FD);
139316a497c6SRafael Auler   __munmap(Ctx.MMapPtr, Ctx.MMapSize);
139416a497c6SRafael Auler   __close(Ctx.FileDesc);
139516a497c6SRafael Auler   HashAlloc.destroy();
139616a497c6SRafael Auler   GlobalWriteProfileMutex->release();
139716a497c6SRafael Auler   DEBUG(report("Finished writing profile.\n"));
139816a497c6SRafael Auler }
139916a497c6SRafael Auler 
140016a497c6SRafael Auler /// Event loop for our child process spawned during setup to dump profile data
140116a497c6SRafael Auler /// at user-specified intervals
140216a497c6SRafael Auler void watchProcess() {
140316a497c6SRafael Auler   timespec ts, rem;
140416a497c6SRafael Auler   uint64_t Ellapsed = 0ull;
140516a497c6SRafael Auler   ts.tv_sec = 1;
140616a497c6SRafael Auler   ts.tv_nsec = 0;
140716a497c6SRafael Auler   while (1) {
140816a497c6SRafael Auler     __nanosleep(&ts, &rem);
140916a497c6SRafael Auler     // This means our parent process died, so no need for us to keep dumping.
141016a497c6SRafael Auler     // Notice that make and some systems will wait until all child processes
141116a497c6SRafael Auler     // of a command finishes before proceeding, so it is important to exit as
141216a497c6SRafael Auler     // early as possible once our parent dies.
141316a497c6SRafael Auler     if (__getppid() == 1) {
141416a497c6SRafael Auler       break;
141516a497c6SRafael Auler     }
141616a497c6SRafael Auler     if (++Ellapsed < __bolt_instr_sleep_time)
141716a497c6SRafael Auler       continue;
141816a497c6SRafael Auler     Ellapsed = 0;
141916a497c6SRafael Auler     __bolt_instr_data_dump();
142016a497c6SRafael Auler     __bolt_instr_clear_counters();
142116a497c6SRafael Auler   }
142216a497c6SRafael Auler   DEBUG(report("My parent process is dead, bye!\n"));
142316a497c6SRafael Auler   __exit(0);
142416a497c6SRafael Auler }
142516a497c6SRafael Auler 
142616a497c6SRafael Auler extern "C" void __bolt_instr_indirect_call();
142716a497c6SRafael Auler extern "C" void __bolt_instr_indirect_tailcall();
142816a497c6SRafael Auler 
142916a497c6SRafael Auler /// Initialization code
143016a497c6SRafael Auler extern "C" void __bolt_instr_setup() {
143116a497c6SRafael Auler   const uint64_t CountersStart =
143216a497c6SRafael Auler       reinterpret_cast<uint64_t>(&__bolt_instr_locations[0]);
143316a497c6SRafael Auler   const uint64_t CountersEnd = alignTo(
143416a497c6SRafael Auler       reinterpret_cast<uint64_t>(&__bolt_instr_locations[__bolt_num_counters]),
143516a497c6SRafael Auler       0x1000);
143616a497c6SRafael Auler   DEBUG(reportNumber("replace mmap start: ", CountersStart, 16));
143716a497c6SRafael Auler   DEBUG(reportNumber("replace mmap stop: ", CountersEnd, 16));
143816a497c6SRafael Auler   assert (CountersEnd > CountersStart, "no counters");
143916a497c6SRafael Auler   // Maps our counters to be shared instead of private, so we keep counting for
144016a497c6SRafael Auler   // forked processes
144116a497c6SRafael Auler   __mmap(CountersStart, CountersEnd - CountersStart,
144216a497c6SRafael Auler          0x3 /*PROT_READ|PROT_WRITE*/,
144316a497c6SRafael Auler          0x31 /*MAP_ANONYMOUS | MAP_SHARED | MAP_FIXED*/, -1, 0);
144416a497c6SRafael Auler 
144516a497c6SRafael Auler   __bolt_trampoline_ind_call = __bolt_instr_indirect_call;
144616a497c6SRafael Auler   __bolt_trampoline_ind_tailcall = __bolt_instr_indirect_tailcall;
144716a497c6SRafael Auler   // Conservatively reserve 100MiB shared pages
144816a497c6SRafael Auler   GlobalAlloc.setMaxSize(0x6400000);
144916a497c6SRafael Auler   GlobalAlloc.setShared(true);
145016a497c6SRafael Auler   GlobalWriteProfileMutex = new (GlobalAlloc, 0) Mutex();
145116a497c6SRafael Auler   if (__bolt_instr_num_ind_calls > 0)
145216a497c6SRafael Auler     GlobalIndCallCounters =
145316a497c6SRafael Auler         new (GlobalAlloc, 0) IndirectCallHashTable[__bolt_instr_num_ind_calls];
145416a497c6SRafael Auler 
145516a497c6SRafael Auler   if (__bolt_instr_sleep_time != 0) {
145616a497c6SRafael Auler     if (auto PID = __fork())
145716a497c6SRafael Auler       return;
145816a497c6SRafael Auler     watchProcess();
145916a497c6SRafael Auler   }
146016a497c6SRafael Auler }
146116a497c6SRafael Auler 
146216a497c6SRafael Auler extern "C" void instrumentIndirectCall(uint64_t Target, uint64_t IndCallID) {
146316a497c6SRafael Auler   GlobalIndCallCounters[IndCallID].incrementVal(Target, GlobalAlloc);
146416a497c6SRafael Auler }
146516a497c6SRafael Auler 
146616a497c6SRafael Auler /// We receive as in-stack arguments the identifier of the indirect call site
146716a497c6SRafael Auler /// as well as the target address for the call
146816a497c6SRafael Auler extern "C" __attribute((naked)) void __bolt_instr_indirect_call()
146916a497c6SRafael Auler {
147016a497c6SRafael Auler   __asm__ __volatile__(SAVE_ALL
1471c6799a68SRafael Auler                        "mov 0x90(%%rsp), %%rdi\n"
1472c6799a68SRafael Auler                        "mov 0x88(%%rsp), %%rsi\n"
147316a497c6SRafael Auler                        "call instrumentIndirectCall\n"
147416a497c6SRafael Auler                        RESTORE_ALL
147516a497c6SRafael Auler                        "pop %%rdi\n"
147616a497c6SRafael Auler                        "add $16, %%rsp\n"
147716a497c6SRafael Auler                        "xchg (%%rsp), %%rdi\n"
147816a497c6SRafael Auler                        "jmp *-8(%%rsp)\n"
147916a497c6SRafael Auler                        :::);
148016a497c6SRafael Auler }
148116a497c6SRafael Auler 
148216a497c6SRafael Auler extern "C" __attribute((naked)) void __bolt_instr_indirect_tailcall()
148316a497c6SRafael Auler {
148416a497c6SRafael Auler   __asm__ __volatile__(SAVE_ALL
1485c6799a68SRafael Auler                        "mov 0x88(%%rsp), %%rdi\n"
1486c6799a68SRafael Auler                        "mov 0x80(%%rsp), %%rsi\n"
148716a497c6SRafael Auler                        "call instrumentIndirectCall\n"
148816a497c6SRafael Auler                        RESTORE_ALL
148916a497c6SRafael Auler                        "add $16, %%rsp\n"
149016a497c6SRafael Auler                        "pop %%rdi\n"
149116a497c6SRafael Auler                        "jmp *-16(%%rsp)\n"
149216a497c6SRafael Auler                        :::);
149316a497c6SRafael Auler }
149416a497c6SRafael Auler 
149516a497c6SRafael Auler /// This is hooking ELF's entry, it needs to save all machine state.
149616a497c6SRafael Auler extern "C" __attribute((naked)) void __bolt_instr_start()
149716a497c6SRafael Auler {
149816a497c6SRafael Auler   __asm__ __volatile__(SAVE_ALL
149916a497c6SRafael Auler                        "call __bolt_instr_setup\n"
150016a497c6SRafael Auler                        RESTORE_ALL
15018c7f524aSAlexander Shaposhnikov                        "jmp *__bolt_instr_init_ptr(%%rip)\n"
150216a497c6SRafael Auler                        :::);
150316a497c6SRafael Auler }
150416a497c6SRafael Auler 
150516a497c6SRafael Auler /// This is hooking into ELF's DT_FINI
150616a497c6SRafael Auler extern "C" void __bolt_instr_fini() {
150716a497c6SRafael Auler   __bolt_instr_fini_ptr();
150816a497c6SRafael Auler   if (__bolt_instr_sleep_time == 0)
150916a497c6SRafael Auler     __bolt_instr_data_dump();
151016a497c6SRafael Auler   DEBUG(report("Finished.\n"));
151162aa74f8SRafael Auler }
1512bbd9d610SAlexander Shaposhnikov 
15133b876cc3SAlexander Shaposhnikov #endif
15143b876cc3SAlexander Shaposhnikov 
15153b876cc3SAlexander Shaposhnikov #if defined(__APPLE__)
1516bbd9d610SAlexander Shaposhnikov 
1517a0dd5b05SAlexander Shaposhnikov extern "C" void __bolt_instr_data_dump() {
1518a0dd5b05SAlexander Shaposhnikov   ProfileWriterContext Ctx = readDescriptions();
1519a0dd5b05SAlexander Shaposhnikov 
1520a0dd5b05SAlexander Shaposhnikov   int FD = 2;
1521a0dd5b05SAlexander Shaposhnikov   BumpPtrAllocator Alloc;
1522a0dd5b05SAlexander Shaposhnikov   const uint8_t *FuncDesc = Ctx.FuncDescriptions;
1523a0dd5b05SAlexander Shaposhnikov   uint32_t bolt_instr_num_funcs = _bolt_instr_num_funcs_getter();
1524a0dd5b05SAlexander Shaposhnikov 
1525a0dd5b05SAlexander Shaposhnikov   for (int I = 0, E = bolt_instr_num_funcs; I < E; ++I) {
1526a0dd5b05SAlexander Shaposhnikov     FuncDesc = writeFunctionProfile(FD, Ctx, FuncDesc, Alloc);
1527a0dd5b05SAlexander Shaposhnikov     Alloc.clear();
1528a0dd5b05SAlexander Shaposhnikov     DEBUG(reportNumber("FuncDesc now: ", (uint64_t)FuncDesc, 16));
1529a0dd5b05SAlexander Shaposhnikov   }
1530a0dd5b05SAlexander Shaposhnikov   assert(FuncDesc == (void *)Ctx.Strings,
1531a0dd5b05SAlexander Shaposhnikov          "FuncDesc ptr must be equal to stringtable");
1532a0dd5b05SAlexander Shaposhnikov }
1533a0dd5b05SAlexander Shaposhnikov 
1534bbd9d610SAlexander Shaposhnikov // On OSX/iOS the final symbol name of an extern "C" function/variable contains
1535bbd9d610SAlexander Shaposhnikov // one extra leading underscore: _bolt_instr_setup -> __bolt_instr_setup.
15363b876cc3SAlexander Shaposhnikov extern "C"
15373b876cc3SAlexander Shaposhnikov __attribute__((section("__TEXT,__setup")))
15383b876cc3SAlexander Shaposhnikov __attribute__((force_align_arg_pointer))
15393b876cc3SAlexander Shaposhnikov void _bolt_instr_setup() {
1540a0dd5b05SAlexander Shaposhnikov   __asm__ __volatile__(SAVE_ALL :::);
15413b876cc3SAlexander Shaposhnikov 
1542a0dd5b05SAlexander Shaposhnikov   report("Hello!\n");
15433b876cc3SAlexander Shaposhnikov 
1544a0dd5b05SAlexander Shaposhnikov   __asm__ __volatile__(RESTORE_ALL :::);
15451cf23e5eSAlexander Shaposhnikov }
1546bbd9d610SAlexander Shaposhnikov 
15473b876cc3SAlexander Shaposhnikov extern "C"
15483b876cc3SAlexander Shaposhnikov __attribute__((section("__TEXT,__fini")))
15493b876cc3SAlexander Shaposhnikov __attribute__((force_align_arg_pointer))
15503b876cc3SAlexander Shaposhnikov void _bolt_instr_fini() {
1551a0dd5b05SAlexander Shaposhnikov   report("Bye!\n");
1552a0dd5b05SAlexander Shaposhnikov   __bolt_instr_data_dump();
1553e067f2adSAlexander Shaposhnikov }
1554e067f2adSAlexander Shaposhnikov 
1555bbd9d610SAlexander Shaposhnikov #endif
1556