xref: /llvm-project/bolt/runtime/instr.cpp (revision 3b876cc3e776712bee39a8337871109f9e206096)
162aa74f8SRafael Auler //===-- instr.cpp -----------------------------------------------*- C++ -*-===//
262aa74f8SRafael Auler //
362aa74f8SRafael Auler //                     The LLVM Compiler Infrastructure
462aa74f8SRafael Auler //
562aa74f8SRafael Auler // This file is distributed under the University of Illinois Open Source
662aa74f8SRafael Auler // License. See LICENSE.TXT for details.
762aa74f8SRafael Auler // This file contains code that is linked to the final binary with a function
862aa74f8SRafael Auler // that is called at program exit to dump instrumented data collected during
962aa74f8SRafael Auler // execution.
1062aa74f8SRafael Auler //
1162aa74f8SRafael Auler //===----------------------------------------------------------------------===//
1262aa74f8SRafael Auler //
1316a497c6SRafael Auler // BOLT runtime instrumentation library for x86 Linux. Currently, BOLT does
1416a497c6SRafael Auler // not support linking modules with dependencies on one another into the final
1516a497c6SRafael Auler // binary (TODO?), which means this library has to be self-contained in a single
1616a497c6SRafael Auler // module.
1716a497c6SRafael Auler //
1816a497c6SRafael Auler // All extern declarations here need to be defined by BOLT itself. Those will be
1916a497c6SRafael Auler // undefined symbols that BOLT needs to resolve by emitting these symbols with
2016a497c6SRafael Auler // MCStreamer. Currently, Passes/Instrumentation.cpp is the pass responsible
2116a497c6SRafael Auler // for defining the symbols here and these two files have a tight coupling: one
2216a497c6SRafael Auler // working statically when you run BOLT and another during program runtime when
2316a497c6SRafael Auler // you run an instrumented binary. The main goal here is to output an fdata file
2416a497c6SRafael Auler // (BOLT profile) with the instrumentation counters inserted by the static pass.
2516a497c6SRafael Auler // Counters for indirect calls are an exception, as we can't know them
2616a497c6SRafael Auler // statically. These counters are created and managed here. To allow this, we
2716a497c6SRafael Auler // need a minimal framework for allocating memory dynamically. We provide this
2816a497c6SRafael Auler // with the BumpPtrAllocator class (not LLVM's, but our own version of it).
2916a497c6SRafael Auler //
3016a497c6SRafael Auler // Since this code is intended to be inserted into any executable, we decided to
3116a497c6SRafael Auler // make it standalone and do not depend on any external libraries (i.e. language
3216a497c6SRafael Auler // support libraries, such as glibc or stdc++). To allow this, we provide a few
3316a497c6SRafael Auler // light implementations of common OS interacting functionalities using direct
3416a497c6SRafael Auler // syscall wrappers. Our simple allocator doesn't manage deallocations that
3516a497c6SRafael Auler // fragment the memory space, so it's stack based. This is the minimal framework
3616a497c6SRafael Auler // provided here to allow processing instrumented counters and writing fdata.
3716a497c6SRafael Auler //
3816a497c6SRafael Auler // In the C++ idiom used here, we never use or rely on constructors or
3916a497c6SRafael Auler // destructors for global objects. That's because those need support from the
4016a497c6SRafael Auler // linker in initialization/finalization code, and we want to keep our linker
4116a497c6SRafael Auler // very simple. Similarly, we don't create any global objects that are zero
4216a497c6SRafael Auler // initialized, since those would need to go .bss, which our simple linker also
4316a497c6SRafael Auler // don't support (TODO?).
4462aa74f8SRafael Auler //
4562aa74f8SRafael Auler //===----------------------------------------------------------------------===//
4662aa74f8SRafael Auler 
479bd71615SXun Li #include "common.h"
4862aa74f8SRafael Auler 
4916a497c6SRafael Auler // Enables a very verbose logging to stderr useful when debugging
50cc4b2fb6SRafael Auler //#define ENABLE_DEBUG
51cc4b2fb6SRafael Auler 
52cc4b2fb6SRafael Auler #ifdef ENABLE_DEBUG
53cc4b2fb6SRafael Auler #define DEBUG(X)                                                               \
54cc4b2fb6SRafael Auler   { X; }
55cc4b2fb6SRafael Auler #else
56cc4b2fb6SRafael Auler #define DEBUG(X)                                                               \
57cc4b2fb6SRafael Auler   {}
58cc4b2fb6SRafael Auler #endif
59cc4b2fb6SRafael Auler 
60*3b876cc3SAlexander Shaposhnikov 
61*3b876cc3SAlexander Shaposhnikov #if defined(__APPLE__)
62*3b876cc3SAlexander Shaposhnikov extern "C" {
63*3b876cc3SAlexander Shaposhnikov 
64*3b876cc3SAlexander Shaposhnikov extern uint64_t* _bolt_instr_locations_getter();
65*3b876cc3SAlexander Shaposhnikov extern uint32_t _bolt_num_counters_getter();
66*3b876cc3SAlexander Shaposhnikov 
67*3b876cc3SAlexander Shaposhnikov }
68*3b876cc3SAlexander Shaposhnikov 
69*3b876cc3SAlexander Shaposhnikov #else
70bbd9d610SAlexander Shaposhnikov 
7116a497c6SRafael Auler // Main counters inserted by instrumentation, incremented during runtime when
7216a497c6SRafael Auler // points of interest (locations) in the program are reached. Those are direct
7316a497c6SRafael Auler // calls and direct and indirect branches (local ones). There are also counters
7416a497c6SRafael Auler // for basic block execution if they are a spanning tree leaf and need to be
7516a497c6SRafael Auler // counted in order to infer the execution count of other edges of the CFG.
7662aa74f8SRafael Auler extern uint64_t __bolt_instr_locations[];
7716a497c6SRafael Auler extern uint32_t __bolt_num_counters;
7816a497c6SRafael Auler // Descriptions are serialized metadata about binary functions written by BOLT,
7916a497c6SRafael Auler // so we have a minimal understanding about the program structure. For a
8016a497c6SRafael Auler // reference on the exact format of this metadata, see *Description structs,
8116a497c6SRafael Auler // Location, IntrumentedNode and EntryNode.
8216a497c6SRafael Auler // Number of indirect call site descriptions
8316a497c6SRafael Auler extern uint32_t __bolt_instr_num_ind_calls;
8416a497c6SRafael Auler // Number of indirect call target descriptions
8516a497c6SRafael Auler extern uint32_t __bolt_instr_num_ind_targets;
86cc4b2fb6SRafael Auler // Number of function descriptions
87cc4b2fb6SRafael Auler extern uint32_t __bolt_instr_num_funcs;
8816a497c6SRafael Auler // Time to sleep across dumps (when we write the fdata profile to disk)
8916a497c6SRafael Auler extern uint32_t __bolt_instr_sleep_time;
90cc4b2fb6SRafael Auler // Filename to dump data to
9162aa74f8SRafael Auler extern char __bolt_instr_filename[];
9216a497c6SRafael Auler // If true, append current PID to the fdata filename when creating it so
9316a497c6SRafael Auler // different invocations of the same program can be differentiated.
9416a497c6SRafael Auler extern bool __bolt_instr_use_pid;
9516a497c6SRafael Auler // Functions that will be used to instrument indirect calls. BOLT static pass
9616a497c6SRafael Auler // will identify indirect calls and modify them to load the address in these
9716a497c6SRafael Auler // trampolines and call this address instead. BOLT can't use direct calls to
9816a497c6SRafael Auler // our handlers because our addresses here are not known at analysis time. We
9916a497c6SRafael Auler // only support resolving dependencies from this file to the output of BOLT,
10016a497c6SRafael Auler // *not* the other way around.
10116a497c6SRafael Auler // TODO: We need better linking support to make that happen.
10216a497c6SRafael Auler extern void (*__bolt_trampoline_ind_call)();
10316a497c6SRafael Auler extern void (*__bolt_trampoline_ind_tailcall)();
10416a497c6SRafael Auler // Function pointers to init/fini routines in the binary, so we can resume
10516a497c6SRafael Auler // regular execution of these functions that we hooked
10616a497c6SRafael Auler extern void (*__bolt_instr_init_ptr)();
10716a497c6SRafael Auler extern void (*__bolt_instr_fini_ptr)();
10862aa74f8SRafael Auler 
109cc4b2fb6SRafael Auler namespace {
110cc4b2fb6SRafael Auler 
111cc4b2fb6SRafael Auler /// A simple allocator that mmaps a fixed size region and manages this space
112cc4b2fb6SRafael Auler /// in a stack fashion, meaning you always deallocate the last element that
11316a497c6SRafael Auler /// was allocated. In practice, we don't need to deallocate individual elements.
11416a497c6SRafael Auler /// We monotonically increase our usage and then deallocate everything once we
11516a497c6SRafael Auler /// are done processing something.
116cc4b2fb6SRafael Auler class BumpPtrAllocator {
11716a497c6SRafael Auler   /// This is written before each allocation and act as a canary to detect when
11816a497c6SRafael Auler   /// a bug caused our program to cross allocation boundaries.
119cc4b2fb6SRafael Auler   struct EntryMetadata {
120cc4b2fb6SRafael Auler     uint64_t Magic;
121cc4b2fb6SRafael Auler     uint64_t AllocSize;
122cc4b2fb6SRafael Auler   };
1239bd71615SXun Li 
124cc4b2fb6SRafael Auler public:
125faaefff6SAlexander Shaposhnikov   void *allocate(size_t Size) {
12616a497c6SRafael Auler     Lock L(M);
127cc4b2fb6SRafael Auler     if (StackBase == nullptr) {
12816a497c6SRafael Auler       StackBase = reinterpret_cast<uint8_t *>(
12916a497c6SRafael Auler           __mmap(0, MaxSize, 0x3 /* PROT_READ | PROT_WRITE*/,
13016a497c6SRafael Auler                  Shared ? 0x21 /*MAP_SHARED | MAP_ANONYMOUS*/
13116a497c6SRafael Auler                         : 0x22 /* MAP_PRIVATE | MAP_ANONYMOUS*/,
13216a497c6SRafael Auler                  -1, 0));
133cc4b2fb6SRafael Auler       StackSize = 0;
134cc4b2fb6SRafael Auler     }
135cc4b2fb6SRafael Auler     Size = alignTo(Size + sizeof(EntryMetadata), 16);
136cc4b2fb6SRafael Auler     uint8_t *AllocAddress = StackBase + StackSize + sizeof(EntryMetadata);
137cc4b2fb6SRafael Auler     auto *M = reinterpret_cast<EntryMetadata *>(StackBase + StackSize);
13816a497c6SRafael Auler     M->Magic = Magic;
139cc4b2fb6SRafael Auler     M->AllocSize = Size;
140cc4b2fb6SRafael Auler     StackSize += Size;
14116a497c6SRafael Auler     assert(StackSize < MaxSize, "allocator ran out of memory");
142cc4b2fb6SRafael Auler     return AllocAddress;
143cc4b2fb6SRafael Auler   }
144cc4b2fb6SRafael Auler 
14516a497c6SRafael Auler #ifdef DEBUG
14616a497c6SRafael Auler   /// Element-wise deallocation is only used for debugging to catch memory
14716a497c6SRafael Auler   /// bugs by checking magic bytes. Ordinarily, we reset the allocator once
14816a497c6SRafael Auler   /// we are done with it. Reset is done with clear(). There's no need
14916a497c6SRafael Auler   /// to deallocate each element individually.
150cc4b2fb6SRafael Auler   void deallocate(void *Ptr) {
15116a497c6SRafael Auler     Lock L(M);
152cc4b2fb6SRafael Auler     uint8_t MetadataOffset = sizeof(EntryMetadata);
153cc4b2fb6SRafael Auler     auto *M = reinterpret_cast<EntryMetadata *>(
154cc4b2fb6SRafael Auler         reinterpret_cast<uint8_t *>(Ptr) - MetadataOffset);
155cc4b2fb6SRafael Auler     const uint8_t *StackTop = StackBase + StackSize + MetadataOffset;
156cc4b2fb6SRafael Auler     // Validate size
157cc4b2fb6SRafael Auler     if (Ptr != StackTop - M->AllocSize) {
15816a497c6SRafael Auler       // Failed validation, check if it is a pointer returned by operator new []
159cc4b2fb6SRafael Auler       MetadataOffset +=
160cc4b2fb6SRafael Auler           sizeof(uint64_t); // Space for number of elements alloc'ed
161cc4b2fb6SRafael Auler       M = reinterpret_cast<EntryMetadata *>(reinterpret_cast<uint8_t *>(Ptr) -
162cc4b2fb6SRafael Auler                                             MetadataOffset);
16316a497c6SRafael Auler       // Ok, it failed both checks if this assertion fails. Stop the program, we
16416a497c6SRafael Auler       // have a memory bug.
165cc4b2fb6SRafael Auler       assert(Ptr == StackTop - M->AllocSize,
166cc4b2fb6SRafael Auler              "must deallocate the last element alloc'ed");
167cc4b2fb6SRafael Auler     }
16816a497c6SRafael Auler     assert(M->Magic == Magic, "allocator magic is corrupt");
169cc4b2fb6SRafael Auler     StackSize -= M->AllocSize;
170cc4b2fb6SRafael Auler   }
17116a497c6SRafael Auler #else
17216a497c6SRafael Auler   void deallocate(void *) {}
17316a497c6SRafael Auler #endif
17416a497c6SRafael Auler 
17516a497c6SRafael Auler   void clear() {
17616a497c6SRafael Auler     Lock L(M);
17716a497c6SRafael Auler     StackSize = 0;
17816a497c6SRafael Auler   }
17916a497c6SRafael Auler 
18016a497c6SRafael Auler   /// Set mmap reservation size (only relevant before first allocation)
1819bd71615SXun Li   void setMaxSize(uint64_t Size) { MaxSize = Size; }
18216a497c6SRafael Auler 
18316a497c6SRafael Auler   /// Set mmap reservation privacy (only relevant before first allocation)
1849bd71615SXun Li   void setShared(bool S) { Shared = S; }
18516a497c6SRafael Auler 
18616a497c6SRafael Auler   void destroy() {
18716a497c6SRafael Auler     if (StackBase == nullptr)
18816a497c6SRafael Auler       return;
18916a497c6SRafael Auler     __munmap(StackBase, MaxSize);
19016a497c6SRafael Auler   }
191cc4b2fb6SRafael Auler 
192cc4b2fb6SRafael Auler private:
19316a497c6SRafael Auler   static constexpr uint64_t Magic = 0x1122334455667788ull;
19416a497c6SRafael Auler   uint64_t MaxSize = 0xa00000;
195cc4b2fb6SRafael Auler   uint8_t *StackBase{nullptr};
196cc4b2fb6SRafael Auler   uint64_t StackSize{0};
19716a497c6SRafael Auler   bool Shared{false};
19816a497c6SRafael Auler   Mutex M;
199cc4b2fb6SRafael Auler };
200cc4b2fb6SRafael Auler 
20116a497c6SRafael Auler /// Used for allocating indirect call instrumentation counters. Initialized by
20216a497c6SRafael Auler /// __bolt_instr_setup, our initialization routine.
20316a497c6SRafael Auler BumpPtrAllocator GlobalAlloc;
204cc4b2fb6SRafael Auler } // anonymous namespace
205cc4b2fb6SRafael Auler 
206cc4b2fb6SRafael Auler // User-defined placement new operators. We only use those (as opposed to
207cc4b2fb6SRafael Auler // overriding the regular operator new) so we can keep our allocator in the
208cc4b2fb6SRafael Auler // stack instead of in a data section (global).
209faaefff6SAlexander Shaposhnikov void *operator new(size_t Sz, BumpPtrAllocator &A) { return A.allocate(Sz); }
210faaefff6SAlexander Shaposhnikov void *operator new(size_t Sz, BumpPtrAllocator &A, char C) {
211cc4b2fb6SRafael Auler   auto *Ptr = reinterpret_cast<char *>(A.allocate(Sz));
212cc4b2fb6SRafael Auler   memSet(Ptr, C, Sz);
213cc4b2fb6SRafael Auler   return Ptr;
214cc4b2fb6SRafael Auler }
215faaefff6SAlexander Shaposhnikov void *operator new[](size_t Sz, BumpPtrAllocator &A) {
216cc4b2fb6SRafael Auler   return A.allocate(Sz);
217cc4b2fb6SRafael Auler }
218faaefff6SAlexander Shaposhnikov void *operator new[](size_t Sz, BumpPtrAllocator &A, char C) {
219cc4b2fb6SRafael Auler   auto *Ptr = reinterpret_cast<char *>(A.allocate(Sz));
220cc4b2fb6SRafael Auler   memSet(Ptr, C, Sz);
221cc4b2fb6SRafael Auler   return Ptr;
222cc4b2fb6SRafael Auler }
223cc4b2fb6SRafael Auler // Only called during exception unwinding (useless). We must manually dealloc.
224cc4b2fb6SRafael Auler // C++ language weirdness
2259bd71615SXun Li void operator delete(void *Ptr, BumpPtrAllocator &A) { A.deallocate(Ptr); }
226cc4b2fb6SRafael Auler 
227cc4b2fb6SRafael Auler namespace {
228cc4b2fb6SRafael Auler 
22916a497c6SRafael Auler /// Basic key-val atom stored in our hash
23016a497c6SRafael Auler struct SimpleHashTableEntryBase {
23116a497c6SRafael Auler   uint64_t Key;
23216a497c6SRafael Auler   uint64_t Val;
23316a497c6SRafael Auler };
23416a497c6SRafael Auler 
23516a497c6SRafael Auler /// This hash table implementation starts by allocating a table of size
23616a497c6SRafael Auler /// InitialSize. When conflicts happen in this main table, it resolves
23716a497c6SRafael Auler /// them by chaining a new table of size IncSize. It never reallocs as our
23816a497c6SRafael Auler /// allocator doesn't support it. The key is intended to be function pointers.
23916a497c6SRafael Auler /// There's no clever hash function (it's just x mod size, size being prime).
24016a497c6SRafael Auler /// I never tuned the coefficientes in the modular equation (TODO)
24116a497c6SRafael Auler /// This is used for indirect calls (each call site has one of this, so it
24216a497c6SRafael Auler /// should have a small footprint) and for tallying call counts globally for
24316a497c6SRafael Auler /// each target to check if we missed the origin of some calls (this one is a
24416a497c6SRafael Auler /// large instantiation of this template, since it is global for all call sites)
24516a497c6SRafael Auler template <typename T = SimpleHashTableEntryBase, uint32_t InitialSize = 7,
24616a497c6SRafael Auler           uint32_t IncSize = 7>
24716a497c6SRafael Auler class SimpleHashTable {
24816a497c6SRafael Auler public:
24916a497c6SRafael Auler   using MapEntry = T;
25016a497c6SRafael Auler 
25116a497c6SRafael Auler   /// Increment by 1 the value of \p Key. If it is not in this table, it will be
25216a497c6SRafael Auler   /// added to the table and its value set to 1.
25316a497c6SRafael Auler   void incrementVal(uint64_t Key, BumpPtrAllocator &Alloc) {
25416a497c6SRafael Auler     ++get(Key, Alloc).Val;
25516a497c6SRafael Auler   }
25616a497c6SRafael Auler 
25716a497c6SRafael Auler   /// Basic member accessing interface. Here we pass the allocator explicitly to
25816a497c6SRafael Auler   /// avoid storing a pointer to it as part of this table (remember there is one
25916a497c6SRafael Auler   /// hash for each indirect call site, so we wan't to minimize our footprint).
26016a497c6SRafael Auler   MapEntry &get(uint64_t Key, BumpPtrAllocator &Alloc) {
26116a497c6SRafael Auler     Lock L(M);
26216a497c6SRafael Auler     if (TableRoot)
26316a497c6SRafael Auler       return getEntry(TableRoot, Key, Key, Alloc, 0);
26416a497c6SRafael Auler     return firstAllocation(Key, Alloc);
26516a497c6SRafael Auler   }
26616a497c6SRafael Auler 
26716a497c6SRafael Auler   /// Traverses all elements in the table
26816a497c6SRafael Auler   template <typename... Args>
26916a497c6SRafael Auler   void forEachElement(void (*Callback)(MapEntry &, Args...), Args... args) {
27016a497c6SRafael Auler     if (!TableRoot)
27116a497c6SRafael Auler       return;
27216a497c6SRafael Auler     return forEachElement(Callback, InitialSize, TableRoot, args...);
27316a497c6SRafael Auler   }
27416a497c6SRafael Auler 
27516a497c6SRafael Auler   void resetCounters();
27616a497c6SRafael Auler 
27716a497c6SRafael Auler private:
27816a497c6SRafael Auler   constexpr static uint64_t VacantMarker = 0;
27916a497c6SRafael Auler   constexpr static uint64_t FollowUpTableMarker = 0x8000000000000000ull;
28016a497c6SRafael Auler 
28116a497c6SRafael Auler   MapEntry *TableRoot{nullptr};
28216a497c6SRafael Auler   Mutex M;
28316a497c6SRafael Auler 
28416a497c6SRafael Auler   template <typename... Args>
28516a497c6SRafael Auler   void forEachElement(void (*Callback)(MapEntry &, Args...),
28616a497c6SRafael Auler                       uint32_t NumEntries, MapEntry *Entries, Args... args) {
28716a497c6SRafael Auler     for (int I = 0; I < NumEntries; ++I) {
28816a497c6SRafael Auler       auto &Entry = Entries[I];
28916a497c6SRafael Auler       if (Entry.Key == VacantMarker)
29016a497c6SRafael Auler         continue;
29116a497c6SRafael Auler       if (Entry.Key & FollowUpTableMarker) {
29216a497c6SRafael Auler         forEachElement(Callback, IncSize,
29316a497c6SRafael Auler                        reinterpret_cast<MapEntry *>(Entry.Key &
29416a497c6SRafael Auler                                                     ~FollowUpTableMarker),
29516a497c6SRafael Auler                        args...);
29616a497c6SRafael Auler         continue;
29716a497c6SRafael Auler       }
29816a497c6SRafael Auler       Callback(Entry, args...);
29916a497c6SRafael Auler     }
30016a497c6SRafael Auler   }
30116a497c6SRafael Auler 
30216a497c6SRafael Auler   MapEntry &firstAllocation(uint64_t Key, BumpPtrAllocator &Alloc) {
30316a497c6SRafael Auler     TableRoot = new (Alloc, 0) MapEntry[InitialSize];
30416a497c6SRafael Auler     auto &Entry = TableRoot[Key % InitialSize];
30516a497c6SRafael Auler     Entry.Key = Key;
30616a497c6SRafael Auler     return Entry;
30716a497c6SRafael Auler   }
30816a497c6SRafael Auler 
30916a497c6SRafael Auler   MapEntry &getEntry(MapEntry *Entries, uint64_t Key, uint64_t Selector,
31016a497c6SRafael Auler                      BumpPtrAllocator &Alloc, int CurLevel) {
31116a497c6SRafael Auler     const uint32_t NumEntries = CurLevel == 0 ? InitialSize : IncSize;
31216a497c6SRafael Auler     uint64_t Remainder = Selector / NumEntries;
31316a497c6SRafael Auler     Selector = Selector % NumEntries;
31416a497c6SRafael Auler     auto &Entry = Entries[Selector];
31516a497c6SRafael Auler 
31616a497c6SRafael Auler     // A hit
31716a497c6SRafael Auler     if (Entry.Key == Key) {
31816a497c6SRafael Auler       return Entry;
31916a497c6SRafael Auler     }
32016a497c6SRafael Auler 
32116a497c6SRafael Auler     // Vacant - add new entry
32216a497c6SRafael Auler     if (Entry.Key == VacantMarker) {
32316a497c6SRafael Auler       Entry.Key = Key;
32416a497c6SRafael Auler       return Entry;
32516a497c6SRafael Auler     }
32616a497c6SRafael Auler 
32716a497c6SRafael Auler     // Defer to the next level
32816a497c6SRafael Auler     if (Entry.Key & FollowUpTableMarker) {
32916a497c6SRafael Auler       return getEntry(
33016a497c6SRafael Auler           reinterpret_cast<MapEntry *>(Entry.Key & ~FollowUpTableMarker),
33116a497c6SRafael Auler           Key, Remainder, Alloc, CurLevel + 1);
33216a497c6SRafael Auler     }
33316a497c6SRafael Auler 
33416a497c6SRafael Auler     // Conflict - create the next level
33516a497c6SRafael Auler     MapEntry *NextLevelTbl = new (Alloc, 0) MapEntry[IncSize];
33616a497c6SRafael Auler     uint64_t CurEntrySelector = Entry.Key / InitialSize;
33716a497c6SRafael Auler     for (int I = 0; I < CurLevel; ++I)
33816a497c6SRafael Auler       CurEntrySelector /= IncSize;
33916a497c6SRafael Auler     CurEntrySelector = CurEntrySelector % IncSize;
34016a497c6SRafael Auler     NextLevelTbl[CurEntrySelector] = Entry;
34116a497c6SRafael Auler     Entry.Key = reinterpret_cast<uint64_t>(NextLevelTbl) | FollowUpTableMarker;
34216a497c6SRafael Auler     return getEntry(NextLevelTbl, Key, Remainder, Alloc, CurLevel + 1);
34316a497c6SRafael Auler   }
34416a497c6SRafael Auler };
34516a497c6SRafael Auler 
34616a497c6SRafael Auler template <typename T> void resetIndCallCounter(T &Entry) {
34716a497c6SRafael Auler   Entry.Val = 0;
34816a497c6SRafael Auler }
34916a497c6SRafael Auler 
35016a497c6SRafael Auler template <typename T, uint32_t X, uint32_t Y>
35116a497c6SRafael Auler void SimpleHashTable<T, X, Y>::resetCounters() {
35216a497c6SRafael Auler   Lock L(M);
35316a497c6SRafael Auler   forEachElement(resetIndCallCounter);
35416a497c6SRafael Auler }
35516a497c6SRafael Auler 
35616a497c6SRafael Auler /// Represents a hash table mapping a function target address to its counter.
35716a497c6SRafael Auler using IndirectCallHashTable = SimpleHashTable<>;
35816a497c6SRafael Auler 
35916a497c6SRafael Auler /// Initialize with number 1 instead of 0 so we don't go into .bss. This is the
36016a497c6SRafael Auler /// global array of all hash tables storing indirect call destinations happening
36116a497c6SRafael Auler /// during runtime, one table per call site.
36216a497c6SRafael Auler IndirectCallHashTable *GlobalIndCallCounters{
36316a497c6SRafael Auler     reinterpret_cast<IndirectCallHashTable *>(1)};
36416a497c6SRafael Auler 
36516a497c6SRafael Auler /// Don't allow reentrancy in the fdata writing phase - only one thread writes
36616a497c6SRafael Auler /// it
36716a497c6SRafael Auler Mutex *GlobalWriteProfileMutex{reinterpret_cast<Mutex *>(1)};
36816a497c6SRafael Auler 
36916a497c6SRafael Auler /// Store number of calls in additional to target address (Key) and frequency
37016a497c6SRafael Auler /// as perceived by the basic block counter (Val).
37116a497c6SRafael Auler struct CallFlowEntryBase : public SimpleHashTableEntryBase {
37216a497c6SRafael Auler   uint64_t Calls;
37316a497c6SRafael Auler };
37416a497c6SRafael Auler 
37516a497c6SRafael Auler using CallFlowHashTableBase = SimpleHashTable<CallFlowEntryBase, 11939, 233>;
37616a497c6SRafael Auler 
37716a497c6SRafael Auler /// This is a large table indexing all possible call targets (indirect and
37816a497c6SRafael Auler /// direct ones). The goal is to find mismatches between number of calls (for
37916a497c6SRafael Auler /// those calls we were able to track) and the entry basic block counter of the
38016a497c6SRafael Auler /// callee. In most cases, these two should be equal. If not, there are two
38116a497c6SRafael Auler /// possible scenarios here:
38216a497c6SRafael Auler ///
38316a497c6SRafael Auler ///  * Entry BB has higher frequency than all known calls to this function.
38416a497c6SRafael Auler ///    In this case, we have dynamic library code or any uninstrumented code
38516a497c6SRafael Auler ///    calling this function. We will write the profile for these untracked
38616a497c6SRafael Auler ///    calls as having source "0 [unknown] 0" in the fdata file.
38716a497c6SRafael Auler ///
38816a497c6SRafael Auler ///  * Number of known calls is higher than the frequency of entry BB
38916a497c6SRafael Auler ///    This only happens when there is no counter for the entry BB / callee
39016a497c6SRafael Auler ///    function is not simple (in BOLT terms). We don't do anything special
39116a497c6SRafael Auler ///    here and just ignore those (we still report all calls to the non-simple
39216a497c6SRafael Auler ///    function, though).
39316a497c6SRafael Auler ///
39416a497c6SRafael Auler class CallFlowHashTable : public CallFlowHashTableBase {
39516a497c6SRafael Auler public:
39616a497c6SRafael Auler   CallFlowHashTable(BumpPtrAllocator &Alloc) : Alloc(Alloc) {}
39716a497c6SRafael Auler 
39816a497c6SRafael Auler   MapEntry &get(uint64_t Key) { return CallFlowHashTableBase::get(Key, Alloc); }
39916a497c6SRafael Auler 
40016a497c6SRafael Auler private:
40116a497c6SRafael Auler   // Different than the hash table for indirect call targets, we do store the
40216a497c6SRafael Auler   // allocator here since there is only one call flow hash and space overhead
40316a497c6SRafael Auler   // is negligible.
40416a497c6SRafael Auler   BumpPtrAllocator &Alloc;
40516a497c6SRafael Auler };
40616a497c6SRafael Auler 
40716a497c6SRafael Auler ///
40816a497c6SRafael Auler /// Description metadata emitted by BOLT to describe the program - refer to
40916a497c6SRafael Auler /// Passes/Instrumentation.cpp - Instrumentation::emitTablesAsELFNote()
41016a497c6SRafael Auler ///
41116a497c6SRafael Auler struct Location {
41216a497c6SRafael Auler   uint32_t FunctionName;
41316a497c6SRafael Auler   uint32_t Offset;
41416a497c6SRafael Auler };
41516a497c6SRafael Auler 
41616a497c6SRafael Auler struct CallDescription {
41716a497c6SRafael Auler   Location From;
41816a497c6SRafael Auler   uint32_t FromNode;
41916a497c6SRafael Auler   Location To;
42016a497c6SRafael Auler   uint32_t Counter;
42116a497c6SRafael Auler   uint64_t TargetAddress;
42216a497c6SRafael Auler };
42316a497c6SRafael Auler 
42416a497c6SRafael Auler using IndCallDescription = Location;
42516a497c6SRafael Auler 
42616a497c6SRafael Auler struct IndCallTargetDescription {
42716a497c6SRafael Auler   Location Loc;
42816a497c6SRafael Auler   uint64_t Address;
42916a497c6SRafael Auler };
43016a497c6SRafael Auler 
43116a497c6SRafael Auler struct EdgeDescription {
43216a497c6SRafael Auler   Location From;
43316a497c6SRafael Auler   uint32_t FromNode;
43416a497c6SRafael Auler   Location To;
43516a497c6SRafael Auler   uint32_t ToNode;
43616a497c6SRafael Auler   uint32_t Counter;
43716a497c6SRafael Auler };
43816a497c6SRafael Auler 
43916a497c6SRafael Auler struct InstrumentedNode {
44016a497c6SRafael Auler   uint32_t Node;
44116a497c6SRafael Auler   uint32_t Counter;
44216a497c6SRafael Auler };
44316a497c6SRafael Auler 
44416a497c6SRafael Auler struct EntryNode {
44516a497c6SRafael Auler   uint64_t Node;
44616a497c6SRafael Auler   uint64_t Address;
44716a497c6SRafael Auler };
44816a497c6SRafael Auler 
44916a497c6SRafael Auler struct FunctionDescription {
45016a497c6SRafael Auler   uint32_t NumLeafNodes;
45116a497c6SRafael Auler   const InstrumentedNode *LeafNodes;
45216a497c6SRafael Auler   uint32_t NumEdges;
45316a497c6SRafael Auler   const EdgeDescription *Edges;
45416a497c6SRafael Auler   uint32_t NumCalls;
45516a497c6SRafael Auler   const CallDescription *Calls;
45616a497c6SRafael Auler   uint32_t NumEntryNodes;
45716a497c6SRafael Auler   const EntryNode *EntryNodes;
45816a497c6SRafael Auler 
45916a497c6SRafael Auler   /// Constructor will parse the serialized function metadata written by BOLT
46016a497c6SRafael Auler   FunctionDescription(const uint8_t *FuncDesc);
46116a497c6SRafael Auler 
46216a497c6SRafael Auler   uint64_t getSize() const {
46316a497c6SRafael Auler     return 16 + NumLeafNodes * sizeof(InstrumentedNode) +
46416a497c6SRafael Auler            NumEdges * sizeof(EdgeDescription) +
46516a497c6SRafael Auler            NumCalls * sizeof(CallDescription) +
46616a497c6SRafael Auler            NumEntryNodes * sizeof(EntryNode);
46716a497c6SRafael Auler   }
46816a497c6SRafael Auler };
46916a497c6SRafael Auler 
47016a497c6SRafael Auler /// The context is created when the fdata profile needs to be written to disk
47116a497c6SRafael Auler /// and we need to interpret our runtime counters. It contains pointers to the
47216a497c6SRafael Auler /// mmaped binary (only the BOLT written metadata section). Deserialization
47316a497c6SRafael Auler /// should be straightforward as most data is POD or an array of POD elements.
47416a497c6SRafael Auler /// This metadata is used to reconstruct function CFGs.
47516a497c6SRafael Auler struct ProfileWriterContext {
47616a497c6SRafael Auler   IndCallDescription *IndCallDescriptions;
47716a497c6SRafael Auler   IndCallTargetDescription *IndCallTargets;
47816a497c6SRafael Auler   uint8_t *FuncDescriptions;
47916a497c6SRafael Auler   char *Strings;  // String table with function names used in this binary
48016a497c6SRafael Auler   int FileDesc;   // File descriptor for the file on disk backing this
48116a497c6SRafael Auler                   // information in memory via mmap
48216a497c6SRafael Auler   void *MMapPtr;  // The mmap ptr
48316a497c6SRafael Auler   int MMapSize;   // The mmap size
48416a497c6SRafael Auler 
48516a497c6SRafael Auler   /// Hash table storing all possible call destinations to detect untracked
48616a497c6SRafael Auler   /// calls and correctly report them as [unknown] in output fdata.
48716a497c6SRafael Auler   CallFlowHashTable *CallFlowTable;
48816a497c6SRafael Auler 
48916a497c6SRafael Auler   /// Lookup the sorted indirect call target vector to fetch function name and
49016a497c6SRafael Auler   /// offset for an arbitrary function pointer.
49116a497c6SRafael Auler   const IndCallTargetDescription *lookupIndCallTarget(uint64_t Target) const;
49216a497c6SRafael Auler };
49316a497c6SRafael Auler 
49416a497c6SRafael Auler /// Perform a string comparison and returns zero if Str1 matches Str2. Compares
49516a497c6SRafael Auler /// at most Size characters.
496cc4b2fb6SRafael Auler int compareStr(const char *Str1, const char *Str2, int Size) {
497821480d2SRafael Auler   while (*Str1 == *Str2) {
498821480d2SRafael Auler     if (*Str1 == '\0' || --Size == 0)
499821480d2SRafael Auler       return 0;
500821480d2SRafael Auler     ++Str1;
501821480d2SRafael Auler     ++Str2;
502821480d2SRafael Auler   }
503821480d2SRafael Auler   return 1;
504821480d2SRafael Auler }
505821480d2SRafael Auler 
50616a497c6SRafael Auler /// Output Location to the fdata file
50716a497c6SRafael Auler char *serializeLoc(const ProfileWriterContext &Ctx, char *OutBuf,
508cc4b2fb6SRafael Auler                    const Location Loc, uint32_t BufSize) {
509821480d2SRafael Auler   // fdata location format: Type Name Offset
510821480d2SRafael Auler   // Type 1 - regular symbol
511821480d2SRafael Auler   OutBuf = strCopy(OutBuf, "1 ");
51216a497c6SRafael Auler   const char *Str = Ctx.Strings + Loc.FunctionName;
513cc4b2fb6SRafael Auler   uint32_t Size = 25;
51462aa74f8SRafael Auler   while (*Str) {
51562aa74f8SRafael Auler     *OutBuf++ = *Str++;
516cc4b2fb6SRafael Auler     if (++Size >= BufSize)
517cc4b2fb6SRafael Auler       break;
51862aa74f8SRafael Auler   }
519cc4b2fb6SRafael Auler   assert(!*Str, "buffer overflow, function name too large");
52062aa74f8SRafael Auler   *OutBuf++ = ' ';
521821480d2SRafael Auler   OutBuf = intToStr(OutBuf, Loc.Offset, 16);
52262aa74f8SRafael Auler   *OutBuf++ = ' ';
52362aa74f8SRafael Auler   return OutBuf;
52462aa74f8SRafael Auler }
52562aa74f8SRafael Auler 
52616a497c6SRafael Auler /// Read and deserialize a function description written by BOLT. \p FuncDesc
52716a497c6SRafael Auler /// points at the beginning of the function metadata structure in the file.
52816a497c6SRafael Auler /// See Instrumentation::emitTablesAsELFNote()
52916a497c6SRafael Auler FunctionDescription::FunctionDescription(const uint8_t *FuncDesc) {
53016a497c6SRafael Auler   NumLeafNodes = *reinterpret_cast<const uint32_t *>(FuncDesc);
53116a497c6SRafael Auler   DEBUG(reportNumber("NumLeafNodes = ", NumLeafNodes, 10));
53216a497c6SRafael Auler   LeafNodes = reinterpret_cast<const InstrumentedNode *>(FuncDesc + 4);
53316a497c6SRafael Auler 
53416a497c6SRafael Auler   NumEdges = *reinterpret_cast<const uint32_t *>(
53516a497c6SRafael Auler       FuncDesc + 4 + NumLeafNodes * sizeof(InstrumentedNode));
53616a497c6SRafael Auler   DEBUG(reportNumber("NumEdges = ", NumEdges, 10));
53716a497c6SRafael Auler   Edges = reinterpret_cast<const EdgeDescription *>(
53816a497c6SRafael Auler       FuncDesc + 8 + NumLeafNodes * sizeof(InstrumentedNode));
53916a497c6SRafael Auler 
54016a497c6SRafael Auler   NumCalls = *reinterpret_cast<const uint32_t *>(
54116a497c6SRafael Auler       FuncDesc + 8 + NumLeafNodes * sizeof(InstrumentedNode) +
54216a497c6SRafael Auler       NumEdges * sizeof(EdgeDescription));
54316a497c6SRafael Auler   DEBUG(reportNumber("NumCalls = ", NumCalls, 10));
54416a497c6SRafael Auler   Calls = reinterpret_cast<const CallDescription *>(
54516a497c6SRafael Auler       FuncDesc + 12 + NumLeafNodes * sizeof(InstrumentedNode) +
54616a497c6SRafael Auler       NumEdges * sizeof(EdgeDescription));
54716a497c6SRafael Auler   NumEntryNodes = *reinterpret_cast<const uint32_t *>(
54816a497c6SRafael Auler       FuncDesc + 12 + NumLeafNodes * sizeof(InstrumentedNode) +
54916a497c6SRafael Auler       NumEdges * sizeof(EdgeDescription) + NumCalls * sizeof(CallDescription));
55016a497c6SRafael Auler   DEBUG(reportNumber("NumEntryNodes = ", NumEntryNodes, 10));
55116a497c6SRafael Auler   EntryNodes = reinterpret_cast<const EntryNode *>(
55216a497c6SRafael Auler       FuncDesc + 16 + NumLeafNodes * sizeof(InstrumentedNode) +
55316a497c6SRafael Auler       NumEdges * sizeof(EdgeDescription) + NumCalls * sizeof(CallDescription));
55416a497c6SRafael Auler }
55516a497c6SRafael Auler 
55616a497c6SRafael Auler /// Read and mmap descriptions written by BOLT from the executable's notes
55716a497c6SRafael Auler /// section
558ba31344fSRafael Auler #ifdef HAVE_ELF_H
55916a497c6SRafael Auler ProfileWriterContext readDescriptions() {
56016a497c6SRafael Auler   ProfileWriterContext Result;
561821480d2SRafael Auler   uint64_t FD = __open("/proc/self/exe",
562821480d2SRafael Auler                        /*flags=*/0 /*O_RDONLY*/,
563821480d2SRafael Auler                        /*mode=*/0666);
564cc4b2fb6SRafael Auler   assert(static_cast<int64_t>(FD) > 0, "Failed to open /proc/self/exe");
565821480d2SRafael Auler   Result.FileDesc = FD;
566821480d2SRafael Auler 
567821480d2SRafael Auler   // mmap our binary to memory
568821480d2SRafael Auler   uint64_t Size = __lseek(FD, 0, 2 /*SEEK_END*/);
569821480d2SRafael Auler   uint8_t *BinContents = reinterpret_cast<uint8_t *>(
570821480d2SRafael Auler       __mmap(0, Size, 0x1 /* PROT_READ*/, 0x2 /* MAP_PRIVATE*/, FD, 0));
571821480d2SRafael Auler   Result.MMapPtr = BinContents;
572821480d2SRafael Auler   Result.MMapSize = Size;
573821480d2SRafael Auler   Elf64_Ehdr *Hdr = reinterpret_cast<Elf64_Ehdr *>(BinContents);
574821480d2SRafael Auler   Elf64_Shdr *Shdr = reinterpret_cast<Elf64_Shdr *>(BinContents + Hdr->e_shoff);
575821480d2SRafael Auler   Elf64_Shdr *StringTblHeader = reinterpret_cast<Elf64_Shdr *>(
576821480d2SRafael Auler       BinContents + Hdr->e_shoff + Hdr->e_shstrndx * Hdr->e_shentsize);
577821480d2SRafael Auler 
578821480d2SRafael Auler   // Find .bolt.instr.tables with the data we need and set pointers to it
579821480d2SRafael Auler   for (int I = 0; I < Hdr->e_shnum; ++I) {
580821480d2SRafael Auler     char *SecName = reinterpret_cast<char *>(
581821480d2SRafael Auler         BinContents + StringTblHeader->sh_offset + Shdr->sh_name);
582821480d2SRafael Auler     if (compareStr(SecName, ".bolt.instr.tables", 64) != 0) {
583821480d2SRafael Auler       Shdr = reinterpret_cast<Elf64_Shdr *>(BinContents + Hdr->e_shoff +
584821480d2SRafael Auler                                             (I + 1) * Hdr->e_shentsize);
585821480d2SRafael Auler       continue;
586821480d2SRafael Auler     }
587821480d2SRafael Auler     // Actual contents of the ELF note start after offset 20 decimal:
588821480d2SRafael Auler     // Offset 0: Producer name size (4 bytes)
589821480d2SRafael Auler     // Offset 4: Contents size (4 bytes)
590821480d2SRafael Auler     // Offset 8: Note type (4 bytes)
591821480d2SRafael Auler     // Offset 12: Producer name (BOLT\0) (5 bytes + align to 4-byte boundary)
592821480d2SRafael Auler     // Offset 20: Contents
59316a497c6SRafael Auler     uint32_t IndCallDescSize =
594cc4b2fb6SRafael Auler         *reinterpret_cast<uint32_t *>(BinContents + Shdr->sh_offset + 20);
59516a497c6SRafael Auler     uint32_t IndCallTargetDescSize = *reinterpret_cast<uint32_t *>(
59616a497c6SRafael Auler         BinContents + Shdr->sh_offset + 24 + IndCallDescSize);
59716a497c6SRafael Auler     uint32_t FuncDescSize =
59816a497c6SRafael Auler         *reinterpret_cast<uint32_t *>(BinContents + Shdr->sh_offset + 28 +
59916a497c6SRafael Auler                                       IndCallDescSize + IndCallTargetDescSize);
60016a497c6SRafael Auler     Result.IndCallDescriptions = reinterpret_cast<IndCallDescription *>(
60116a497c6SRafael Auler         BinContents + Shdr->sh_offset + 24);
60216a497c6SRafael Auler     Result.IndCallTargets = reinterpret_cast<IndCallTargetDescription *>(
60316a497c6SRafael Auler         BinContents + Shdr->sh_offset + 28 + IndCallDescSize);
60416a497c6SRafael Auler     Result.FuncDescriptions = BinContents + Shdr->sh_offset + 32 +
60516a497c6SRafael Auler                               IndCallDescSize + IndCallTargetDescSize;
60616a497c6SRafael Auler     Result.Strings = reinterpret_cast<char *>(
60716a497c6SRafael Auler         BinContents + Shdr->sh_offset + 32 + IndCallDescSize +
60816a497c6SRafael Auler         IndCallTargetDescSize + FuncDescSize);
609821480d2SRafael Auler     return Result;
610821480d2SRafael Auler   }
611821480d2SRafael Auler   const char ErrMsg[] =
612821480d2SRafael Auler       "BOLT instrumentation runtime error: could not find section "
613821480d2SRafael Auler       ".bolt.instr.tables\n";
614821480d2SRafael Auler   reportError(ErrMsg, sizeof(ErrMsg));
615821480d2SRafael Auler   return Result;
616821480d2SRafael Auler }
617ba31344fSRafael Auler #else
61816a497c6SRafael Auler ProfileWriterContext readDescriptions() {
61916a497c6SRafael Auler   ProfileWriterContext Result;
620ba31344fSRafael Auler   const char ErrMsg[] =
621ba31344fSRafael Auler     "BOLT instrumentation runtime error: unsupported binary format.\n";
622ba31344fSRafael Auler   reportError(ErrMsg, sizeof(ErrMsg));
623ba31344fSRafael Auler   return Result;
624ba31344fSRafael Auler }
625ba31344fSRafael Auler #endif
626821480d2SRafael Auler 
62716a497c6SRafael Auler /// Debug by printing overall metadata global numbers to check it is sane
62816a497c6SRafael Auler void printStats(const ProfileWriterContext &Ctx) {
629cc4b2fb6SRafael Auler   char StatMsg[BufSize];
630cc4b2fb6SRafael Auler   char *StatPtr = StatMsg;
63116a497c6SRafael Auler   StatPtr =
63216a497c6SRafael Auler       strCopy(StatPtr,
63316a497c6SRafael Auler               "\nBOLT INSTRUMENTATION RUNTIME STATISTICS\n\nIndCallDescSize: ");
634cc4b2fb6SRafael Auler   StatPtr = intToStr(StatPtr,
63516a497c6SRafael Auler                      Ctx.FuncDescriptions -
63616a497c6SRafael Auler                          reinterpret_cast<uint8_t *>(Ctx.IndCallDescriptions),
637cc4b2fb6SRafael Auler                      10);
638cc4b2fb6SRafael Auler   StatPtr = strCopy(StatPtr, "\nFuncDescSize: ");
639cc4b2fb6SRafael Auler   StatPtr = intToStr(
640cc4b2fb6SRafael Auler       StatPtr,
64116a497c6SRafael Auler       reinterpret_cast<uint8_t *>(Ctx.Strings) - Ctx.FuncDescriptions, 10);
64216a497c6SRafael Auler   StatPtr = strCopy(StatPtr, "\n__bolt_instr_num_ind_calls: ");
64316a497c6SRafael Auler   StatPtr = intToStr(StatPtr, __bolt_instr_num_ind_calls, 10);
644cc4b2fb6SRafael Auler   StatPtr = strCopy(StatPtr, "\n__bolt_instr_num_funcs: ");
645cc4b2fb6SRafael Auler   StatPtr = intToStr(StatPtr, __bolt_instr_num_funcs, 10);
646cc4b2fb6SRafael Auler   StatPtr = strCopy(StatPtr, "\n");
647cc4b2fb6SRafael Auler   __write(2, StatMsg, StatPtr - StatMsg);
648cc4b2fb6SRafael Auler }
649cc4b2fb6SRafael Auler 
650cc4b2fb6SRafael Auler /// This is part of a simple CFG representation in memory, where we store
651cc4b2fb6SRafael Auler /// a dynamically sized array of input and output edges per node, and store
652cc4b2fb6SRafael Auler /// a dynamically sized array of nodes per graph. We also store the spanning
653cc4b2fb6SRafael Auler /// tree edges for that CFG in a separate array of nodes in
654cc4b2fb6SRafael Auler /// \p SpanningTreeNodes, while the regular nodes live in \p CFGNodes.
655cc4b2fb6SRafael Auler struct Edge {
656cc4b2fb6SRafael Auler   uint32_t Node; // Index in nodes array regarding the destination of this edge
657cc4b2fb6SRafael Auler   uint32_t ID;   // Edge index in an array comprising all edges of the graph
658cc4b2fb6SRafael Auler };
659cc4b2fb6SRafael Auler 
660cc4b2fb6SRafael Auler /// A regular graph node or a spanning tree node
661cc4b2fb6SRafael Auler struct Node {
662cc4b2fb6SRafael Auler   uint32_t NumInEdges{0};  // Input edge count used to size InEdge
663cc4b2fb6SRafael Auler   uint32_t NumOutEdges{0}; // Output edge count used to size OutEdges
664cc4b2fb6SRafael Auler   Edge *InEdges{nullptr};  // Created and managed by \p Graph
665cc4b2fb6SRafael Auler   Edge *OutEdges{nullptr}; // ditto
666cc4b2fb6SRafael Auler };
667cc4b2fb6SRafael Auler 
668cc4b2fb6SRafael Auler /// Main class for CFG representation in memory. Manages object creation and
669cc4b2fb6SRafael Auler /// destruction, populates an array of CFG nodes as well as corresponding
670cc4b2fb6SRafael Auler /// spanning tree nodes.
671cc4b2fb6SRafael Auler struct Graph {
672cc4b2fb6SRafael Auler   uint32_t NumNodes;
673cc4b2fb6SRafael Auler   Node *CFGNodes;
674cc4b2fb6SRafael Auler   Node *SpanningTreeNodes;
67516a497c6SRafael Auler   uint64_t *EdgeFreqs;
67616a497c6SRafael Auler   uint64_t *CallFreqs;
677cc4b2fb6SRafael Auler   BumpPtrAllocator &Alloc;
67816a497c6SRafael Auler   const FunctionDescription &D;
679cc4b2fb6SRafael Auler 
68016a497c6SRafael Auler   /// Reads a list of edges from function description \p D and builds
681cc4b2fb6SRafael Auler   /// the graph from it. Allocates several internal dynamic structures that are
68216a497c6SRafael Auler   /// later destroyed by ~Graph() and uses \p Alloc. D.LeafNodes contain all
683cc4b2fb6SRafael Auler   /// spanning tree leaf nodes descriptions (their counters). They are the seed
684cc4b2fb6SRafael Auler   /// used to compute the rest of the missing edge counts in a bottom-up
685cc4b2fb6SRafael Auler   /// traversal of the spanning tree.
68616a497c6SRafael Auler   Graph(BumpPtrAllocator &Alloc, const FunctionDescription &D,
68716a497c6SRafael Auler         const uint64_t *Counters, ProfileWriterContext &Ctx);
688cc4b2fb6SRafael Auler   ~Graph();
689cc4b2fb6SRafael Auler   void dump() const;
69016a497c6SRafael Auler 
69116a497c6SRafael Auler private:
69216a497c6SRafael Auler   void computeEdgeFrequencies(const uint64_t *Counters,
69316a497c6SRafael Auler                               ProfileWriterContext &Ctx);
69416a497c6SRafael Auler   void dumpEdgeFreqs() const;
695cc4b2fb6SRafael Auler };
696cc4b2fb6SRafael Auler 
69716a497c6SRafael Auler Graph::Graph(BumpPtrAllocator &Alloc, const FunctionDescription &D,
69816a497c6SRafael Auler              const uint64_t *Counters, ProfileWriterContext &Ctx)
69916a497c6SRafael Auler     : Alloc(Alloc), D(D) {
700cc4b2fb6SRafael Auler   DEBUG(reportNumber("G = 0x", (uint64_t)this, 16));
701cc4b2fb6SRafael Auler   // First pass to determine number of nodes
70216a497c6SRafael Auler   int32_t MaxNodes = -1;
70316a497c6SRafael Auler   CallFreqs = nullptr;
70416a497c6SRafael Auler   EdgeFreqs = nullptr;
70516a497c6SRafael Auler   for (int I = 0; I < D.NumEdges; ++I) {
70616a497c6SRafael Auler     if (static_cast<int32_t>(D.Edges[I].FromNode) > MaxNodes)
70716a497c6SRafael Auler       MaxNodes = D.Edges[I].FromNode;
70816a497c6SRafael Auler     if (static_cast<int32_t>(D.Edges[I].ToNode) > MaxNodes)
70916a497c6SRafael Auler       MaxNodes = D.Edges[I].ToNode;
710cc4b2fb6SRafael Auler   }
71116a497c6SRafael Auler   for (int I = 0; I < D.NumLeafNodes; ++I) {
71216a497c6SRafael Auler     if (static_cast<int32_t>(D.LeafNodes[I].Node) > MaxNodes)
71316a497c6SRafael Auler       MaxNodes = D.LeafNodes[I].Node;
714cc4b2fb6SRafael Auler   }
71516a497c6SRafael Auler   for (int I = 0; I < D.NumCalls; ++I) {
71616a497c6SRafael Auler     if (static_cast<int32_t>(D.Calls[I].FromNode) > MaxNodes)
71716a497c6SRafael Auler       MaxNodes = D.Calls[I].FromNode;
71816a497c6SRafael Auler   }
71916a497c6SRafael Auler   // No nodes? Nothing to do
72016a497c6SRafael Auler   if (MaxNodes < 0) {
72116a497c6SRafael Auler     DEBUG(report("No nodes!\n"));
722cc4b2fb6SRafael Auler     CFGNodes = nullptr;
723cc4b2fb6SRafael Auler     SpanningTreeNodes = nullptr;
724cc4b2fb6SRafael Auler     NumNodes = 0;
725cc4b2fb6SRafael Auler     return;
726cc4b2fb6SRafael Auler   }
727cc4b2fb6SRafael Auler   ++MaxNodes;
728cc4b2fb6SRafael Auler   DEBUG(reportNumber("NumNodes = ", MaxNodes, 10));
72916a497c6SRafael Auler   NumNodes = static_cast<uint32_t>(MaxNodes);
730cc4b2fb6SRafael Auler 
731cc4b2fb6SRafael Auler   // Initial allocations
732cc4b2fb6SRafael Auler   CFGNodes = new (Alloc) Node[MaxNodes];
733cc4b2fb6SRafael Auler   DEBUG(reportNumber("G->CFGNodes = 0x", (uint64_t)CFGNodes, 16));
734cc4b2fb6SRafael Auler   SpanningTreeNodes = new (Alloc) Node[MaxNodes];
735cc4b2fb6SRafael Auler   DEBUG(reportNumber("G->SpanningTreeNodes = 0x",
736cc4b2fb6SRafael Auler                      (uint64_t)SpanningTreeNodes, 16));
737cc4b2fb6SRafael Auler 
738cc4b2fb6SRafael Auler   // Figure out how much to allocate to each vector (in/out edge sets)
73916a497c6SRafael Auler   for (int I = 0; I < D.NumEdges; ++I) {
74016a497c6SRafael Auler     CFGNodes[D.Edges[I].FromNode].NumOutEdges++;
74116a497c6SRafael Auler     CFGNodes[D.Edges[I].ToNode].NumInEdges++;
74216a497c6SRafael Auler     if (D.Edges[I].Counter != 0xffffffff)
743cc4b2fb6SRafael Auler       continue;
744cc4b2fb6SRafael Auler 
74516a497c6SRafael Auler     SpanningTreeNodes[D.Edges[I].FromNode].NumOutEdges++;
74616a497c6SRafael Auler     SpanningTreeNodes[D.Edges[I].ToNode].NumInEdges++;
747cc4b2fb6SRafael Auler   }
748cc4b2fb6SRafael Auler 
749cc4b2fb6SRafael Auler   // Allocate in/out edge sets
750cc4b2fb6SRafael Auler   for (int I = 0; I < MaxNodes; ++I) {
751cc4b2fb6SRafael Auler     if (CFGNodes[I].NumInEdges > 0)
752cc4b2fb6SRafael Auler       CFGNodes[I].InEdges = new (Alloc) Edge[CFGNodes[I].NumInEdges];
753cc4b2fb6SRafael Auler     if (CFGNodes[I].NumOutEdges > 0)
754cc4b2fb6SRafael Auler       CFGNodes[I].OutEdges = new (Alloc) Edge[CFGNodes[I].NumOutEdges];
755cc4b2fb6SRafael Auler     if (SpanningTreeNodes[I].NumInEdges > 0)
756cc4b2fb6SRafael Auler       SpanningTreeNodes[I].InEdges =
757cc4b2fb6SRafael Auler           new (Alloc) Edge[SpanningTreeNodes[I].NumInEdges];
758cc4b2fb6SRafael Auler     if (SpanningTreeNodes[I].NumOutEdges > 0)
759cc4b2fb6SRafael Auler       SpanningTreeNodes[I].OutEdges =
760cc4b2fb6SRafael Auler           new (Alloc) Edge[SpanningTreeNodes[I].NumOutEdges];
761cc4b2fb6SRafael Auler     CFGNodes[I].NumInEdges = 0;
762cc4b2fb6SRafael Auler     CFGNodes[I].NumOutEdges = 0;
763cc4b2fb6SRafael Auler     SpanningTreeNodes[I].NumInEdges = 0;
764cc4b2fb6SRafael Auler     SpanningTreeNodes[I].NumOutEdges = 0;
765cc4b2fb6SRafael Auler   }
766cc4b2fb6SRafael Auler 
767cc4b2fb6SRafael Auler   // Fill in/out edge sets
76816a497c6SRafael Auler   for (int I = 0; I < D.NumEdges; ++I) {
76916a497c6SRafael Auler     const uint32_t Src = D.Edges[I].FromNode;
77016a497c6SRafael Auler     const uint32_t Dst = D.Edges[I].ToNode;
771cc4b2fb6SRafael Auler     Edge *E = &CFGNodes[Src].OutEdges[CFGNodes[Src].NumOutEdges++];
772cc4b2fb6SRafael Auler     E->Node = Dst;
773cc4b2fb6SRafael Auler     E->ID = I;
774cc4b2fb6SRafael Auler 
775cc4b2fb6SRafael Auler     E = &CFGNodes[Dst].InEdges[CFGNodes[Dst].NumInEdges++];
776cc4b2fb6SRafael Auler     E->Node = Src;
777cc4b2fb6SRafael Auler     E->ID = I;
778cc4b2fb6SRafael Auler 
77916a497c6SRafael Auler     if (D.Edges[I].Counter != 0xffffffff)
780cc4b2fb6SRafael Auler       continue;
781cc4b2fb6SRafael Auler 
782cc4b2fb6SRafael Auler     E = &SpanningTreeNodes[Src]
783cc4b2fb6SRafael Auler              .OutEdges[SpanningTreeNodes[Src].NumOutEdges++];
784cc4b2fb6SRafael Auler     E->Node = Dst;
785cc4b2fb6SRafael Auler     E->ID = I;
786cc4b2fb6SRafael Auler 
787cc4b2fb6SRafael Auler     E = &SpanningTreeNodes[Dst]
788cc4b2fb6SRafael Auler              .InEdges[SpanningTreeNodes[Dst].NumInEdges++];
789cc4b2fb6SRafael Auler     E->Node = Src;
790cc4b2fb6SRafael Auler     E->ID = I;
791cc4b2fb6SRafael Auler   }
79216a497c6SRafael Auler 
79316a497c6SRafael Auler   computeEdgeFrequencies(Counters, Ctx);
794cc4b2fb6SRafael Auler }
795cc4b2fb6SRafael Auler 
796cc4b2fb6SRafael Auler Graph::~Graph() {
79716a497c6SRafael Auler   if (CallFreqs)
79816a497c6SRafael Auler     Alloc.deallocate(CallFreqs);
79916a497c6SRafael Auler   if (EdgeFreqs)
80016a497c6SRafael Auler     Alloc.deallocate(EdgeFreqs);
801cc4b2fb6SRafael Auler   for (int I = NumNodes - 1; I >= 0; --I) {
802cc4b2fb6SRafael Auler     if (SpanningTreeNodes[I].OutEdges)
803cc4b2fb6SRafael Auler       Alloc.deallocate(SpanningTreeNodes[I].OutEdges);
804cc4b2fb6SRafael Auler     if (SpanningTreeNodes[I].InEdges)
805cc4b2fb6SRafael Auler       Alloc.deallocate(SpanningTreeNodes[I].InEdges);
806cc4b2fb6SRafael Auler     if (CFGNodes[I].OutEdges)
807cc4b2fb6SRafael Auler       Alloc.deallocate(CFGNodes[I].OutEdges);
808cc4b2fb6SRafael Auler     if (CFGNodes[I].InEdges)
809cc4b2fb6SRafael Auler       Alloc.deallocate(CFGNodes[I].InEdges);
810cc4b2fb6SRafael Auler   }
811cc4b2fb6SRafael Auler   if (SpanningTreeNodes)
812cc4b2fb6SRafael Auler     Alloc.deallocate(SpanningTreeNodes);
813cc4b2fb6SRafael Auler   if (CFGNodes)
814cc4b2fb6SRafael Auler     Alloc.deallocate(CFGNodes);
815cc4b2fb6SRafael Auler }
816cc4b2fb6SRafael Auler 
817cc4b2fb6SRafael Auler void Graph::dump() const {
818cc4b2fb6SRafael Auler   reportNumber("Dumping graph with number of nodes: ", NumNodes, 10);
819cc4b2fb6SRafael Auler   report("  Full graph:\n");
820cc4b2fb6SRafael Auler   for (int I = 0; I < NumNodes; ++I) {
821cc4b2fb6SRafael Auler     const Node *N = &CFGNodes[I];
822cc4b2fb6SRafael Auler     reportNumber("    Node #", I, 10);
823cc4b2fb6SRafael Auler     reportNumber("      InEdges total ", N->NumInEdges, 10);
824cc4b2fb6SRafael Auler     for (int J = 0; J < N->NumInEdges; ++J)
825cc4b2fb6SRafael Auler       reportNumber("        ", N->InEdges[J].Node, 10);
826cc4b2fb6SRafael Auler     reportNumber("      OutEdges total ", N->NumOutEdges, 10);
827cc4b2fb6SRafael Auler     for (int J = 0; J < N->NumOutEdges; ++J)
828cc4b2fb6SRafael Auler       reportNumber("        ", N->OutEdges[J].Node, 10);
829cc4b2fb6SRafael Auler     report("\n");
830cc4b2fb6SRafael Auler   }
831cc4b2fb6SRafael Auler   report("  Spanning tree:\n");
832cc4b2fb6SRafael Auler   for (int I = 0; I < NumNodes; ++I) {
833cc4b2fb6SRafael Auler     const Node *N = &SpanningTreeNodes[I];
834cc4b2fb6SRafael Auler     reportNumber("    Node #", I, 10);
835cc4b2fb6SRafael Auler     reportNumber("      InEdges total ", N->NumInEdges, 10);
836cc4b2fb6SRafael Auler     for (int J = 0; J < N->NumInEdges; ++J)
837cc4b2fb6SRafael Auler       reportNumber("        ", N->InEdges[J].Node, 10);
838cc4b2fb6SRafael Auler     reportNumber("      OutEdges total ", N->NumOutEdges, 10);
839cc4b2fb6SRafael Auler     for (int J = 0; J < N->NumOutEdges; ++J)
840cc4b2fb6SRafael Auler       reportNumber("        ", N->OutEdges[J].Node, 10);
841cc4b2fb6SRafael Auler     report("\n");
842cc4b2fb6SRafael Auler   }
843cc4b2fb6SRafael Auler }
844cc4b2fb6SRafael Auler 
84516a497c6SRafael Auler void Graph::dumpEdgeFreqs() const {
84616a497c6SRafael Auler   reportNumber(
84716a497c6SRafael Auler       "Dumping edge frequencies for graph with num edges: ", D.NumEdges, 10);
84816a497c6SRafael Auler   for (int I = 0; I < D.NumEdges; ++I) {
84916a497c6SRafael Auler     reportNumber("* Src: ", D.Edges[I].FromNode, 10);
85016a497c6SRafael Auler     reportNumber("  Dst: ", D.Edges[I].ToNode, 10);
851cc4b2fb6SRafael Auler     reportNumber("    Cnt: ", EdgeFreqs[I], 10);
852cc4b2fb6SRafael Auler   }
853cc4b2fb6SRafael Auler }
854cc4b2fb6SRafael Auler 
85516a497c6SRafael Auler /// Auxiliary map structure for fast lookups of which calls map to each node of
85616a497c6SRafael Auler /// the function CFG
85716a497c6SRafael Auler struct NodeToCallsMap {
85816a497c6SRafael Auler   struct MapEntry {
85916a497c6SRafael Auler     uint32_t NumCalls;
86016a497c6SRafael Auler     uint32_t *Calls;
86116a497c6SRafael Auler   };
86216a497c6SRafael Auler   MapEntry *Entries;
86316a497c6SRafael Auler   BumpPtrAllocator &Alloc;
86416a497c6SRafael Auler   const uint32_t NumNodes;
865cc4b2fb6SRafael Auler 
86616a497c6SRafael Auler   NodeToCallsMap(BumpPtrAllocator &Alloc, const FunctionDescription &D,
86716a497c6SRafael Auler                  uint32_t NumNodes)
86816a497c6SRafael Auler       : Alloc(Alloc), NumNodes(NumNodes) {
86916a497c6SRafael Auler     Entries = new (Alloc, 0) MapEntry[NumNodes];
87016a497c6SRafael Auler     for (int I = 0; I < D.NumCalls; ++I) {
87116a497c6SRafael Auler       DEBUG(reportNumber("Registering call in node ", D.Calls[I].FromNode, 10));
87216a497c6SRafael Auler       ++Entries[D.Calls[I].FromNode].NumCalls;
87316a497c6SRafael Auler     }
87416a497c6SRafael Auler     for (int I = 0; I < NumNodes; ++I) {
87516a497c6SRafael Auler       Entries[I].Calls = Entries[I].NumCalls ? new (Alloc)
87616a497c6SRafael Auler                                                    uint32_t[Entries[I].NumCalls]
87716a497c6SRafael Auler                                              : nullptr;
87816a497c6SRafael Auler       Entries[I].NumCalls = 0;
87916a497c6SRafael Auler     }
88016a497c6SRafael Auler     for (int I = 0; I < D.NumCalls; ++I) {
88116a497c6SRafael Auler       auto &Entry = Entries[D.Calls[I].FromNode];
88216a497c6SRafael Auler       Entry.Calls[Entry.NumCalls++] = I;
88316a497c6SRafael Auler     }
88416a497c6SRafael Auler   }
88516a497c6SRafael Auler 
88616a497c6SRafael Auler   /// Set the frequency of all calls in node \p NodeID to Freq. However, if
88716a497c6SRafael Auler   /// the calls have their own counters and do not depend on the basic block
88816a497c6SRafael Auler   /// counter, this means they have landing pads and throw exceptions. In this
88916a497c6SRafael Auler   /// case, set their frequency with their counters and return the maximum
89016a497c6SRafael Auler   /// value observed in such counters. This will be used as the new frequency
89116a497c6SRafael Auler   /// at basic block entry. This is used to fix the CFG edge frequencies in the
89216a497c6SRafael Auler   /// presence of exceptions.
89316a497c6SRafael Auler   uint64_t visitAllCallsIn(uint32_t NodeID, uint64_t Freq, uint64_t *CallFreqs,
89416a497c6SRafael Auler                            const FunctionDescription &D,
89516a497c6SRafael Auler                            const uint64_t *Counters,
89616a497c6SRafael Auler                            ProfileWriterContext &Ctx) const {
89716a497c6SRafael Auler     const auto &Entry = Entries[NodeID];
89816a497c6SRafael Auler     uint64_t MaxValue = 0ull;
89916a497c6SRafael Auler     for (int I = 0, E = Entry.NumCalls; I != E; ++I) {
90016a497c6SRafael Auler       const auto CallID = Entry.Calls[I];
90116a497c6SRafael Auler       DEBUG(reportNumber("  Setting freq for call ID: ", CallID, 10));
90216a497c6SRafael Auler       auto &CallDesc = D.Calls[CallID];
90316a497c6SRafael Auler       if (CallDesc.Counter == 0xffffffff) {
90416a497c6SRafael Auler         CallFreqs[CallID] = Freq;
90516a497c6SRafael Auler         DEBUG(reportNumber("  with : ", Freq, 10));
90616a497c6SRafael Auler       } else {
90716a497c6SRafael Auler         const auto CounterVal = Counters[CallDesc.Counter];
90816a497c6SRafael Auler         CallFreqs[CallID] = CounterVal;
90916a497c6SRafael Auler         MaxValue = CounterVal > MaxValue ? CounterVal : MaxValue;
91016a497c6SRafael Auler         DEBUG(reportNumber("  with (private counter) : ", CounterVal, 10));
91116a497c6SRafael Auler       }
91216a497c6SRafael Auler       DEBUG(reportNumber("  Address: 0x", CallDesc.TargetAddress, 16));
91316a497c6SRafael Auler       if (CallFreqs[CallID] > 0)
91416a497c6SRafael Auler         Ctx.CallFlowTable->get(CallDesc.TargetAddress).Calls +=
91516a497c6SRafael Auler             CallFreqs[CallID];
91616a497c6SRafael Auler     }
91716a497c6SRafael Auler     return MaxValue;
91816a497c6SRafael Auler   }
91916a497c6SRafael Auler 
92016a497c6SRafael Auler   ~NodeToCallsMap() {
92116a497c6SRafael Auler     for (int I = NumNodes - 1; I >= 0; --I) {
92216a497c6SRafael Auler       if (Entries[I].Calls)
92316a497c6SRafael Auler         Alloc.deallocate(Entries[I].Calls);
92416a497c6SRafael Auler     }
92516a497c6SRafael Auler     Alloc.deallocate(Entries);
92616a497c6SRafael Auler   }
92716a497c6SRafael Auler };
92816a497c6SRafael Auler 
92916a497c6SRafael Auler /// Fill an array with the frequency of each edge in the function represented
93016a497c6SRafael Auler /// by G, as well as another array for each call.
93116a497c6SRafael Auler void Graph::computeEdgeFrequencies(const uint64_t *Counters,
93216a497c6SRafael Auler                                    ProfileWriterContext &Ctx) {
93316a497c6SRafael Auler   if (NumNodes == 0)
93416a497c6SRafael Auler     return;
93516a497c6SRafael Auler 
93616a497c6SRafael Auler   EdgeFreqs = D.NumEdges ? new (Alloc, 0) uint64_t [D.NumEdges] : nullptr;
93716a497c6SRafael Auler   CallFreqs = D.NumCalls ? new (Alloc, 0) uint64_t [D.NumCalls] : nullptr;
93816a497c6SRafael Auler 
93916a497c6SRafael Auler   // Setup a lookup for calls present in each node (BB)
94016a497c6SRafael Auler   NodeToCallsMap *CallMap = new (Alloc) NodeToCallsMap(Alloc, D, NumNodes);
941cc4b2fb6SRafael Auler 
942cc4b2fb6SRafael Auler   // Perform a bottom-up, BFS traversal of the spanning tree in G. Edges in the
943cc4b2fb6SRafael Auler   // spanning tree don't have explicit counters. We must infer their value using
944cc4b2fb6SRafael Auler   // a linear combination of other counters (sum of counters of the outgoing
945cc4b2fb6SRafael Auler   // edges minus sum of counters of the incoming edges).
94616a497c6SRafael Auler   uint32_t *Stack = new (Alloc) uint32_t [NumNodes];
947cc4b2fb6SRafael Auler   uint32_t StackTop = 0;
948cc4b2fb6SRafael Auler   enum Status : uint8_t { S_NEW = 0, S_VISITING, S_VISITED };
94916a497c6SRafael Auler   Status *Visited = new (Alloc, 0) Status[NumNodes];
95016a497c6SRafael Auler   uint64_t *LeafFrequency = new (Alloc, 0) uint64_t[NumNodes];
95116a497c6SRafael Auler   uint64_t *EntryAddress = new (Alloc, 0) uint64_t[NumNodes];
952cc4b2fb6SRafael Auler 
953cc4b2fb6SRafael Auler   // Setup a fast lookup for frequency of leaf nodes, which have special
954cc4b2fb6SRafael Auler   // basic block frequency instrumentation (they are not edge profiled).
95516a497c6SRafael Auler   for (int I = 0; I < D.NumLeafNodes; ++I) {
95616a497c6SRafael Auler     LeafFrequency[D.LeafNodes[I].Node] = Counters[D.LeafNodes[I].Counter];
957cc4b2fb6SRafael Auler     DEBUG({
95816a497c6SRafael Auler       if (Counters[D.LeafNodes[I].Counter] > 0) {
95916a497c6SRafael Auler         reportNumber("Leaf Node# ", D.LeafNodes[I].Node, 10);
96016a497c6SRafael Auler         reportNumber("     Counter: ", Counters[D.LeafNodes[I].Counter], 10);
961cc4b2fb6SRafael Auler       }
962cc4b2fb6SRafael Auler     });
96316a497c6SRafael Auler   }
96416a497c6SRafael Auler   for (int I = 0; I < D.NumEntryNodes; ++I) {
96516a497c6SRafael Auler     EntryAddress[D.EntryNodes[I].Node] = D.EntryNodes[I].Address;
96616a497c6SRafael Auler     DEBUG({
96716a497c6SRafael Auler         reportNumber("Entry Node# ", D.EntryNodes[I].Node, 10);
96816a497c6SRafael Auler         reportNumber("      Address: ", D.EntryNodes[I].Address, 16);
96916a497c6SRafael Auler     });
970cc4b2fb6SRafael Auler   }
971cc4b2fb6SRafael Auler   // Add all root nodes to the stack
97216a497c6SRafael Auler   for (int I = 0; I < NumNodes; ++I) {
97316a497c6SRafael Auler     if (SpanningTreeNodes[I].NumInEdges == 0)
974cc4b2fb6SRafael Auler       Stack[StackTop++] = I;
975cc4b2fb6SRafael Auler   }
976cc4b2fb6SRafael Auler   // Empty stack?
977cc4b2fb6SRafael Auler   if (StackTop == 0) {
97816a497c6SRafael Auler     DEBUG(report("Empty stack!\n"));
97916a497c6SRafael Auler     Alloc.deallocate(EntryAddress);
980cc4b2fb6SRafael Auler     Alloc.deallocate(LeafFrequency);
981cc4b2fb6SRafael Auler     Alloc.deallocate(Visited);
982cc4b2fb6SRafael Auler     Alloc.deallocate(Stack);
98316a497c6SRafael Auler     CallMap->~NodeToCallsMap();
98416a497c6SRafael Auler     Alloc.deallocate(CallMap);
98516a497c6SRafael Auler     if (CallFreqs)
98616a497c6SRafael Auler       Alloc.deallocate(CallFreqs);
98716a497c6SRafael Auler     if (EdgeFreqs)
98816a497c6SRafael Auler       Alloc.deallocate(EdgeFreqs);
98916a497c6SRafael Auler     EdgeFreqs = nullptr;
99016a497c6SRafael Auler     CallFreqs = nullptr;
99116a497c6SRafael Auler     return;
992cc4b2fb6SRafael Auler   }
993cc4b2fb6SRafael Auler   // Add all known edge counts, will infer the rest
99416a497c6SRafael Auler   for (int I = 0; I < D.NumEdges; ++I) {
99516a497c6SRafael Auler     const uint32_t C = D.Edges[I].Counter;
996cc4b2fb6SRafael Auler     if (C == 0xffffffff) // inferred counter - we will compute its value
997cc4b2fb6SRafael Auler       continue;
99816a497c6SRafael Auler     EdgeFreqs[I] = Counters[C];
999cc4b2fb6SRafael Auler   }
1000cc4b2fb6SRafael Auler 
1001cc4b2fb6SRafael Auler   while (StackTop > 0) {
1002cc4b2fb6SRafael Auler     const uint32_t Cur = Stack[--StackTop];
1003cc4b2fb6SRafael Auler     DEBUG({
1004cc4b2fb6SRafael Auler       if (Visited[Cur] == S_VISITING)
1005cc4b2fb6SRafael Auler         report("(visiting) ");
1006cc4b2fb6SRafael Auler       else
1007cc4b2fb6SRafael Auler         report("(new) ");
1008cc4b2fb6SRafael Auler       reportNumber("Cur: ", Cur, 10);
1009cc4b2fb6SRafael Auler     });
1010cc4b2fb6SRafael Auler 
1011cc4b2fb6SRafael Auler     // This shouldn't happen in a tree
1012cc4b2fb6SRafael Auler     assert(Visited[Cur] != S_VISITED, "should not have visited nodes in stack");
1013cc4b2fb6SRafael Auler     if (Visited[Cur] == S_NEW) {
1014cc4b2fb6SRafael Auler       Visited[Cur] = S_VISITING;
1015cc4b2fb6SRafael Auler       Stack[StackTop++] = Cur;
101616a497c6SRafael Auler       assert(StackTop <= NumNodes, "stack grew too large");
101716a497c6SRafael Auler       for (int I = 0, E = SpanningTreeNodes[Cur].NumOutEdges; I < E; ++I) {
101816a497c6SRafael Auler         const uint32_t Succ = SpanningTreeNodes[Cur].OutEdges[I].Node;
1019cc4b2fb6SRafael Auler         Stack[StackTop++] = Succ;
102016a497c6SRafael Auler         assert(StackTop <= NumNodes, "stack grew too large");
1021cc4b2fb6SRafael Auler      }
1022cc4b2fb6SRafael Auler       continue;
1023cc4b2fb6SRafael Auler     }
1024cc4b2fb6SRafael Auler     Visited[Cur] = S_VISITED;
1025cc4b2fb6SRafael Auler 
1026cc4b2fb6SRafael Auler     // Establish our node frequency based on outgoing edges, which should all be
1027cc4b2fb6SRafael Auler     // resolved by now.
1028cc4b2fb6SRafael Auler     int64_t CurNodeFreq = LeafFrequency[Cur];
1029cc4b2fb6SRafael Auler     // Not a leaf?
1030cc4b2fb6SRafael Auler     if (!CurNodeFreq) {
103116a497c6SRafael Auler       for (int I = 0, E = CFGNodes[Cur].NumOutEdges; I != E; ++I) {
103216a497c6SRafael Auler         const uint32_t SuccEdge = CFGNodes[Cur].OutEdges[I].ID;
103316a497c6SRafael Auler         CurNodeFreq += EdgeFreqs[SuccEdge];
1034cc4b2fb6SRafael Auler       }
1035cc4b2fb6SRafael Auler     }
103616a497c6SRafael Auler     if (CurNodeFreq < 0)
103716a497c6SRafael Auler       CurNodeFreq = 0;
103816a497c6SRafael Auler 
103916a497c6SRafael Auler     const uint64_t CallFreq = CallMap->visitAllCallsIn(
104016a497c6SRafael Auler         Cur, CurNodeFreq > 0 ? CurNodeFreq : 0, CallFreqs, D, Counters, Ctx);
104116a497c6SRafael Auler 
104216a497c6SRafael Auler     // Exception handling affected our output flow? Fix with calls info
104316a497c6SRafael Auler     DEBUG({
104416a497c6SRafael Auler       if (CallFreq > CurNodeFreq)
104516a497c6SRafael Auler         report("Bumping node frequency with call info\n");
104616a497c6SRafael Auler     });
104716a497c6SRafael Auler     CurNodeFreq = CallFreq > CurNodeFreq ? CallFreq : CurNodeFreq;
104816a497c6SRafael Auler 
104916a497c6SRafael Auler     if (CurNodeFreq > 0) {
105016a497c6SRafael Auler       if (uint64_t Addr = EntryAddress[Cur]) {
105116a497c6SRafael Auler         DEBUG(
105216a497c6SRafael Auler             reportNumber("  Setting flow at entry point address 0x", Addr, 16));
105316a497c6SRafael Auler         DEBUG(reportNumber("  with: ", CurNodeFreq, 10));
105416a497c6SRafael Auler         Ctx.CallFlowTable->get(Addr).Val = CurNodeFreq;
105516a497c6SRafael Auler       }
105616a497c6SRafael Auler     }
105716a497c6SRafael Auler 
105816a497c6SRafael Auler     // No parent? Reached a tree root, limit to call frequency updating.
105916a497c6SRafael Auler     if (SpanningTreeNodes[Cur].NumInEdges == 0) {
106016a497c6SRafael Auler       continue;
106116a497c6SRafael Auler     }
106216a497c6SRafael Auler 
106316a497c6SRafael Auler     assert(SpanningTreeNodes[Cur].NumInEdges == 1, "must have 1 parent");
106416a497c6SRafael Auler     const uint32_t Parent = SpanningTreeNodes[Cur].InEdges[0].Node;
106516a497c6SRafael Auler     const uint32_t ParentEdge = SpanningTreeNodes[Cur].InEdges[0].ID;
106616a497c6SRafael Auler 
1067cc4b2fb6SRafael Auler     // Calculate parent edge freq.
106816a497c6SRafael Auler     int64_t ParentEdgeFreq = CurNodeFreq;
106916a497c6SRafael Auler     for (int I = 0, E = CFGNodes[Cur].NumInEdges; I != E; ++I) {
107016a497c6SRafael Auler       const uint32_t PredEdge = CFGNodes[Cur].InEdges[I].ID;
107116a497c6SRafael Auler       ParentEdgeFreq -= EdgeFreqs[PredEdge];
1072cc4b2fb6SRafael Auler     }
107316a497c6SRafael Auler 
1074cc4b2fb6SRafael Auler     // Sometimes the conservative CFG that BOLT builds will lead to incorrect
1075cc4b2fb6SRafael Auler     // flow computation. For example, in a BB that transitively calls the exit
1076cc4b2fb6SRafael Auler     // syscall, BOLT will add a fall-through successor even though it should not
1077cc4b2fb6SRafael Auler     // have any successors. So this block execution will likely be wrong. We
1078cc4b2fb6SRafael Auler     // tolerate this imperfection since this case should be quite infrequent.
1079cc4b2fb6SRafael Auler     if (ParentEdgeFreq < 0) {
108016a497c6SRafael Auler       DEBUG(dumpEdgeFreqs());
1081cc4b2fb6SRafael Auler       DEBUG(report("WARNING: incorrect flow"));
1082cc4b2fb6SRafael Auler       ParentEdgeFreq = 0;
1083cc4b2fb6SRafael Auler     }
1084cc4b2fb6SRafael Auler     DEBUG(reportNumber("  Setting freq for ParentEdge: ", ParentEdge, 10));
1085cc4b2fb6SRafael Auler     DEBUG(reportNumber("  with ParentEdgeFreq: ", ParentEdgeFreq, 10));
108616a497c6SRafael Auler     EdgeFreqs[ParentEdge] = ParentEdgeFreq;
1087cc4b2fb6SRafael Auler   }
1088cc4b2fb6SRafael Auler 
108916a497c6SRafael Auler   Alloc.deallocate(EntryAddress);
1090cc4b2fb6SRafael Auler   Alloc.deallocate(LeafFrequency);
1091cc4b2fb6SRafael Auler   Alloc.deallocate(Visited);
1092cc4b2fb6SRafael Auler   Alloc.deallocate(Stack);
109316a497c6SRafael Auler   CallMap->~NodeToCallsMap();
109416a497c6SRafael Auler   Alloc.deallocate(CallMap);
109516a497c6SRafael Auler   DEBUG(dumpEdgeFreqs());
1096cc4b2fb6SRafael Auler }
1097cc4b2fb6SRafael Auler 
109816a497c6SRafael Auler /// Write to \p FD all of the edge profiles for function \p FuncDesc. Uses
109916a497c6SRafael Auler /// \p Alloc to allocate helper dynamic structures used to compute profile for
110016a497c6SRafael Auler /// edges that we do not explictly instrument.
110116a497c6SRafael Auler const uint8_t *writeFunctionProfile(int FD, ProfileWriterContext &Ctx,
110216a497c6SRafael Auler                                     const uint8_t *FuncDesc,
110316a497c6SRafael Auler                                     BumpPtrAllocator &Alloc) {
110416a497c6SRafael Auler   const FunctionDescription F(FuncDesc);
110516a497c6SRafael Auler   const uint8_t *next = FuncDesc + F.getSize();
1106cc4b2fb6SRafael Auler 
1107cc4b2fb6SRafael Auler   // Skip funcs we know are cold
1108cc4b2fb6SRafael Auler #ifndef ENABLE_DEBUG
110916a497c6SRafael Auler   uint64_t CountersFreq = 0;
111016a497c6SRafael Auler   for (int I = 0; I < F.NumLeafNodes; ++I) {
111116a497c6SRafael Auler     CountersFreq += __bolt_instr_locations[F.LeafNodes[I].Counter];
1112cc4b2fb6SRafael Auler   }
111316a497c6SRafael Auler   if (CountersFreq == 0) {
111416a497c6SRafael Auler     for (int I = 0; I < F.NumEdges; ++I) {
111516a497c6SRafael Auler       const uint32_t C = F.Edges[I].Counter;
111616a497c6SRafael Auler       if (C == 0xffffffff)
111716a497c6SRafael Auler         continue;
111816a497c6SRafael Auler       CountersFreq += __bolt_instr_locations[C];
111916a497c6SRafael Auler     }
112016a497c6SRafael Auler     if (CountersFreq == 0) {
112116a497c6SRafael Auler       for (int I = 0; I < F.NumCalls; ++I) {
112216a497c6SRafael Auler         const uint32_t C = F.Calls[I].Counter;
112316a497c6SRafael Auler         if (C == 0xffffffff)
112416a497c6SRafael Auler           continue;
112516a497c6SRafael Auler         CountersFreq += __bolt_instr_locations[C];
112616a497c6SRafael Auler       }
112716a497c6SRafael Auler       if (CountersFreq == 0)
1128cc4b2fb6SRafael Auler         return next;
112916a497c6SRafael Auler     }
113016a497c6SRafael Auler   }
1131cc4b2fb6SRafael Auler #endif
1132cc4b2fb6SRafael Auler 
113316a497c6SRafael Auler   Graph *G = new (Alloc) Graph(Alloc, F, __bolt_instr_locations, Ctx);
1134cc4b2fb6SRafael Auler   DEBUG(G->dump());
113516a497c6SRafael Auler   if (!G->EdgeFreqs && !G->CallFreqs) {
1136cc4b2fb6SRafael Auler     G->~Graph();
1137cc4b2fb6SRafael Auler     Alloc.deallocate(G);
1138cc4b2fb6SRafael Auler     return next;
1139cc4b2fb6SRafael Auler   }
1140cc4b2fb6SRafael Auler 
114116a497c6SRafael Auler   for (int I = 0; I < F.NumEdges; ++I) {
114216a497c6SRafael Auler     const uint64_t Freq = G->EdgeFreqs[I];
1143cc4b2fb6SRafael Auler     if (Freq == 0)
1144cc4b2fb6SRafael Auler       continue;
114516a497c6SRafael Auler     const EdgeDescription *Desc = &F.Edges[I];
1146cc4b2fb6SRafael Auler     char LineBuf[BufSize];
1147cc4b2fb6SRafael Auler     char *Ptr = LineBuf;
114816a497c6SRafael Auler     Ptr = serializeLoc(Ctx, Ptr, Desc->From, BufSize);
114916a497c6SRafael Auler     Ptr = serializeLoc(Ctx, Ptr, Desc->To, BufSize - (Ptr - LineBuf));
1150cc4b2fb6SRafael Auler     Ptr = strCopy(Ptr, "0 ", BufSize - (Ptr - LineBuf) - 22);
1151cc4b2fb6SRafael Auler     Ptr = intToStr(Ptr, Freq, 10);
1152cc4b2fb6SRafael Auler     *Ptr++ = '\n';
1153cc4b2fb6SRafael Auler     __write(FD, LineBuf, Ptr - LineBuf);
1154cc4b2fb6SRafael Auler   }
1155cc4b2fb6SRafael Auler 
115616a497c6SRafael Auler   for (int I = 0; I < F.NumCalls; ++I) {
115716a497c6SRafael Auler     const uint64_t Freq = G->CallFreqs[I];
115816a497c6SRafael Auler     if (Freq == 0)
115916a497c6SRafael Auler       continue;
116016a497c6SRafael Auler     char LineBuf[BufSize];
116116a497c6SRafael Auler     char *Ptr = LineBuf;
116216a497c6SRafael Auler     const CallDescription *Desc = &F.Calls[I];
116316a497c6SRafael Auler     Ptr = serializeLoc(Ctx, Ptr, Desc->From, BufSize);
116416a497c6SRafael Auler     Ptr = serializeLoc(Ctx, Ptr, Desc->To, BufSize - (Ptr - LineBuf));
116516a497c6SRafael Auler     Ptr = strCopy(Ptr, "0 ", BufSize - (Ptr - LineBuf) - 25);
116616a497c6SRafael Auler     Ptr = intToStr(Ptr, Freq, 10);
116716a497c6SRafael Auler     *Ptr++ = '\n';
116816a497c6SRafael Auler     __write(FD, LineBuf, Ptr - LineBuf);
116916a497c6SRafael Auler   }
117016a497c6SRafael Auler 
1171cc4b2fb6SRafael Auler   G->~Graph();
1172cc4b2fb6SRafael Auler   Alloc.deallocate(G);
1173cc4b2fb6SRafael Auler   return next;
1174cc4b2fb6SRafael Auler }
1175cc4b2fb6SRafael Auler 
117616a497c6SRafael Auler const IndCallTargetDescription *
117716a497c6SRafael Auler ProfileWriterContext::lookupIndCallTarget(uint64_t Target) const {
117816a497c6SRafael Auler   uint32_t B = 0;
117916a497c6SRafael Auler   uint32_t E = __bolt_instr_num_ind_targets;
118016a497c6SRafael Auler   if (E == 0)
118116a497c6SRafael Auler     return nullptr;
118216a497c6SRafael Auler   do {
118316a497c6SRafael Auler     uint32_t I = (E - B) / 2 + B;
118416a497c6SRafael Auler     if (IndCallTargets[I].Address == Target)
118516a497c6SRafael Auler       return &IndCallTargets[I];
118616a497c6SRafael Auler     if (IndCallTargets[I].Address < Target)
118716a497c6SRafael Auler       B = I + 1;
118816a497c6SRafael Auler     else
118916a497c6SRafael Auler       E = I;
119016a497c6SRafael Auler   } while (B < E);
119116a497c6SRafael Auler   return nullptr;
1192cc4b2fb6SRafael Auler }
119362aa74f8SRafael Auler 
119416a497c6SRafael Auler /// Write a single indirect call <src, target> pair to the fdata file
119516a497c6SRafael Auler void visitIndCallCounter(IndirectCallHashTable::MapEntry &Entry,
119616a497c6SRafael Auler                          int FD, int CallsiteID,
119716a497c6SRafael Auler                          ProfileWriterContext *Ctx) {
119816a497c6SRafael Auler   if (Entry.Val == 0)
119916a497c6SRafael Auler     return;
120016a497c6SRafael Auler   DEBUG(reportNumber("Target func 0x", Entry.Key, 16));
120116a497c6SRafael Auler   DEBUG(reportNumber("Target freq: ", Entry.Val, 10));
120216a497c6SRafael Auler   const IndCallDescription *CallsiteDesc =
120316a497c6SRafael Auler       &Ctx->IndCallDescriptions[CallsiteID];
120416a497c6SRafael Auler   const IndCallTargetDescription *TargetDesc =
120516a497c6SRafael Auler       Ctx->lookupIndCallTarget(Entry.Key);
120616a497c6SRafael Auler   if (!TargetDesc) {
120716a497c6SRafael Auler     DEBUG(report("Failed to lookup indirect call target\n"));
1208cc4b2fb6SRafael Auler     char LineBuf[BufSize];
120962aa74f8SRafael Auler     char *Ptr = LineBuf;
121016a497c6SRafael Auler     Ptr = serializeLoc(*Ctx, Ptr, *CallsiteDesc, BufSize);
121116a497c6SRafael Auler     Ptr = strCopy(Ptr, "0 [unknown] 0 0 ", BufSize - (Ptr - LineBuf) - 40);
121216a497c6SRafael Auler     Ptr = intToStr(Ptr, Entry.Val, 10);
121316a497c6SRafael Auler     *Ptr++ = '\n';
121416a497c6SRafael Auler     __write(FD, LineBuf, Ptr - LineBuf);
121516a497c6SRafael Auler     return;
121616a497c6SRafael Auler   }
121716a497c6SRafael Auler   Ctx->CallFlowTable->get(TargetDesc->Address).Calls += Entry.Val;
121816a497c6SRafael Auler   char LineBuf[BufSize];
121916a497c6SRafael Auler   char *Ptr = LineBuf;
122016a497c6SRafael Auler   Ptr = serializeLoc(*Ctx, Ptr, *CallsiteDesc, BufSize);
122116a497c6SRafael Auler   Ptr = serializeLoc(*Ctx, Ptr, TargetDesc->Loc, BufSize - (Ptr - LineBuf));
1222cc4b2fb6SRafael Auler   Ptr = strCopy(Ptr, "0 ", BufSize - (Ptr - LineBuf) - 25);
122316a497c6SRafael Auler   Ptr = intToStr(Ptr, Entry.Val, 10);
122462aa74f8SRafael Auler   *Ptr++ = '\n';
1225821480d2SRafael Auler   __write(FD, LineBuf, Ptr - LineBuf);
122662aa74f8SRafael Auler }
1227cc4b2fb6SRafael Auler 
122816a497c6SRafael Auler /// Write to \p FD all of the indirect call profiles.
122916a497c6SRafael Auler void writeIndirectCallProfile(int FD, ProfileWriterContext &Ctx) {
123016a497c6SRafael Auler   for (int I = 0; I < __bolt_instr_num_ind_calls; ++I) {
123116a497c6SRafael Auler     DEBUG(reportNumber("IndCallsite #", I, 10));
123216a497c6SRafael Auler     GlobalIndCallCounters[I].forEachElement(visitIndCallCounter, FD, I, &Ctx);
123316a497c6SRafael Auler   }
123416a497c6SRafael Auler }
123516a497c6SRafael Auler 
123616a497c6SRafael Auler /// Check a single call flow for a callee versus all known callers. If there are
123716a497c6SRafael Auler /// less callers than what the callee expects, write the difference with source
123816a497c6SRafael Auler /// [unknown] in the profile.
123916a497c6SRafael Auler void visitCallFlowEntry(CallFlowHashTable::MapEntry &Entry, int FD,
124016a497c6SRafael Auler                         ProfileWriterContext *Ctx) {
124116a497c6SRafael Auler   DEBUG(reportNumber("Call flow entry address: 0x", Entry.Key, 16));
124216a497c6SRafael Auler   DEBUG(reportNumber("Calls: ", Entry.Calls, 10));
124316a497c6SRafael Auler   DEBUG(reportNumber("Reported entry frequency: ", Entry.Val, 10));
124416a497c6SRafael Auler   DEBUG({
124516a497c6SRafael Auler     if (Entry.Calls > Entry.Val)
124616a497c6SRafael Auler       report("  More calls than expected!\n");
124716a497c6SRafael Auler   });
124816a497c6SRafael Auler   if (Entry.Val <= Entry.Calls)
124916a497c6SRafael Auler     return;
125016a497c6SRafael Auler   DEBUG(reportNumber(
125116a497c6SRafael Auler       "  Balancing calls with traffic: ", Entry.Val - Entry.Calls, 10));
125216a497c6SRafael Auler   const IndCallTargetDescription *TargetDesc =
125316a497c6SRafael Auler       Ctx->lookupIndCallTarget(Entry.Key);
125416a497c6SRafael Auler   if (!TargetDesc) {
125516a497c6SRafael Auler     // There is probably something wrong with this callee and this should be
125616a497c6SRafael Auler     // investigated, but I don't want to assert and lose all data collected.
125716a497c6SRafael Auler     DEBUG(report("WARNING: failed to look up call target!\n"));
125816a497c6SRafael Auler     return;
125916a497c6SRafael Auler   }
126016a497c6SRafael Auler   char LineBuf[BufSize];
126116a497c6SRafael Auler   char *Ptr = LineBuf;
126216a497c6SRafael Auler   Ptr = strCopy(Ptr, "0 [unknown] 0 ", BufSize);
126316a497c6SRafael Auler   Ptr = serializeLoc(*Ctx, Ptr, TargetDesc->Loc, BufSize - (Ptr - LineBuf));
126416a497c6SRafael Auler   Ptr = strCopy(Ptr, "0 ", BufSize - (Ptr - LineBuf) - 25);
126516a497c6SRafael Auler   Ptr = intToStr(Ptr, Entry.Val - Entry.Calls, 10);
126616a497c6SRafael Auler   *Ptr++ = '\n';
126716a497c6SRafael Auler   __write(FD, LineBuf, Ptr - LineBuf);
126816a497c6SRafael Auler }
126916a497c6SRafael Auler 
127016a497c6SRafael Auler /// Open fdata file for writing and return a valid file descriptor, aborting
127116a497c6SRafael Auler /// program upon failure.
127216a497c6SRafael Auler int openProfile() {
127316a497c6SRafael Auler   // Build the profile name string by appending our PID
127416a497c6SRafael Auler   char Buf[BufSize];
127516a497c6SRafael Auler   char *Ptr = Buf;
127616a497c6SRafael Auler   uint64_t PID = __getpid();
127716a497c6SRafael Auler   Ptr = strCopy(Buf, __bolt_instr_filename, BufSize);
127816a497c6SRafael Auler   if (__bolt_instr_use_pid) {
127916a497c6SRafael Auler     Ptr = strCopy(Ptr, ".", BufSize - (Ptr - Buf + 1));
128016a497c6SRafael Auler     Ptr = intToStr(Ptr, PID, 10);
128116a497c6SRafael Auler     Ptr = strCopy(Ptr, ".fdata", BufSize - (Ptr - Buf + 1));
128216a497c6SRafael Auler   }
128316a497c6SRafael Auler   *Ptr++ = '\0';
128416a497c6SRafael Auler   uint64_t FD = __open(Buf,
128516a497c6SRafael Auler                        /*flags=*/0x241 /*O_WRONLY|O_TRUNC|O_CREAT*/,
128616a497c6SRafael Auler                        /*mode=*/0666);
128716a497c6SRafael Auler   if (static_cast<int64_t>(FD) < 0) {
128816a497c6SRafael Auler     report("Error while trying to open profile file for writing: ");
128916a497c6SRafael Auler     report(Buf);
129016a497c6SRafael Auler     reportNumber("\nFailed with error number: 0x",
129116a497c6SRafael Auler                  0 - static_cast<int64_t>(FD), 16);
129216a497c6SRafael Auler     __exit(1);
129316a497c6SRafael Auler   }
129416a497c6SRafael Auler   return FD;
129516a497c6SRafael Auler }
129616a497c6SRafael Auler } // anonymous namespace
129716a497c6SRafael Auler 
129816a497c6SRafael Auler /// Reset all counters in case you want to start profiling a new phase of your
129916a497c6SRafael Auler /// program independently of prior phases.
130016a497c6SRafael Auler /// The address of this function is printed by BOLT and this can be called by
130116a497c6SRafael Auler /// any attached debugger during runtime. There is a useful oneliner for gdb:
130216a497c6SRafael Auler ///
130316a497c6SRafael Auler ///   gdb -p $(pgrep -xo PROCESSNAME) -ex 'p ((void(*)())0xdeadbeef)()' \
130416a497c6SRafael Auler ///     -ex 'set confirm off' -ex quit
130516a497c6SRafael Auler ///
130616a497c6SRafael Auler /// Where 0xdeadbeef is this function address and PROCESSNAME your binary file
130716a497c6SRafael Auler /// name.
130816a497c6SRafael Auler extern "C" void __bolt_instr_clear_counters() {
130916a497c6SRafael Auler   memSet(reinterpret_cast<char *>(__bolt_instr_locations), 0,
131016a497c6SRafael Auler          __bolt_num_counters * 8);
131116a497c6SRafael Auler   for (int I = 0; I < __bolt_instr_num_ind_calls; ++I) {
131216a497c6SRafael Auler     GlobalIndCallCounters[I].resetCounters();
131316a497c6SRafael Auler   }
131416a497c6SRafael Auler }
131516a497c6SRafael Auler 
131616a497c6SRafael Auler /// This is the entry point for profile writing.
131716a497c6SRafael Auler /// There are three ways of getting here:
131816a497c6SRafael Auler ///
131916a497c6SRafael Auler ///  * Program execution ended, finalization methods are running and BOLT
132016a497c6SRafael Auler ///    hooked into FINI from your binary dynamic section;
132116a497c6SRafael Auler ///  * You used the sleep timer option and during initialization we forked
132216a497c6SRafael Auler ///    a separete process that will call this function periodically;
132316a497c6SRafael Auler ///  * BOLT prints this function address so you can attach a debugger and
132416a497c6SRafael Auler ///    call this function directly to get your profile written to disk
132516a497c6SRafael Auler ///    on demand.
132616a497c6SRafael Auler ///
132716a497c6SRafael Auler extern "C" void __bolt_instr_data_dump() {
132816a497c6SRafael Auler   // Already dumping
132916a497c6SRafael Auler   if (!GlobalWriteProfileMutex->acquire())
133016a497c6SRafael Auler     return;
133116a497c6SRafael Auler 
133216a497c6SRafael Auler   BumpPtrAllocator HashAlloc;
133316a497c6SRafael Auler   HashAlloc.setMaxSize(0x6400000);
133416a497c6SRafael Auler   ProfileWriterContext Ctx = readDescriptions();
133516a497c6SRafael Auler   Ctx.CallFlowTable = new (HashAlloc, 0) CallFlowHashTable(HashAlloc);
133616a497c6SRafael Auler 
133716a497c6SRafael Auler   DEBUG(printStats(Ctx));
133816a497c6SRafael Auler 
133916a497c6SRafael Auler   int FD = openProfile();
134016a497c6SRafael Auler 
1341cc4b2fb6SRafael Auler   BumpPtrAllocator Alloc;
134216a497c6SRafael Auler   const uint8_t *FuncDesc = Ctx.FuncDescriptions;
1343cc4b2fb6SRafael Auler   for (int I = 0, E = __bolt_instr_num_funcs; I < E; ++I) {
134416a497c6SRafael Auler     FuncDesc = writeFunctionProfile(FD, Ctx, FuncDesc, Alloc);
134516a497c6SRafael Auler     Alloc.clear();
1346cc4b2fb6SRafael Auler     DEBUG(reportNumber("FuncDesc now: ", (uint64_t)FuncDesc, 16));
1347cc4b2fb6SRafael Auler   }
134816a497c6SRafael Auler   assert(FuncDesc == (void *)Ctx.Strings,
1349cc4b2fb6SRafael Auler          "FuncDesc ptr must be equal to stringtable");
1350cc4b2fb6SRafael Auler 
135116a497c6SRafael Auler   writeIndirectCallProfile(FD, Ctx);
135216a497c6SRafael Auler   Ctx.CallFlowTable->forEachElement(visitCallFlowEntry, FD, &Ctx);
135316a497c6SRafael Auler 
1354821480d2SRafael Auler   __close(FD);
135516a497c6SRafael Auler   __munmap(Ctx.MMapPtr, Ctx.MMapSize);
135616a497c6SRafael Auler   __close(Ctx.FileDesc);
135716a497c6SRafael Auler   HashAlloc.destroy();
135816a497c6SRafael Auler   GlobalWriteProfileMutex->release();
135916a497c6SRafael Auler   DEBUG(report("Finished writing profile.\n"));
136016a497c6SRafael Auler }
136116a497c6SRafael Auler 
136216a497c6SRafael Auler /// Event loop for our child process spawned during setup to dump profile data
136316a497c6SRafael Auler /// at user-specified intervals
136416a497c6SRafael Auler void watchProcess() {
136516a497c6SRafael Auler   timespec ts, rem;
136616a497c6SRafael Auler   uint64_t Ellapsed = 0ull;
136716a497c6SRafael Auler   ts.tv_sec = 1;
136816a497c6SRafael Auler   ts.tv_nsec = 0;
136916a497c6SRafael Auler   while (1) {
137016a497c6SRafael Auler     __nanosleep(&ts, &rem);
137116a497c6SRafael Auler     // This means our parent process died, so no need for us to keep dumping.
137216a497c6SRafael Auler     // Notice that make and some systems will wait until all child processes
137316a497c6SRafael Auler     // of a command finishes before proceeding, so it is important to exit as
137416a497c6SRafael Auler     // early as possible once our parent dies.
137516a497c6SRafael Auler     if (__getppid() == 1) {
137616a497c6SRafael Auler       break;
137716a497c6SRafael Auler     }
137816a497c6SRafael Auler     if (++Ellapsed < __bolt_instr_sleep_time)
137916a497c6SRafael Auler       continue;
138016a497c6SRafael Auler     Ellapsed = 0;
138116a497c6SRafael Auler     __bolt_instr_data_dump();
138216a497c6SRafael Auler     __bolt_instr_clear_counters();
138316a497c6SRafael Auler   }
138416a497c6SRafael Auler   DEBUG(report("My parent process is dead, bye!\n"));
138516a497c6SRafael Auler   __exit(0);
138616a497c6SRafael Auler }
138716a497c6SRafael Auler 
138816a497c6SRafael Auler extern "C" void __bolt_instr_indirect_call();
138916a497c6SRafael Auler extern "C" void __bolt_instr_indirect_tailcall();
139016a497c6SRafael Auler 
139116a497c6SRafael Auler /// Initialization code
139216a497c6SRafael Auler extern "C" void __bolt_instr_setup() {
139316a497c6SRafael Auler   const uint64_t CountersStart =
139416a497c6SRafael Auler       reinterpret_cast<uint64_t>(&__bolt_instr_locations[0]);
139516a497c6SRafael Auler   const uint64_t CountersEnd = alignTo(
139616a497c6SRafael Auler       reinterpret_cast<uint64_t>(&__bolt_instr_locations[__bolt_num_counters]),
139716a497c6SRafael Auler       0x1000);
139816a497c6SRafael Auler   DEBUG(reportNumber("replace mmap start: ", CountersStart, 16));
139916a497c6SRafael Auler   DEBUG(reportNumber("replace mmap stop: ", CountersEnd, 16));
140016a497c6SRafael Auler   assert (CountersEnd > CountersStart, "no counters");
140116a497c6SRafael Auler   // Maps our counters to be shared instead of private, so we keep counting for
140216a497c6SRafael Auler   // forked processes
140316a497c6SRafael Auler   __mmap(CountersStart, CountersEnd - CountersStart,
140416a497c6SRafael Auler          0x3 /*PROT_READ|PROT_WRITE*/,
140516a497c6SRafael Auler          0x31 /*MAP_ANONYMOUS | MAP_SHARED | MAP_FIXED*/, -1, 0);
140616a497c6SRafael Auler 
140716a497c6SRafael Auler   __bolt_trampoline_ind_call = __bolt_instr_indirect_call;
140816a497c6SRafael Auler   __bolt_trampoline_ind_tailcall = __bolt_instr_indirect_tailcall;
140916a497c6SRafael Auler   // Conservatively reserve 100MiB shared pages
141016a497c6SRafael Auler   GlobalAlloc.setMaxSize(0x6400000);
141116a497c6SRafael Auler   GlobalAlloc.setShared(true);
141216a497c6SRafael Auler   GlobalWriteProfileMutex = new (GlobalAlloc, 0) Mutex();
141316a497c6SRafael Auler   if (__bolt_instr_num_ind_calls > 0)
141416a497c6SRafael Auler     GlobalIndCallCounters =
141516a497c6SRafael Auler         new (GlobalAlloc, 0) IndirectCallHashTable[__bolt_instr_num_ind_calls];
141616a497c6SRafael Auler 
141716a497c6SRafael Auler   if (__bolt_instr_sleep_time != 0) {
141816a497c6SRafael Auler     if (auto PID = __fork())
141916a497c6SRafael Auler       return;
142016a497c6SRafael Auler     watchProcess();
142116a497c6SRafael Auler   }
142216a497c6SRafael Auler }
142316a497c6SRafael Auler 
142416a497c6SRafael Auler extern "C" void instrumentIndirectCall(uint64_t Target, uint64_t IndCallID) {
142516a497c6SRafael Auler   GlobalIndCallCounters[IndCallID].incrementVal(Target, GlobalAlloc);
142616a497c6SRafael Auler }
142716a497c6SRafael Auler 
142816a497c6SRafael Auler /// We receive as in-stack arguments the identifier of the indirect call site
142916a497c6SRafael Auler /// as well as the target address for the call
143016a497c6SRafael Auler extern "C" __attribute((naked)) void __bolt_instr_indirect_call()
143116a497c6SRafael Auler {
143216a497c6SRafael Auler   __asm__ __volatile__(SAVE_ALL
1433c6799a68SRafael Auler                        "mov 0x90(%%rsp), %%rdi\n"
1434c6799a68SRafael Auler                        "mov 0x88(%%rsp), %%rsi\n"
143516a497c6SRafael Auler                        "call instrumentIndirectCall\n"
143616a497c6SRafael Auler                        RESTORE_ALL
143716a497c6SRafael Auler                        "pop %%rdi\n"
143816a497c6SRafael Auler                        "add $16, %%rsp\n"
143916a497c6SRafael Auler                        "xchg (%%rsp), %%rdi\n"
144016a497c6SRafael Auler                        "jmp *-8(%%rsp)\n"
144116a497c6SRafael Auler                        :::);
144216a497c6SRafael Auler }
144316a497c6SRafael Auler 
144416a497c6SRafael Auler extern "C" __attribute((naked)) void __bolt_instr_indirect_tailcall()
144516a497c6SRafael Auler {
144616a497c6SRafael Auler   __asm__ __volatile__(SAVE_ALL
1447c6799a68SRafael Auler                        "mov 0x88(%%rsp), %%rdi\n"
1448c6799a68SRafael Auler                        "mov 0x80(%%rsp), %%rsi\n"
144916a497c6SRafael Auler                        "call instrumentIndirectCall\n"
145016a497c6SRafael Auler                        RESTORE_ALL
145116a497c6SRafael Auler                        "add $16, %%rsp\n"
145216a497c6SRafael Auler                        "pop %%rdi\n"
145316a497c6SRafael Auler                        "jmp *-16(%%rsp)\n"
145416a497c6SRafael Auler                        :::);
145516a497c6SRafael Auler }
145616a497c6SRafael Auler 
145716a497c6SRafael Auler /// This is hooking ELF's entry, it needs to save all machine state.
145816a497c6SRafael Auler extern "C" __attribute((naked)) void __bolt_instr_start()
145916a497c6SRafael Auler {
146016a497c6SRafael Auler   __asm__ __volatile__(SAVE_ALL
146116a497c6SRafael Auler                        "call __bolt_instr_setup\n"
146216a497c6SRafael Auler                        RESTORE_ALL
14638c7f524aSAlexander Shaposhnikov                        "jmp *__bolt_instr_init_ptr(%%rip)\n"
146416a497c6SRafael Auler                        :::);
146516a497c6SRafael Auler }
146616a497c6SRafael Auler 
146716a497c6SRafael Auler /// This is hooking into ELF's DT_FINI
146816a497c6SRafael Auler extern "C" void __bolt_instr_fini() {
146916a497c6SRafael Auler   __bolt_instr_fini_ptr();
147016a497c6SRafael Auler   if (__bolt_instr_sleep_time == 0)
147116a497c6SRafael Auler     __bolt_instr_data_dump();
147216a497c6SRafael Auler   DEBUG(report("Finished.\n"));
147362aa74f8SRafael Auler }
1474bbd9d610SAlexander Shaposhnikov 
1475*3b876cc3SAlexander Shaposhnikov #endif
1476*3b876cc3SAlexander Shaposhnikov 
1477*3b876cc3SAlexander Shaposhnikov #if defined(__APPLE__)
1478bbd9d610SAlexander Shaposhnikov 
1479bbd9d610SAlexander Shaposhnikov // On OSX/iOS the final symbol name of an extern "C" function/variable contains
1480bbd9d610SAlexander Shaposhnikov // one extra leading underscore: _bolt_instr_setup -> __bolt_instr_setup.
1481*3b876cc3SAlexander Shaposhnikov extern "C"
1482*3b876cc3SAlexander Shaposhnikov __attribute__((section("__TEXT,__setup")))
1483*3b876cc3SAlexander Shaposhnikov __attribute__((force_align_arg_pointer))
1484*3b876cc3SAlexander Shaposhnikov void _bolt_instr_setup() {
14851cf23e5eSAlexander Shaposhnikov   const char *Message = "Hello!\n";
14861cf23e5eSAlexander Shaposhnikov   __write(2, Message, 7);
1487*3b876cc3SAlexander Shaposhnikov 
1488*3b876cc3SAlexander Shaposhnikov   uint32_t NumCounters = _bolt_num_counters_getter();
1489*3b876cc3SAlexander Shaposhnikov   reportNumber("__bolt_instr_setup, number of counters: ", NumCounters, 10);
1490*3b876cc3SAlexander Shaposhnikov 
1491*3b876cc3SAlexander Shaposhnikov   uint64_t *Locs = _bolt_instr_locations_getter();
1492*3b876cc3SAlexander Shaposhnikov   reportNumber("__bolt_instr_setup, address of counters: ",
1493*3b876cc3SAlexander Shaposhnikov                reinterpret_cast<uint64_t>(Locs), 10);
1494*3b876cc3SAlexander Shaposhnikov 
1495*3b876cc3SAlexander Shaposhnikov   for (size_t I = 0; I < NumCounters; ++I)
1496*3b876cc3SAlexander Shaposhnikov     reportNumber("Counter value: ", Locs[I], 10);
14971cf23e5eSAlexander Shaposhnikov }
1498bbd9d610SAlexander Shaposhnikov 
1499*3b876cc3SAlexander Shaposhnikov extern "C"
1500*3b876cc3SAlexander Shaposhnikov __attribute__((section("__TEXT,__fini")))
1501*3b876cc3SAlexander Shaposhnikov __attribute__((force_align_arg_pointer))
1502*3b876cc3SAlexander Shaposhnikov void _bolt_instr_fini() {
1503*3b876cc3SAlexander Shaposhnikov   uint32_t NumCounters = _bolt_num_counters_getter();
1504*3b876cc3SAlexander Shaposhnikov   reportNumber("__bolt_instr_fini, number of counters: ", NumCounters, 10);
1505*3b876cc3SAlexander Shaposhnikov 
1506*3b876cc3SAlexander Shaposhnikov   uint64_t *Locs = _bolt_instr_locations_getter();
1507*3b876cc3SAlexander Shaposhnikov   reportNumber("__bolt_instr_fini, address of counters: ",
1508*3b876cc3SAlexander Shaposhnikov                reinterpret_cast<uint64_t>(Locs), 10);
1509*3b876cc3SAlexander Shaposhnikov 
1510*3b876cc3SAlexander Shaposhnikov   for (size_t I = 0; I < NumCounters; ++I)
1511*3b876cc3SAlexander Shaposhnikov     reportNumber("Counter value: ", Locs[I], 10);
1512*3b876cc3SAlexander Shaposhnikov 
1513e067f2adSAlexander Shaposhnikov   const char *Message = "Bye!\n";
1514e067f2adSAlexander Shaposhnikov   __write(2, Message, 5);
1515e067f2adSAlexander Shaposhnikov }
1516e067f2adSAlexander Shaposhnikov 
1517bbd9d610SAlexander Shaposhnikov #endif
1518