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 603b876cc3SAlexander Shaposhnikov 613b876cc3SAlexander Shaposhnikov #if defined(__APPLE__) 623b876cc3SAlexander Shaposhnikov extern "C" { 633b876cc3SAlexander Shaposhnikov extern uint64_t* _bolt_instr_locations_getter(); 643b876cc3SAlexander Shaposhnikov extern uint32_t _bolt_num_counters_getter(); 653b876cc3SAlexander Shaposhnikov 66*a0dd5b05SAlexander Shaposhnikov extern uint8_t* _bolt_instr_tables_getter(); 67*a0dd5b05SAlexander Shaposhnikov extern uint32_t _bolt_instr_num_funcs_getter(); 683b876cc3SAlexander Shaposhnikov } 693b876cc3SAlexander Shaposhnikov 703b876cc3SAlexander Shaposhnikov #else 71bbd9d610SAlexander Shaposhnikov 7216a497c6SRafael Auler // Main counters inserted by instrumentation, incremented during runtime when 7316a497c6SRafael Auler // points of interest (locations) in the program are reached. Those are direct 7416a497c6SRafael Auler // calls and direct and indirect branches (local ones). There are also counters 7516a497c6SRafael Auler // for basic block execution if they are a spanning tree leaf and need to be 7616a497c6SRafael Auler // counted in order to infer the execution count of other edges of the CFG. 7762aa74f8SRafael Auler extern uint64_t __bolt_instr_locations[]; 7816a497c6SRafael Auler extern uint32_t __bolt_num_counters; 7916a497c6SRafael Auler // Descriptions are serialized metadata about binary functions written by BOLT, 8016a497c6SRafael Auler // so we have a minimal understanding about the program structure. For a 8116a497c6SRafael Auler // reference on the exact format of this metadata, see *Description structs, 8216a497c6SRafael Auler // Location, IntrumentedNode and EntryNode. 8316a497c6SRafael Auler // Number of indirect call site descriptions 8416a497c6SRafael Auler extern uint32_t __bolt_instr_num_ind_calls; 8516a497c6SRafael Auler // Number of indirect call target descriptions 8616a497c6SRafael Auler extern uint32_t __bolt_instr_num_ind_targets; 87cc4b2fb6SRafael Auler // Number of function descriptions 88cc4b2fb6SRafael Auler extern uint32_t __bolt_instr_num_funcs; 8916a497c6SRafael Auler // Time to sleep across dumps (when we write the fdata profile to disk) 9016a497c6SRafael Auler extern uint32_t __bolt_instr_sleep_time; 91cc4b2fb6SRafael Auler // Filename to dump data to 9262aa74f8SRafael Auler extern char __bolt_instr_filename[]; 9316a497c6SRafael Auler // If true, append current PID to the fdata filename when creating it so 9416a497c6SRafael Auler // different invocations of the same program can be differentiated. 9516a497c6SRafael Auler extern bool __bolt_instr_use_pid; 9616a497c6SRafael Auler // Functions that will be used to instrument indirect calls. BOLT static pass 9716a497c6SRafael Auler // will identify indirect calls and modify them to load the address in these 9816a497c6SRafael Auler // trampolines and call this address instead. BOLT can't use direct calls to 9916a497c6SRafael Auler // our handlers because our addresses here are not known at analysis time. We 10016a497c6SRafael Auler // only support resolving dependencies from this file to the output of BOLT, 10116a497c6SRafael Auler // *not* the other way around. 10216a497c6SRafael Auler // TODO: We need better linking support to make that happen. 10316a497c6SRafael Auler extern void (*__bolt_trampoline_ind_call)(); 10416a497c6SRafael Auler extern void (*__bolt_trampoline_ind_tailcall)(); 10516a497c6SRafael Auler // Function pointers to init/fini routines in the binary, so we can resume 10616a497c6SRafael Auler // regular execution of these functions that we hooked 10716a497c6SRafael Auler extern void (*__bolt_instr_init_ptr)(); 10816a497c6SRafael Auler extern void (*__bolt_instr_fini_ptr)(); 10962aa74f8SRafael Auler 110*a0dd5b05SAlexander Shaposhnikov #endif 111*a0dd5b05SAlexander Shaposhnikov 112cc4b2fb6SRafael Auler namespace { 113cc4b2fb6SRafael Auler 114cc4b2fb6SRafael Auler /// A simple allocator that mmaps a fixed size region and manages this space 115cc4b2fb6SRafael Auler /// in a stack fashion, meaning you always deallocate the last element that 11616a497c6SRafael Auler /// was allocated. In practice, we don't need to deallocate individual elements. 11716a497c6SRafael Auler /// We monotonically increase our usage and then deallocate everything once we 11816a497c6SRafael Auler /// are done processing something. 119cc4b2fb6SRafael Auler class BumpPtrAllocator { 12016a497c6SRafael Auler /// This is written before each allocation and act as a canary to detect when 12116a497c6SRafael Auler /// a bug caused our program to cross allocation boundaries. 122cc4b2fb6SRafael Auler struct EntryMetadata { 123cc4b2fb6SRafael Auler uint64_t Magic; 124cc4b2fb6SRafael Auler uint64_t AllocSize; 125cc4b2fb6SRafael Auler }; 1269bd71615SXun Li 127cc4b2fb6SRafael Auler public: 128faaefff6SAlexander Shaposhnikov void *allocate(size_t Size) { 12916a497c6SRafael Auler Lock L(M); 130*a0dd5b05SAlexander Shaposhnikov 131cc4b2fb6SRafael Auler if (StackBase == nullptr) { 132*a0dd5b05SAlexander Shaposhnikov #if defined(__APPLE__) 133*a0dd5b05SAlexander Shaposhnikov int MAP_PRIVATE_MAP_ANONYMOUS = 0x1002; 134*a0dd5b05SAlexander Shaposhnikov #else 135*a0dd5b05SAlexander Shaposhnikov int MAP_PRIVATE_MAP_ANONYMOUS = 0x22; 136*a0dd5b05SAlexander Shaposhnikov #endif 13716a497c6SRafael Auler StackBase = reinterpret_cast<uint8_t *>( 13816a497c6SRafael Auler __mmap(0, MaxSize, 0x3 /* PROT_READ | PROT_WRITE*/, 13916a497c6SRafael Auler Shared ? 0x21 /*MAP_SHARED | MAP_ANONYMOUS*/ 140*a0dd5b05SAlexander Shaposhnikov : MAP_PRIVATE_MAP_ANONYMOUS /* MAP_PRIVATE | MAP_ANONYMOUS*/, 14116a497c6SRafael Auler -1, 0)); 142cc4b2fb6SRafael Auler StackSize = 0; 143cc4b2fb6SRafael Auler } 144*a0dd5b05SAlexander Shaposhnikov 145cc4b2fb6SRafael Auler Size = alignTo(Size + sizeof(EntryMetadata), 16); 146cc4b2fb6SRafael Auler uint8_t *AllocAddress = StackBase + StackSize + sizeof(EntryMetadata); 147cc4b2fb6SRafael Auler auto *M = reinterpret_cast<EntryMetadata *>(StackBase + StackSize); 14816a497c6SRafael Auler M->Magic = Magic; 149cc4b2fb6SRafael Auler M->AllocSize = Size; 150cc4b2fb6SRafael Auler StackSize += Size; 15116a497c6SRafael Auler assert(StackSize < MaxSize, "allocator ran out of memory"); 152cc4b2fb6SRafael Auler return AllocAddress; 153cc4b2fb6SRafael Auler } 154cc4b2fb6SRafael Auler 15516a497c6SRafael Auler #ifdef DEBUG 15616a497c6SRafael Auler /// Element-wise deallocation is only used for debugging to catch memory 15716a497c6SRafael Auler /// bugs by checking magic bytes. Ordinarily, we reset the allocator once 15816a497c6SRafael Auler /// we are done with it. Reset is done with clear(). There's no need 15916a497c6SRafael Auler /// to deallocate each element individually. 160cc4b2fb6SRafael Auler void deallocate(void *Ptr) { 16116a497c6SRafael Auler Lock L(M); 162cc4b2fb6SRafael Auler uint8_t MetadataOffset = sizeof(EntryMetadata); 163cc4b2fb6SRafael Auler auto *M = reinterpret_cast<EntryMetadata *>( 164cc4b2fb6SRafael Auler reinterpret_cast<uint8_t *>(Ptr) - MetadataOffset); 165cc4b2fb6SRafael Auler const uint8_t *StackTop = StackBase + StackSize + MetadataOffset; 166cc4b2fb6SRafael Auler // Validate size 167cc4b2fb6SRafael Auler if (Ptr != StackTop - M->AllocSize) { 16816a497c6SRafael Auler // Failed validation, check if it is a pointer returned by operator new [] 169cc4b2fb6SRafael Auler MetadataOffset += 170cc4b2fb6SRafael Auler sizeof(uint64_t); // Space for number of elements alloc'ed 171cc4b2fb6SRafael Auler M = reinterpret_cast<EntryMetadata *>(reinterpret_cast<uint8_t *>(Ptr) - 172cc4b2fb6SRafael Auler MetadataOffset); 17316a497c6SRafael Auler // Ok, it failed both checks if this assertion fails. Stop the program, we 17416a497c6SRafael Auler // have a memory bug. 175cc4b2fb6SRafael Auler assert(Ptr == StackTop - M->AllocSize, 176cc4b2fb6SRafael Auler "must deallocate the last element alloc'ed"); 177cc4b2fb6SRafael Auler } 17816a497c6SRafael Auler assert(M->Magic == Magic, "allocator magic is corrupt"); 179cc4b2fb6SRafael Auler StackSize -= M->AllocSize; 180cc4b2fb6SRafael Auler } 18116a497c6SRafael Auler #else 18216a497c6SRafael Auler void deallocate(void *) {} 18316a497c6SRafael Auler #endif 18416a497c6SRafael Auler 18516a497c6SRafael Auler void clear() { 18616a497c6SRafael Auler Lock L(M); 18716a497c6SRafael Auler StackSize = 0; 18816a497c6SRafael Auler } 18916a497c6SRafael Auler 19016a497c6SRafael Auler /// Set mmap reservation size (only relevant before first allocation) 1919bd71615SXun Li void setMaxSize(uint64_t Size) { MaxSize = Size; } 19216a497c6SRafael Auler 19316a497c6SRafael Auler /// Set mmap reservation privacy (only relevant before first allocation) 1949bd71615SXun Li void setShared(bool S) { Shared = S; } 19516a497c6SRafael Auler 19616a497c6SRafael Auler void destroy() { 19716a497c6SRafael Auler if (StackBase == nullptr) 19816a497c6SRafael Auler return; 19916a497c6SRafael Auler __munmap(StackBase, MaxSize); 20016a497c6SRafael Auler } 201cc4b2fb6SRafael Auler 202cc4b2fb6SRafael Auler private: 20316a497c6SRafael Auler static constexpr uint64_t Magic = 0x1122334455667788ull; 20416a497c6SRafael Auler uint64_t MaxSize = 0xa00000; 205cc4b2fb6SRafael Auler uint8_t *StackBase{nullptr}; 206cc4b2fb6SRafael Auler uint64_t StackSize{0}; 20716a497c6SRafael Auler bool Shared{false}; 20816a497c6SRafael Auler Mutex M; 209cc4b2fb6SRafael Auler }; 210cc4b2fb6SRafael Auler 21116a497c6SRafael Auler /// Used for allocating indirect call instrumentation counters. Initialized by 21216a497c6SRafael Auler /// __bolt_instr_setup, our initialization routine. 21316a497c6SRafael Auler BumpPtrAllocator GlobalAlloc; 214cc4b2fb6SRafael Auler } // anonymous namespace 215cc4b2fb6SRafael Auler 216cc4b2fb6SRafael Auler // User-defined placement new operators. We only use those (as opposed to 217cc4b2fb6SRafael Auler // overriding the regular operator new) so we can keep our allocator in the 218cc4b2fb6SRafael Auler // stack instead of in a data section (global). 219faaefff6SAlexander Shaposhnikov void *operator new(size_t Sz, BumpPtrAllocator &A) { return A.allocate(Sz); } 220faaefff6SAlexander Shaposhnikov void *operator new(size_t Sz, BumpPtrAllocator &A, char C) { 221cc4b2fb6SRafael Auler auto *Ptr = reinterpret_cast<char *>(A.allocate(Sz)); 222cc4b2fb6SRafael Auler memSet(Ptr, C, Sz); 223cc4b2fb6SRafael Auler return Ptr; 224cc4b2fb6SRafael Auler } 225faaefff6SAlexander Shaposhnikov void *operator new[](size_t Sz, BumpPtrAllocator &A) { 226cc4b2fb6SRafael Auler return A.allocate(Sz); 227cc4b2fb6SRafael Auler } 228faaefff6SAlexander Shaposhnikov void *operator new[](size_t Sz, BumpPtrAllocator &A, char C) { 229cc4b2fb6SRafael Auler auto *Ptr = reinterpret_cast<char *>(A.allocate(Sz)); 230cc4b2fb6SRafael Auler memSet(Ptr, C, Sz); 231cc4b2fb6SRafael Auler return Ptr; 232cc4b2fb6SRafael Auler } 233cc4b2fb6SRafael Auler // Only called during exception unwinding (useless). We must manually dealloc. 234cc4b2fb6SRafael Auler // C++ language weirdness 2359bd71615SXun Li void operator delete(void *Ptr, BumpPtrAllocator &A) { A.deallocate(Ptr); } 236cc4b2fb6SRafael Auler 237cc4b2fb6SRafael Auler namespace { 238cc4b2fb6SRafael Auler 23916a497c6SRafael Auler /// Basic key-val atom stored in our hash 24016a497c6SRafael Auler struct SimpleHashTableEntryBase { 24116a497c6SRafael Auler uint64_t Key; 24216a497c6SRafael Auler uint64_t Val; 24316a497c6SRafael Auler }; 24416a497c6SRafael Auler 24516a497c6SRafael Auler /// This hash table implementation starts by allocating a table of size 24616a497c6SRafael Auler /// InitialSize. When conflicts happen in this main table, it resolves 24716a497c6SRafael Auler /// them by chaining a new table of size IncSize. It never reallocs as our 24816a497c6SRafael Auler /// allocator doesn't support it. The key is intended to be function pointers. 24916a497c6SRafael Auler /// There's no clever hash function (it's just x mod size, size being prime). 25016a497c6SRafael Auler /// I never tuned the coefficientes in the modular equation (TODO) 25116a497c6SRafael Auler /// This is used for indirect calls (each call site has one of this, so it 25216a497c6SRafael Auler /// should have a small footprint) and for tallying call counts globally for 25316a497c6SRafael Auler /// each target to check if we missed the origin of some calls (this one is a 25416a497c6SRafael Auler /// large instantiation of this template, since it is global for all call sites) 25516a497c6SRafael Auler template <typename T = SimpleHashTableEntryBase, uint32_t InitialSize = 7, 25616a497c6SRafael Auler uint32_t IncSize = 7> 25716a497c6SRafael Auler class SimpleHashTable { 25816a497c6SRafael Auler public: 25916a497c6SRafael Auler using MapEntry = T; 26016a497c6SRafael Auler 26116a497c6SRafael Auler /// Increment by 1 the value of \p Key. If it is not in this table, it will be 26216a497c6SRafael Auler /// added to the table and its value set to 1. 26316a497c6SRafael Auler void incrementVal(uint64_t Key, BumpPtrAllocator &Alloc) { 26416a497c6SRafael Auler ++get(Key, Alloc).Val; 26516a497c6SRafael Auler } 26616a497c6SRafael Auler 26716a497c6SRafael Auler /// Basic member accessing interface. Here we pass the allocator explicitly to 26816a497c6SRafael Auler /// avoid storing a pointer to it as part of this table (remember there is one 26916a497c6SRafael Auler /// hash for each indirect call site, so we wan't to minimize our footprint). 27016a497c6SRafael Auler MapEntry &get(uint64_t Key, BumpPtrAllocator &Alloc) { 27116a497c6SRafael Auler Lock L(M); 27216a497c6SRafael Auler if (TableRoot) 27316a497c6SRafael Auler return getEntry(TableRoot, Key, Key, Alloc, 0); 27416a497c6SRafael Auler return firstAllocation(Key, Alloc); 27516a497c6SRafael Auler } 27616a497c6SRafael Auler 27716a497c6SRafael Auler /// Traverses all elements in the table 27816a497c6SRafael Auler template <typename... Args> 27916a497c6SRafael Auler void forEachElement(void (*Callback)(MapEntry &, Args...), Args... args) { 28016a497c6SRafael Auler if (!TableRoot) 28116a497c6SRafael Auler return; 28216a497c6SRafael Auler return forEachElement(Callback, InitialSize, TableRoot, args...); 28316a497c6SRafael Auler } 28416a497c6SRafael Auler 28516a497c6SRafael Auler void resetCounters(); 28616a497c6SRafael Auler 28716a497c6SRafael Auler private: 28816a497c6SRafael Auler constexpr static uint64_t VacantMarker = 0; 28916a497c6SRafael Auler constexpr static uint64_t FollowUpTableMarker = 0x8000000000000000ull; 29016a497c6SRafael Auler 29116a497c6SRafael Auler MapEntry *TableRoot{nullptr}; 29216a497c6SRafael Auler Mutex M; 29316a497c6SRafael Auler 29416a497c6SRafael Auler template <typename... Args> 29516a497c6SRafael Auler void forEachElement(void (*Callback)(MapEntry &, Args...), 29616a497c6SRafael Auler uint32_t NumEntries, MapEntry *Entries, Args... args) { 29716a497c6SRafael Auler for (int I = 0; I < NumEntries; ++I) { 29816a497c6SRafael Auler auto &Entry = Entries[I]; 29916a497c6SRafael Auler if (Entry.Key == VacantMarker) 30016a497c6SRafael Auler continue; 30116a497c6SRafael Auler if (Entry.Key & FollowUpTableMarker) { 30216a497c6SRafael Auler forEachElement(Callback, IncSize, 30316a497c6SRafael Auler reinterpret_cast<MapEntry *>(Entry.Key & 30416a497c6SRafael Auler ~FollowUpTableMarker), 30516a497c6SRafael Auler args...); 30616a497c6SRafael Auler continue; 30716a497c6SRafael Auler } 30816a497c6SRafael Auler Callback(Entry, args...); 30916a497c6SRafael Auler } 31016a497c6SRafael Auler } 31116a497c6SRafael Auler 31216a497c6SRafael Auler MapEntry &firstAllocation(uint64_t Key, BumpPtrAllocator &Alloc) { 31316a497c6SRafael Auler TableRoot = new (Alloc, 0) MapEntry[InitialSize]; 31416a497c6SRafael Auler auto &Entry = TableRoot[Key % InitialSize]; 31516a497c6SRafael Auler Entry.Key = Key; 31616a497c6SRafael Auler return Entry; 31716a497c6SRafael Auler } 31816a497c6SRafael Auler 31916a497c6SRafael Auler MapEntry &getEntry(MapEntry *Entries, uint64_t Key, uint64_t Selector, 32016a497c6SRafael Auler BumpPtrAllocator &Alloc, int CurLevel) { 32116a497c6SRafael Auler const uint32_t NumEntries = CurLevel == 0 ? InitialSize : IncSize; 32216a497c6SRafael Auler uint64_t Remainder = Selector / NumEntries; 32316a497c6SRafael Auler Selector = Selector % NumEntries; 32416a497c6SRafael Auler auto &Entry = Entries[Selector]; 32516a497c6SRafael Auler 32616a497c6SRafael Auler // A hit 32716a497c6SRafael Auler if (Entry.Key == Key) { 32816a497c6SRafael Auler return Entry; 32916a497c6SRafael Auler } 33016a497c6SRafael Auler 33116a497c6SRafael Auler // Vacant - add new entry 33216a497c6SRafael Auler if (Entry.Key == VacantMarker) { 33316a497c6SRafael Auler Entry.Key = Key; 33416a497c6SRafael Auler return Entry; 33516a497c6SRafael Auler } 33616a497c6SRafael Auler 33716a497c6SRafael Auler // Defer to the next level 33816a497c6SRafael Auler if (Entry.Key & FollowUpTableMarker) { 33916a497c6SRafael Auler return getEntry( 34016a497c6SRafael Auler reinterpret_cast<MapEntry *>(Entry.Key & ~FollowUpTableMarker), 34116a497c6SRafael Auler Key, Remainder, Alloc, CurLevel + 1); 34216a497c6SRafael Auler } 34316a497c6SRafael Auler 34416a497c6SRafael Auler // Conflict - create the next level 34516a497c6SRafael Auler MapEntry *NextLevelTbl = new (Alloc, 0) MapEntry[IncSize]; 34616a497c6SRafael Auler uint64_t CurEntrySelector = Entry.Key / InitialSize; 34716a497c6SRafael Auler for (int I = 0; I < CurLevel; ++I) 34816a497c6SRafael Auler CurEntrySelector /= IncSize; 34916a497c6SRafael Auler CurEntrySelector = CurEntrySelector % IncSize; 35016a497c6SRafael Auler NextLevelTbl[CurEntrySelector] = Entry; 35116a497c6SRafael Auler Entry.Key = reinterpret_cast<uint64_t>(NextLevelTbl) | FollowUpTableMarker; 35216a497c6SRafael Auler return getEntry(NextLevelTbl, Key, Remainder, Alloc, CurLevel + 1); 35316a497c6SRafael Auler } 35416a497c6SRafael Auler }; 35516a497c6SRafael Auler 35616a497c6SRafael Auler template <typename T> void resetIndCallCounter(T &Entry) { 35716a497c6SRafael Auler Entry.Val = 0; 35816a497c6SRafael Auler } 35916a497c6SRafael Auler 36016a497c6SRafael Auler template <typename T, uint32_t X, uint32_t Y> 36116a497c6SRafael Auler void SimpleHashTable<T, X, Y>::resetCounters() { 36216a497c6SRafael Auler Lock L(M); 36316a497c6SRafael Auler forEachElement(resetIndCallCounter); 36416a497c6SRafael Auler } 36516a497c6SRafael Auler 36616a497c6SRafael Auler /// Represents a hash table mapping a function target address to its counter. 36716a497c6SRafael Auler using IndirectCallHashTable = SimpleHashTable<>; 36816a497c6SRafael Auler 36916a497c6SRafael Auler /// Initialize with number 1 instead of 0 so we don't go into .bss. This is the 37016a497c6SRafael Auler /// global array of all hash tables storing indirect call destinations happening 37116a497c6SRafael Auler /// during runtime, one table per call site. 37216a497c6SRafael Auler IndirectCallHashTable *GlobalIndCallCounters{ 37316a497c6SRafael Auler reinterpret_cast<IndirectCallHashTable *>(1)}; 37416a497c6SRafael Auler 37516a497c6SRafael Auler /// Don't allow reentrancy in the fdata writing phase - only one thread writes 37616a497c6SRafael Auler /// it 37716a497c6SRafael Auler Mutex *GlobalWriteProfileMutex{reinterpret_cast<Mutex *>(1)}; 37816a497c6SRafael Auler 37916a497c6SRafael Auler /// Store number of calls in additional to target address (Key) and frequency 38016a497c6SRafael Auler /// as perceived by the basic block counter (Val). 38116a497c6SRafael Auler struct CallFlowEntryBase : public SimpleHashTableEntryBase { 38216a497c6SRafael Auler uint64_t Calls; 38316a497c6SRafael Auler }; 38416a497c6SRafael Auler 38516a497c6SRafael Auler using CallFlowHashTableBase = SimpleHashTable<CallFlowEntryBase, 11939, 233>; 38616a497c6SRafael Auler 38716a497c6SRafael Auler /// This is a large table indexing all possible call targets (indirect and 38816a497c6SRafael Auler /// direct ones). The goal is to find mismatches between number of calls (for 38916a497c6SRafael Auler /// those calls we were able to track) and the entry basic block counter of the 39016a497c6SRafael Auler /// callee. In most cases, these two should be equal. If not, there are two 39116a497c6SRafael Auler /// possible scenarios here: 39216a497c6SRafael Auler /// 39316a497c6SRafael Auler /// * Entry BB has higher frequency than all known calls to this function. 39416a497c6SRafael Auler /// In this case, we have dynamic library code or any uninstrumented code 39516a497c6SRafael Auler /// calling this function. We will write the profile for these untracked 39616a497c6SRafael Auler /// calls as having source "0 [unknown] 0" in the fdata file. 39716a497c6SRafael Auler /// 39816a497c6SRafael Auler /// * Number of known calls is higher than the frequency of entry BB 39916a497c6SRafael Auler /// This only happens when there is no counter for the entry BB / callee 40016a497c6SRafael Auler /// function is not simple (in BOLT terms). We don't do anything special 40116a497c6SRafael Auler /// here and just ignore those (we still report all calls to the non-simple 40216a497c6SRafael Auler /// function, though). 40316a497c6SRafael Auler /// 40416a497c6SRafael Auler class CallFlowHashTable : public CallFlowHashTableBase { 40516a497c6SRafael Auler public: 40616a497c6SRafael Auler CallFlowHashTable(BumpPtrAllocator &Alloc) : Alloc(Alloc) {} 40716a497c6SRafael Auler 40816a497c6SRafael Auler MapEntry &get(uint64_t Key) { return CallFlowHashTableBase::get(Key, Alloc); } 40916a497c6SRafael Auler 41016a497c6SRafael Auler private: 41116a497c6SRafael Auler // Different than the hash table for indirect call targets, we do store the 41216a497c6SRafael Auler // allocator here since there is only one call flow hash and space overhead 41316a497c6SRafael Auler // is negligible. 41416a497c6SRafael Auler BumpPtrAllocator &Alloc; 41516a497c6SRafael Auler }; 41616a497c6SRafael Auler 41716a497c6SRafael Auler /// 41816a497c6SRafael Auler /// Description metadata emitted by BOLT to describe the program - refer to 41916a497c6SRafael Auler /// Passes/Instrumentation.cpp - Instrumentation::emitTablesAsELFNote() 42016a497c6SRafael Auler /// 42116a497c6SRafael Auler struct Location { 42216a497c6SRafael Auler uint32_t FunctionName; 42316a497c6SRafael Auler uint32_t Offset; 42416a497c6SRafael Auler }; 42516a497c6SRafael Auler 42616a497c6SRafael Auler struct CallDescription { 42716a497c6SRafael Auler Location From; 42816a497c6SRafael Auler uint32_t FromNode; 42916a497c6SRafael Auler Location To; 43016a497c6SRafael Auler uint32_t Counter; 43116a497c6SRafael Auler uint64_t TargetAddress; 43216a497c6SRafael Auler }; 43316a497c6SRafael Auler 43416a497c6SRafael Auler using IndCallDescription = Location; 43516a497c6SRafael Auler 43616a497c6SRafael Auler struct IndCallTargetDescription { 43716a497c6SRafael Auler Location Loc; 43816a497c6SRafael Auler uint64_t Address; 43916a497c6SRafael Auler }; 44016a497c6SRafael Auler 44116a497c6SRafael Auler struct EdgeDescription { 44216a497c6SRafael Auler Location From; 44316a497c6SRafael Auler uint32_t FromNode; 44416a497c6SRafael Auler Location To; 44516a497c6SRafael Auler uint32_t ToNode; 44616a497c6SRafael Auler uint32_t Counter; 44716a497c6SRafael Auler }; 44816a497c6SRafael Auler 44916a497c6SRafael Auler struct InstrumentedNode { 45016a497c6SRafael Auler uint32_t Node; 45116a497c6SRafael Auler uint32_t Counter; 45216a497c6SRafael Auler }; 45316a497c6SRafael Auler 45416a497c6SRafael Auler struct EntryNode { 45516a497c6SRafael Auler uint64_t Node; 45616a497c6SRafael Auler uint64_t Address; 45716a497c6SRafael Auler }; 45816a497c6SRafael Auler 45916a497c6SRafael Auler struct FunctionDescription { 46016a497c6SRafael Auler uint32_t NumLeafNodes; 46116a497c6SRafael Auler const InstrumentedNode *LeafNodes; 46216a497c6SRafael Auler uint32_t NumEdges; 46316a497c6SRafael Auler const EdgeDescription *Edges; 46416a497c6SRafael Auler uint32_t NumCalls; 46516a497c6SRafael Auler const CallDescription *Calls; 46616a497c6SRafael Auler uint32_t NumEntryNodes; 46716a497c6SRafael Auler const EntryNode *EntryNodes; 46816a497c6SRafael Auler 46916a497c6SRafael Auler /// Constructor will parse the serialized function metadata written by BOLT 47016a497c6SRafael Auler FunctionDescription(const uint8_t *FuncDesc); 47116a497c6SRafael Auler 47216a497c6SRafael Auler uint64_t getSize() const { 47316a497c6SRafael Auler return 16 + NumLeafNodes * sizeof(InstrumentedNode) + 47416a497c6SRafael Auler NumEdges * sizeof(EdgeDescription) + 47516a497c6SRafael Auler NumCalls * sizeof(CallDescription) + 47616a497c6SRafael Auler NumEntryNodes * sizeof(EntryNode); 47716a497c6SRafael Auler } 47816a497c6SRafael Auler }; 47916a497c6SRafael Auler 48016a497c6SRafael Auler /// The context is created when the fdata profile needs to be written to disk 48116a497c6SRafael Auler /// and we need to interpret our runtime counters. It contains pointers to the 48216a497c6SRafael Auler /// mmaped binary (only the BOLT written metadata section). Deserialization 48316a497c6SRafael Auler /// should be straightforward as most data is POD or an array of POD elements. 48416a497c6SRafael Auler /// This metadata is used to reconstruct function CFGs. 48516a497c6SRafael Auler struct ProfileWriterContext { 48616a497c6SRafael Auler IndCallDescription *IndCallDescriptions; 48716a497c6SRafael Auler IndCallTargetDescription *IndCallTargets; 48816a497c6SRafael Auler uint8_t *FuncDescriptions; 48916a497c6SRafael Auler char *Strings; // String table with function names used in this binary 49016a497c6SRafael Auler int FileDesc; // File descriptor for the file on disk backing this 49116a497c6SRafael Auler // information in memory via mmap 49216a497c6SRafael Auler void *MMapPtr; // The mmap ptr 49316a497c6SRafael Auler int MMapSize; // The mmap size 49416a497c6SRafael Auler 49516a497c6SRafael Auler /// Hash table storing all possible call destinations to detect untracked 49616a497c6SRafael Auler /// calls and correctly report them as [unknown] in output fdata. 49716a497c6SRafael Auler CallFlowHashTable *CallFlowTable; 49816a497c6SRafael Auler 49916a497c6SRafael Auler /// Lookup the sorted indirect call target vector to fetch function name and 50016a497c6SRafael Auler /// offset for an arbitrary function pointer. 50116a497c6SRafael Auler const IndCallTargetDescription *lookupIndCallTarget(uint64_t Target) const; 50216a497c6SRafael Auler }; 50316a497c6SRafael Auler 50416a497c6SRafael Auler /// Perform a string comparison and returns zero if Str1 matches Str2. Compares 50516a497c6SRafael Auler /// at most Size characters. 506cc4b2fb6SRafael Auler int compareStr(const char *Str1, const char *Str2, int Size) { 507821480d2SRafael Auler while (*Str1 == *Str2) { 508821480d2SRafael Auler if (*Str1 == '\0' || --Size == 0) 509821480d2SRafael Auler return 0; 510821480d2SRafael Auler ++Str1; 511821480d2SRafael Auler ++Str2; 512821480d2SRafael Auler } 513821480d2SRafael Auler return 1; 514821480d2SRafael Auler } 515821480d2SRafael Auler 51616a497c6SRafael Auler /// Output Location to the fdata file 51716a497c6SRafael Auler char *serializeLoc(const ProfileWriterContext &Ctx, char *OutBuf, 518cc4b2fb6SRafael Auler const Location Loc, uint32_t BufSize) { 519821480d2SRafael Auler // fdata location format: Type Name Offset 520821480d2SRafael Auler // Type 1 - regular symbol 521821480d2SRafael Auler OutBuf = strCopy(OutBuf, "1 "); 52216a497c6SRafael Auler const char *Str = Ctx.Strings + Loc.FunctionName; 523cc4b2fb6SRafael Auler uint32_t Size = 25; 52462aa74f8SRafael Auler while (*Str) { 52562aa74f8SRafael Auler *OutBuf++ = *Str++; 526cc4b2fb6SRafael Auler if (++Size >= BufSize) 527cc4b2fb6SRafael Auler break; 52862aa74f8SRafael Auler } 529cc4b2fb6SRafael Auler assert(!*Str, "buffer overflow, function name too large"); 53062aa74f8SRafael Auler *OutBuf++ = ' '; 531821480d2SRafael Auler OutBuf = intToStr(OutBuf, Loc.Offset, 16); 53262aa74f8SRafael Auler *OutBuf++ = ' '; 53362aa74f8SRafael Auler return OutBuf; 53462aa74f8SRafael Auler } 53562aa74f8SRafael Auler 53616a497c6SRafael Auler /// Read and deserialize a function description written by BOLT. \p FuncDesc 53716a497c6SRafael Auler /// points at the beginning of the function metadata structure in the file. 53816a497c6SRafael Auler /// See Instrumentation::emitTablesAsELFNote() 53916a497c6SRafael Auler FunctionDescription::FunctionDescription(const uint8_t *FuncDesc) { 54016a497c6SRafael Auler NumLeafNodes = *reinterpret_cast<const uint32_t *>(FuncDesc); 54116a497c6SRafael Auler DEBUG(reportNumber("NumLeafNodes = ", NumLeafNodes, 10)); 54216a497c6SRafael Auler LeafNodes = reinterpret_cast<const InstrumentedNode *>(FuncDesc + 4); 54316a497c6SRafael Auler 54416a497c6SRafael Auler NumEdges = *reinterpret_cast<const uint32_t *>( 54516a497c6SRafael Auler FuncDesc + 4 + NumLeafNodes * sizeof(InstrumentedNode)); 54616a497c6SRafael Auler DEBUG(reportNumber("NumEdges = ", NumEdges, 10)); 54716a497c6SRafael Auler Edges = reinterpret_cast<const EdgeDescription *>( 54816a497c6SRafael Auler FuncDesc + 8 + NumLeafNodes * sizeof(InstrumentedNode)); 54916a497c6SRafael Auler 55016a497c6SRafael Auler NumCalls = *reinterpret_cast<const uint32_t *>( 55116a497c6SRafael Auler FuncDesc + 8 + NumLeafNodes * sizeof(InstrumentedNode) + 55216a497c6SRafael Auler NumEdges * sizeof(EdgeDescription)); 55316a497c6SRafael Auler DEBUG(reportNumber("NumCalls = ", NumCalls, 10)); 55416a497c6SRafael Auler Calls = reinterpret_cast<const CallDescription *>( 55516a497c6SRafael Auler FuncDesc + 12 + NumLeafNodes * sizeof(InstrumentedNode) + 55616a497c6SRafael Auler NumEdges * sizeof(EdgeDescription)); 55716a497c6SRafael Auler NumEntryNodes = *reinterpret_cast<const uint32_t *>( 55816a497c6SRafael Auler FuncDesc + 12 + NumLeafNodes * sizeof(InstrumentedNode) + 55916a497c6SRafael Auler NumEdges * sizeof(EdgeDescription) + NumCalls * sizeof(CallDescription)); 56016a497c6SRafael Auler DEBUG(reportNumber("NumEntryNodes = ", NumEntryNodes, 10)); 56116a497c6SRafael Auler EntryNodes = reinterpret_cast<const EntryNode *>( 56216a497c6SRafael Auler FuncDesc + 16 + NumLeafNodes * sizeof(InstrumentedNode) + 56316a497c6SRafael Auler NumEdges * sizeof(EdgeDescription) + NumCalls * sizeof(CallDescription)); 56416a497c6SRafael Auler } 56516a497c6SRafael Auler 56616a497c6SRafael Auler /// Read and mmap descriptions written by BOLT from the executable's notes 56716a497c6SRafael Auler /// section 568*a0dd5b05SAlexander Shaposhnikov #if defined(HAVE_ELF_H) and !defined(__APPLE__) 56916a497c6SRafael Auler ProfileWriterContext readDescriptions() { 57016a497c6SRafael Auler ProfileWriterContext Result; 571821480d2SRafael Auler uint64_t FD = __open("/proc/self/exe", 572821480d2SRafael Auler /*flags=*/0 /*O_RDONLY*/, 573821480d2SRafael Auler /*mode=*/0666); 574cc4b2fb6SRafael Auler assert(static_cast<int64_t>(FD) > 0, "Failed to open /proc/self/exe"); 575821480d2SRafael Auler Result.FileDesc = FD; 576821480d2SRafael Auler 577821480d2SRafael Auler // mmap our binary to memory 578821480d2SRafael Auler uint64_t Size = __lseek(FD, 0, 2 /*SEEK_END*/); 579821480d2SRafael Auler uint8_t *BinContents = reinterpret_cast<uint8_t *>( 580821480d2SRafael Auler __mmap(0, Size, 0x1 /* PROT_READ*/, 0x2 /* MAP_PRIVATE*/, FD, 0)); 581821480d2SRafael Auler Result.MMapPtr = BinContents; 582821480d2SRafael Auler Result.MMapSize = Size; 583821480d2SRafael Auler Elf64_Ehdr *Hdr = reinterpret_cast<Elf64_Ehdr *>(BinContents); 584821480d2SRafael Auler Elf64_Shdr *Shdr = reinterpret_cast<Elf64_Shdr *>(BinContents + Hdr->e_shoff); 585821480d2SRafael Auler Elf64_Shdr *StringTblHeader = reinterpret_cast<Elf64_Shdr *>( 586821480d2SRafael Auler BinContents + Hdr->e_shoff + Hdr->e_shstrndx * Hdr->e_shentsize); 587821480d2SRafael Auler 588821480d2SRafael Auler // Find .bolt.instr.tables with the data we need and set pointers to it 589821480d2SRafael Auler for (int I = 0; I < Hdr->e_shnum; ++I) { 590821480d2SRafael Auler char *SecName = reinterpret_cast<char *>( 591821480d2SRafael Auler BinContents + StringTblHeader->sh_offset + Shdr->sh_name); 592821480d2SRafael Auler if (compareStr(SecName, ".bolt.instr.tables", 64) != 0) { 593821480d2SRafael Auler Shdr = reinterpret_cast<Elf64_Shdr *>(BinContents + Hdr->e_shoff + 594821480d2SRafael Auler (I + 1) * Hdr->e_shentsize); 595821480d2SRafael Auler continue; 596821480d2SRafael Auler } 597821480d2SRafael Auler // Actual contents of the ELF note start after offset 20 decimal: 598821480d2SRafael Auler // Offset 0: Producer name size (4 bytes) 599821480d2SRafael Auler // Offset 4: Contents size (4 bytes) 600821480d2SRafael Auler // Offset 8: Note type (4 bytes) 601821480d2SRafael Auler // Offset 12: Producer name (BOLT\0) (5 bytes + align to 4-byte boundary) 602821480d2SRafael Auler // Offset 20: Contents 60316a497c6SRafael Auler uint32_t IndCallDescSize = 604cc4b2fb6SRafael Auler *reinterpret_cast<uint32_t *>(BinContents + Shdr->sh_offset + 20); 60516a497c6SRafael Auler uint32_t IndCallTargetDescSize = *reinterpret_cast<uint32_t *>( 60616a497c6SRafael Auler BinContents + Shdr->sh_offset + 24 + IndCallDescSize); 60716a497c6SRafael Auler uint32_t FuncDescSize = 60816a497c6SRafael Auler *reinterpret_cast<uint32_t *>(BinContents + Shdr->sh_offset + 28 + 60916a497c6SRafael Auler IndCallDescSize + IndCallTargetDescSize); 61016a497c6SRafael Auler Result.IndCallDescriptions = reinterpret_cast<IndCallDescription *>( 61116a497c6SRafael Auler BinContents + Shdr->sh_offset + 24); 61216a497c6SRafael Auler Result.IndCallTargets = reinterpret_cast<IndCallTargetDescription *>( 61316a497c6SRafael Auler BinContents + Shdr->sh_offset + 28 + IndCallDescSize); 61416a497c6SRafael Auler Result.FuncDescriptions = BinContents + Shdr->sh_offset + 32 + 61516a497c6SRafael Auler IndCallDescSize + IndCallTargetDescSize; 61616a497c6SRafael Auler Result.Strings = reinterpret_cast<char *>( 61716a497c6SRafael Auler BinContents + Shdr->sh_offset + 32 + IndCallDescSize + 61816a497c6SRafael Auler IndCallTargetDescSize + FuncDescSize); 619821480d2SRafael Auler return Result; 620821480d2SRafael Auler } 621821480d2SRafael Auler const char ErrMsg[] = 622821480d2SRafael Auler "BOLT instrumentation runtime error: could not find section " 623821480d2SRafael Auler ".bolt.instr.tables\n"; 624821480d2SRafael Auler reportError(ErrMsg, sizeof(ErrMsg)); 625821480d2SRafael Auler return Result; 626821480d2SRafael Auler } 627*a0dd5b05SAlexander Shaposhnikov 628ba31344fSRafael Auler #else 629*a0dd5b05SAlexander Shaposhnikov 63016a497c6SRafael Auler ProfileWriterContext readDescriptions() { 63116a497c6SRafael Auler ProfileWriterContext Result; 632*a0dd5b05SAlexander Shaposhnikov uint8_t *Tables = _bolt_instr_tables_getter(); 633*a0dd5b05SAlexander Shaposhnikov uint32_t IndCallDescSize = *reinterpret_cast<uint32_t *>(Tables); 634*a0dd5b05SAlexander Shaposhnikov uint32_t IndCallTargetDescSize = 635*a0dd5b05SAlexander Shaposhnikov *reinterpret_cast<uint32_t *>(Tables + 4 + IndCallDescSize); 636*a0dd5b05SAlexander Shaposhnikov uint32_t FuncDescSize = *reinterpret_cast<uint32_t *>( 637*a0dd5b05SAlexander Shaposhnikov Tables + 8 + IndCallDescSize + IndCallTargetDescSize); 638*a0dd5b05SAlexander Shaposhnikov Result.IndCallDescriptions = 639*a0dd5b05SAlexander Shaposhnikov reinterpret_cast<IndCallDescription *>(Tables + 4); 640*a0dd5b05SAlexander Shaposhnikov Result.IndCallTargets = reinterpret_cast<IndCallTargetDescription *>( 641*a0dd5b05SAlexander Shaposhnikov Tables + 8 + IndCallDescSize); 642*a0dd5b05SAlexander Shaposhnikov Result.FuncDescriptions = 643*a0dd5b05SAlexander Shaposhnikov Tables + 12 + IndCallDescSize + IndCallTargetDescSize; 644*a0dd5b05SAlexander Shaposhnikov Result.Strings = reinterpret_cast<char *>( 645*a0dd5b05SAlexander Shaposhnikov Tables + 12 + IndCallDescSize + IndCallTargetDescSize + FuncDescSize); 646ba31344fSRafael Auler return Result; 647ba31344fSRafael Auler } 648*a0dd5b05SAlexander Shaposhnikov 649ba31344fSRafael Auler #endif 650821480d2SRafael Auler 651*a0dd5b05SAlexander Shaposhnikov #if !defined(__APPLE__) 65216a497c6SRafael Auler /// Debug by printing overall metadata global numbers to check it is sane 65316a497c6SRafael Auler void printStats(const ProfileWriterContext &Ctx) { 654cc4b2fb6SRafael Auler char StatMsg[BufSize]; 655cc4b2fb6SRafael Auler char *StatPtr = StatMsg; 65616a497c6SRafael Auler StatPtr = 65716a497c6SRafael Auler strCopy(StatPtr, 65816a497c6SRafael Auler "\nBOLT INSTRUMENTATION RUNTIME STATISTICS\n\nIndCallDescSize: "); 659cc4b2fb6SRafael Auler StatPtr = intToStr(StatPtr, 66016a497c6SRafael Auler Ctx.FuncDescriptions - 66116a497c6SRafael Auler reinterpret_cast<uint8_t *>(Ctx.IndCallDescriptions), 662cc4b2fb6SRafael Auler 10); 663cc4b2fb6SRafael Auler StatPtr = strCopy(StatPtr, "\nFuncDescSize: "); 664cc4b2fb6SRafael Auler StatPtr = intToStr( 665cc4b2fb6SRafael Auler StatPtr, 66616a497c6SRafael Auler reinterpret_cast<uint8_t *>(Ctx.Strings) - Ctx.FuncDescriptions, 10); 66716a497c6SRafael Auler StatPtr = strCopy(StatPtr, "\n__bolt_instr_num_ind_calls: "); 66816a497c6SRafael Auler StatPtr = intToStr(StatPtr, __bolt_instr_num_ind_calls, 10); 669cc4b2fb6SRafael Auler StatPtr = strCopy(StatPtr, "\n__bolt_instr_num_funcs: "); 670cc4b2fb6SRafael Auler StatPtr = intToStr(StatPtr, __bolt_instr_num_funcs, 10); 671cc4b2fb6SRafael Auler StatPtr = strCopy(StatPtr, "\n"); 672cc4b2fb6SRafael Auler __write(2, StatMsg, StatPtr - StatMsg); 673cc4b2fb6SRafael Auler } 674*a0dd5b05SAlexander Shaposhnikov #endif 675*a0dd5b05SAlexander Shaposhnikov 676cc4b2fb6SRafael Auler 677cc4b2fb6SRafael Auler /// This is part of a simple CFG representation in memory, where we store 678cc4b2fb6SRafael Auler /// a dynamically sized array of input and output edges per node, and store 679cc4b2fb6SRafael Auler /// a dynamically sized array of nodes per graph. We also store the spanning 680cc4b2fb6SRafael Auler /// tree edges for that CFG in a separate array of nodes in 681cc4b2fb6SRafael Auler /// \p SpanningTreeNodes, while the regular nodes live in \p CFGNodes. 682cc4b2fb6SRafael Auler struct Edge { 683cc4b2fb6SRafael Auler uint32_t Node; // Index in nodes array regarding the destination of this edge 684cc4b2fb6SRafael Auler uint32_t ID; // Edge index in an array comprising all edges of the graph 685cc4b2fb6SRafael Auler }; 686cc4b2fb6SRafael Auler 687cc4b2fb6SRafael Auler /// A regular graph node or a spanning tree node 688cc4b2fb6SRafael Auler struct Node { 689cc4b2fb6SRafael Auler uint32_t NumInEdges{0}; // Input edge count used to size InEdge 690cc4b2fb6SRafael Auler uint32_t NumOutEdges{0}; // Output edge count used to size OutEdges 691cc4b2fb6SRafael Auler Edge *InEdges{nullptr}; // Created and managed by \p Graph 692cc4b2fb6SRafael Auler Edge *OutEdges{nullptr}; // ditto 693cc4b2fb6SRafael Auler }; 694cc4b2fb6SRafael Auler 695cc4b2fb6SRafael Auler /// Main class for CFG representation in memory. Manages object creation and 696cc4b2fb6SRafael Auler /// destruction, populates an array of CFG nodes as well as corresponding 697cc4b2fb6SRafael Auler /// spanning tree nodes. 698cc4b2fb6SRafael Auler struct Graph { 699cc4b2fb6SRafael Auler uint32_t NumNodes; 700cc4b2fb6SRafael Auler Node *CFGNodes; 701cc4b2fb6SRafael Auler Node *SpanningTreeNodes; 70216a497c6SRafael Auler uint64_t *EdgeFreqs; 70316a497c6SRafael Auler uint64_t *CallFreqs; 704cc4b2fb6SRafael Auler BumpPtrAllocator &Alloc; 70516a497c6SRafael Auler const FunctionDescription &D; 706cc4b2fb6SRafael Auler 70716a497c6SRafael Auler /// Reads a list of edges from function description \p D and builds 708cc4b2fb6SRafael Auler /// the graph from it. Allocates several internal dynamic structures that are 70916a497c6SRafael Auler /// later destroyed by ~Graph() and uses \p Alloc. D.LeafNodes contain all 710cc4b2fb6SRafael Auler /// spanning tree leaf nodes descriptions (their counters). They are the seed 711cc4b2fb6SRafael Auler /// used to compute the rest of the missing edge counts in a bottom-up 712cc4b2fb6SRafael Auler /// traversal of the spanning tree. 71316a497c6SRafael Auler Graph(BumpPtrAllocator &Alloc, const FunctionDescription &D, 71416a497c6SRafael Auler const uint64_t *Counters, ProfileWriterContext &Ctx); 715cc4b2fb6SRafael Auler ~Graph(); 716cc4b2fb6SRafael Auler void dump() const; 71716a497c6SRafael Auler 71816a497c6SRafael Auler private: 71916a497c6SRafael Auler void computeEdgeFrequencies(const uint64_t *Counters, 72016a497c6SRafael Auler ProfileWriterContext &Ctx); 72116a497c6SRafael Auler void dumpEdgeFreqs() const; 722cc4b2fb6SRafael Auler }; 723cc4b2fb6SRafael Auler 72416a497c6SRafael Auler Graph::Graph(BumpPtrAllocator &Alloc, const FunctionDescription &D, 72516a497c6SRafael Auler const uint64_t *Counters, ProfileWriterContext &Ctx) 72616a497c6SRafael Auler : Alloc(Alloc), D(D) { 727cc4b2fb6SRafael Auler DEBUG(reportNumber("G = 0x", (uint64_t)this, 16)); 728cc4b2fb6SRafael Auler // First pass to determine number of nodes 72916a497c6SRafael Auler int32_t MaxNodes = -1; 73016a497c6SRafael Auler CallFreqs = nullptr; 73116a497c6SRafael Auler EdgeFreqs = nullptr; 73216a497c6SRafael Auler for (int I = 0; I < D.NumEdges; ++I) { 73316a497c6SRafael Auler if (static_cast<int32_t>(D.Edges[I].FromNode) > MaxNodes) 73416a497c6SRafael Auler MaxNodes = D.Edges[I].FromNode; 73516a497c6SRafael Auler if (static_cast<int32_t>(D.Edges[I].ToNode) > MaxNodes) 73616a497c6SRafael Auler MaxNodes = D.Edges[I].ToNode; 737cc4b2fb6SRafael Auler } 738*a0dd5b05SAlexander Shaposhnikov 73916a497c6SRafael Auler for (int I = 0; I < D.NumLeafNodes; ++I) { 74016a497c6SRafael Auler if (static_cast<int32_t>(D.LeafNodes[I].Node) > MaxNodes) 74116a497c6SRafael Auler MaxNodes = D.LeafNodes[I].Node; 742cc4b2fb6SRafael Auler } 74316a497c6SRafael Auler for (int I = 0; I < D.NumCalls; ++I) { 74416a497c6SRafael Auler if (static_cast<int32_t>(D.Calls[I].FromNode) > MaxNodes) 74516a497c6SRafael Auler MaxNodes = D.Calls[I].FromNode; 74616a497c6SRafael Auler } 74716a497c6SRafael Auler // No nodes? Nothing to do 74816a497c6SRafael Auler if (MaxNodes < 0) { 74916a497c6SRafael Auler DEBUG(report("No nodes!\n")); 750cc4b2fb6SRafael Auler CFGNodes = nullptr; 751cc4b2fb6SRafael Auler SpanningTreeNodes = nullptr; 752cc4b2fb6SRafael Auler NumNodes = 0; 753cc4b2fb6SRafael Auler return; 754cc4b2fb6SRafael Auler } 755cc4b2fb6SRafael Auler ++MaxNodes; 756cc4b2fb6SRafael Auler DEBUG(reportNumber("NumNodes = ", MaxNodes, 10)); 75716a497c6SRafael Auler NumNodes = static_cast<uint32_t>(MaxNodes); 758cc4b2fb6SRafael Auler 759cc4b2fb6SRafael Auler // Initial allocations 760cc4b2fb6SRafael Auler CFGNodes = new (Alloc) Node[MaxNodes]; 761*a0dd5b05SAlexander Shaposhnikov 762cc4b2fb6SRafael Auler DEBUG(reportNumber("G->CFGNodes = 0x", (uint64_t)CFGNodes, 16)); 763cc4b2fb6SRafael Auler SpanningTreeNodes = new (Alloc) Node[MaxNodes]; 764cc4b2fb6SRafael Auler DEBUG(reportNumber("G->SpanningTreeNodes = 0x", 765cc4b2fb6SRafael Auler (uint64_t)SpanningTreeNodes, 16)); 766cc4b2fb6SRafael Auler 767cc4b2fb6SRafael Auler // Figure out how much to allocate to each vector (in/out edge sets) 76816a497c6SRafael Auler for (int I = 0; I < D.NumEdges; ++I) { 76916a497c6SRafael Auler CFGNodes[D.Edges[I].FromNode].NumOutEdges++; 77016a497c6SRafael Auler CFGNodes[D.Edges[I].ToNode].NumInEdges++; 77116a497c6SRafael Auler if (D.Edges[I].Counter != 0xffffffff) 772cc4b2fb6SRafael Auler continue; 773cc4b2fb6SRafael Auler 77416a497c6SRafael Auler SpanningTreeNodes[D.Edges[I].FromNode].NumOutEdges++; 77516a497c6SRafael Auler SpanningTreeNodes[D.Edges[I].ToNode].NumInEdges++; 776cc4b2fb6SRafael Auler } 777cc4b2fb6SRafael Auler 778cc4b2fb6SRafael Auler // Allocate in/out edge sets 779cc4b2fb6SRafael Auler for (int I = 0; I < MaxNodes; ++I) { 780cc4b2fb6SRafael Auler if (CFGNodes[I].NumInEdges > 0) 781cc4b2fb6SRafael Auler CFGNodes[I].InEdges = new (Alloc) Edge[CFGNodes[I].NumInEdges]; 782cc4b2fb6SRafael Auler if (CFGNodes[I].NumOutEdges > 0) 783cc4b2fb6SRafael Auler CFGNodes[I].OutEdges = new (Alloc) Edge[CFGNodes[I].NumOutEdges]; 784cc4b2fb6SRafael Auler if (SpanningTreeNodes[I].NumInEdges > 0) 785cc4b2fb6SRafael Auler SpanningTreeNodes[I].InEdges = 786cc4b2fb6SRafael Auler new (Alloc) Edge[SpanningTreeNodes[I].NumInEdges]; 787cc4b2fb6SRafael Auler if (SpanningTreeNodes[I].NumOutEdges > 0) 788cc4b2fb6SRafael Auler SpanningTreeNodes[I].OutEdges = 789cc4b2fb6SRafael Auler new (Alloc) Edge[SpanningTreeNodes[I].NumOutEdges]; 790cc4b2fb6SRafael Auler CFGNodes[I].NumInEdges = 0; 791cc4b2fb6SRafael Auler CFGNodes[I].NumOutEdges = 0; 792cc4b2fb6SRafael Auler SpanningTreeNodes[I].NumInEdges = 0; 793cc4b2fb6SRafael Auler SpanningTreeNodes[I].NumOutEdges = 0; 794cc4b2fb6SRafael Auler } 795cc4b2fb6SRafael Auler 796cc4b2fb6SRafael Auler // Fill in/out edge sets 79716a497c6SRafael Auler for (int I = 0; I < D.NumEdges; ++I) { 79816a497c6SRafael Auler const uint32_t Src = D.Edges[I].FromNode; 79916a497c6SRafael Auler const uint32_t Dst = D.Edges[I].ToNode; 800cc4b2fb6SRafael Auler Edge *E = &CFGNodes[Src].OutEdges[CFGNodes[Src].NumOutEdges++]; 801cc4b2fb6SRafael Auler E->Node = Dst; 802cc4b2fb6SRafael Auler E->ID = I; 803cc4b2fb6SRafael Auler 804cc4b2fb6SRafael Auler E = &CFGNodes[Dst].InEdges[CFGNodes[Dst].NumInEdges++]; 805cc4b2fb6SRafael Auler E->Node = Src; 806cc4b2fb6SRafael Auler E->ID = I; 807cc4b2fb6SRafael Auler 80816a497c6SRafael Auler if (D.Edges[I].Counter != 0xffffffff) 809cc4b2fb6SRafael Auler continue; 810cc4b2fb6SRafael Auler 811cc4b2fb6SRafael Auler E = &SpanningTreeNodes[Src] 812cc4b2fb6SRafael Auler .OutEdges[SpanningTreeNodes[Src].NumOutEdges++]; 813cc4b2fb6SRafael Auler E->Node = Dst; 814cc4b2fb6SRafael Auler E->ID = I; 815cc4b2fb6SRafael Auler 816cc4b2fb6SRafael Auler E = &SpanningTreeNodes[Dst] 817cc4b2fb6SRafael Auler .InEdges[SpanningTreeNodes[Dst].NumInEdges++]; 818cc4b2fb6SRafael Auler E->Node = Src; 819cc4b2fb6SRafael Auler E->ID = I; 820cc4b2fb6SRafael Auler } 82116a497c6SRafael Auler 82216a497c6SRafael Auler computeEdgeFrequencies(Counters, Ctx); 823cc4b2fb6SRafael Auler } 824cc4b2fb6SRafael Auler 825cc4b2fb6SRafael Auler Graph::~Graph() { 82616a497c6SRafael Auler if (CallFreqs) 82716a497c6SRafael Auler Alloc.deallocate(CallFreqs); 82816a497c6SRafael Auler if (EdgeFreqs) 82916a497c6SRafael Auler Alloc.deallocate(EdgeFreqs); 830cc4b2fb6SRafael Auler for (int I = NumNodes - 1; I >= 0; --I) { 831cc4b2fb6SRafael Auler if (SpanningTreeNodes[I].OutEdges) 832cc4b2fb6SRafael Auler Alloc.deallocate(SpanningTreeNodes[I].OutEdges); 833cc4b2fb6SRafael Auler if (SpanningTreeNodes[I].InEdges) 834cc4b2fb6SRafael Auler Alloc.deallocate(SpanningTreeNodes[I].InEdges); 835cc4b2fb6SRafael Auler if (CFGNodes[I].OutEdges) 836cc4b2fb6SRafael Auler Alloc.deallocate(CFGNodes[I].OutEdges); 837cc4b2fb6SRafael Auler if (CFGNodes[I].InEdges) 838cc4b2fb6SRafael Auler Alloc.deallocate(CFGNodes[I].InEdges); 839cc4b2fb6SRafael Auler } 840cc4b2fb6SRafael Auler if (SpanningTreeNodes) 841cc4b2fb6SRafael Auler Alloc.deallocate(SpanningTreeNodes); 842cc4b2fb6SRafael Auler if (CFGNodes) 843cc4b2fb6SRafael Auler Alloc.deallocate(CFGNodes); 844cc4b2fb6SRafael Auler } 845cc4b2fb6SRafael Auler 846cc4b2fb6SRafael Auler void Graph::dump() const { 847cc4b2fb6SRafael Auler reportNumber("Dumping graph with number of nodes: ", NumNodes, 10); 848cc4b2fb6SRafael Auler report(" Full graph:\n"); 849cc4b2fb6SRafael Auler for (int I = 0; I < NumNodes; ++I) { 850cc4b2fb6SRafael Auler const Node *N = &CFGNodes[I]; 851cc4b2fb6SRafael Auler reportNumber(" Node #", I, 10); 852cc4b2fb6SRafael Auler reportNumber(" InEdges total ", N->NumInEdges, 10); 853cc4b2fb6SRafael Auler for (int J = 0; J < N->NumInEdges; ++J) 854cc4b2fb6SRafael Auler reportNumber(" ", N->InEdges[J].Node, 10); 855cc4b2fb6SRafael Auler reportNumber(" OutEdges total ", N->NumOutEdges, 10); 856cc4b2fb6SRafael Auler for (int J = 0; J < N->NumOutEdges; ++J) 857cc4b2fb6SRafael Auler reportNumber(" ", N->OutEdges[J].Node, 10); 858cc4b2fb6SRafael Auler report("\n"); 859cc4b2fb6SRafael Auler } 860cc4b2fb6SRafael Auler report(" Spanning tree:\n"); 861cc4b2fb6SRafael Auler for (int I = 0; I < NumNodes; ++I) { 862cc4b2fb6SRafael Auler const Node *N = &SpanningTreeNodes[I]; 863cc4b2fb6SRafael Auler reportNumber(" Node #", I, 10); 864cc4b2fb6SRafael Auler reportNumber(" InEdges total ", N->NumInEdges, 10); 865cc4b2fb6SRafael Auler for (int J = 0; J < N->NumInEdges; ++J) 866cc4b2fb6SRafael Auler reportNumber(" ", N->InEdges[J].Node, 10); 867cc4b2fb6SRafael Auler reportNumber(" OutEdges total ", N->NumOutEdges, 10); 868cc4b2fb6SRafael Auler for (int J = 0; J < N->NumOutEdges; ++J) 869cc4b2fb6SRafael Auler reportNumber(" ", N->OutEdges[J].Node, 10); 870cc4b2fb6SRafael Auler report("\n"); 871cc4b2fb6SRafael Auler } 872cc4b2fb6SRafael Auler } 873cc4b2fb6SRafael Auler 87416a497c6SRafael Auler void Graph::dumpEdgeFreqs() const { 87516a497c6SRafael Auler reportNumber( 87616a497c6SRafael Auler "Dumping edge frequencies for graph with num edges: ", D.NumEdges, 10); 87716a497c6SRafael Auler for (int I = 0; I < D.NumEdges; ++I) { 87816a497c6SRafael Auler reportNumber("* Src: ", D.Edges[I].FromNode, 10); 87916a497c6SRafael Auler reportNumber(" Dst: ", D.Edges[I].ToNode, 10); 880cc4b2fb6SRafael Auler reportNumber(" Cnt: ", EdgeFreqs[I], 10); 881cc4b2fb6SRafael Auler } 882cc4b2fb6SRafael Auler } 883cc4b2fb6SRafael Auler 88416a497c6SRafael Auler /// Auxiliary map structure for fast lookups of which calls map to each node of 88516a497c6SRafael Auler /// the function CFG 88616a497c6SRafael Auler struct NodeToCallsMap { 88716a497c6SRafael Auler struct MapEntry { 88816a497c6SRafael Auler uint32_t NumCalls; 88916a497c6SRafael Auler uint32_t *Calls; 89016a497c6SRafael Auler }; 89116a497c6SRafael Auler MapEntry *Entries; 89216a497c6SRafael Auler BumpPtrAllocator &Alloc; 89316a497c6SRafael Auler const uint32_t NumNodes; 894cc4b2fb6SRafael Auler 89516a497c6SRafael Auler NodeToCallsMap(BumpPtrAllocator &Alloc, const FunctionDescription &D, 89616a497c6SRafael Auler uint32_t NumNodes) 89716a497c6SRafael Auler : Alloc(Alloc), NumNodes(NumNodes) { 89816a497c6SRafael Auler Entries = new (Alloc, 0) MapEntry[NumNodes]; 89916a497c6SRafael Auler for (int I = 0; I < D.NumCalls; ++I) { 90016a497c6SRafael Auler DEBUG(reportNumber("Registering call in node ", D.Calls[I].FromNode, 10)); 90116a497c6SRafael Auler ++Entries[D.Calls[I].FromNode].NumCalls; 90216a497c6SRafael Auler } 90316a497c6SRafael Auler for (int I = 0; I < NumNodes; ++I) { 90416a497c6SRafael Auler Entries[I].Calls = Entries[I].NumCalls ? new (Alloc) 90516a497c6SRafael Auler uint32_t[Entries[I].NumCalls] 90616a497c6SRafael Auler : nullptr; 90716a497c6SRafael Auler Entries[I].NumCalls = 0; 90816a497c6SRafael Auler } 90916a497c6SRafael Auler for (int I = 0; I < D.NumCalls; ++I) { 91016a497c6SRafael Auler auto &Entry = Entries[D.Calls[I].FromNode]; 91116a497c6SRafael Auler Entry.Calls[Entry.NumCalls++] = I; 91216a497c6SRafael Auler } 91316a497c6SRafael Auler } 91416a497c6SRafael Auler 91516a497c6SRafael Auler /// Set the frequency of all calls in node \p NodeID to Freq. However, if 91616a497c6SRafael Auler /// the calls have their own counters and do not depend on the basic block 91716a497c6SRafael Auler /// counter, this means they have landing pads and throw exceptions. In this 91816a497c6SRafael Auler /// case, set their frequency with their counters and return the maximum 91916a497c6SRafael Auler /// value observed in such counters. This will be used as the new frequency 92016a497c6SRafael Auler /// at basic block entry. This is used to fix the CFG edge frequencies in the 92116a497c6SRafael Auler /// presence of exceptions. 92216a497c6SRafael Auler uint64_t visitAllCallsIn(uint32_t NodeID, uint64_t Freq, uint64_t *CallFreqs, 92316a497c6SRafael Auler const FunctionDescription &D, 92416a497c6SRafael Auler const uint64_t *Counters, 92516a497c6SRafael Auler ProfileWriterContext &Ctx) const { 92616a497c6SRafael Auler const auto &Entry = Entries[NodeID]; 92716a497c6SRafael Auler uint64_t MaxValue = 0ull; 92816a497c6SRafael Auler for (int I = 0, E = Entry.NumCalls; I != E; ++I) { 92916a497c6SRafael Auler const auto CallID = Entry.Calls[I]; 93016a497c6SRafael Auler DEBUG(reportNumber(" Setting freq for call ID: ", CallID, 10)); 93116a497c6SRafael Auler auto &CallDesc = D.Calls[CallID]; 93216a497c6SRafael Auler if (CallDesc.Counter == 0xffffffff) { 93316a497c6SRafael Auler CallFreqs[CallID] = Freq; 93416a497c6SRafael Auler DEBUG(reportNumber(" with : ", Freq, 10)); 93516a497c6SRafael Auler } else { 93616a497c6SRafael Auler const auto CounterVal = Counters[CallDesc.Counter]; 93716a497c6SRafael Auler CallFreqs[CallID] = CounterVal; 93816a497c6SRafael Auler MaxValue = CounterVal > MaxValue ? CounterVal : MaxValue; 93916a497c6SRafael Auler DEBUG(reportNumber(" with (private counter) : ", CounterVal, 10)); 94016a497c6SRafael Auler } 94116a497c6SRafael Auler DEBUG(reportNumber(" Address: 0x", CallDesc.TargetAddress, 16)); 94216a497c6SRafael Auler if (CallFreqs[CallID] > 0) 94316a497c6SRafael Auler Ctx.CallFlowTable->get(CallDesc.TargetAddress).Calls += 94416a497c6SRafael Auler CallFreqs[CallID]; 94516a497c6SRafael Auler } 94616a497c6SRafael Auler return MaxValue; 94716a497c6SRafael Auler } 94816a497c6SRafael Auler 94916a497c6SRafael Auler ~NodeToCallsMap() { 95016a497c6SRafael Auler for (int I = NumNodes - 1; I >= 0; --I) { 95116a497c6SRafael Auler if (Entries[I].Calls) 95216a497c6SRafael Auler Alloc.deallocate(Entries[I].Calls); 95316a497c6SRafael Auler } 95416a497c6SRafael Auler Alloc.deallocate(Entries); 95516a497c6SRafael Auler } 95616a497c6SRafael Auler }; 95716a497c6SRafael Auler 95816a497c6SRafael Auler /// Fill an array with the frequency of each edge in the function represented 95916a497c6SRafael Auler /// by G, as well as another array for each call. 96016a497c6SRafael Auler void Graph::computeEdgeFrequencies(const uint64_t *Counters, 96116a497c6SRafael Auler ProfileWriterContext &Ctx) { 96216a497c6SRafael Auler if (NumNodes == 0) 96316a497c6SRafael Auler return; 96416a497c6SRafael Auler 96516a497c6SRafael Auler EdgeFreqs = D.NumEdges ? new (Alloc, 0) uint64_t [D.NumEdges] : nullptr; 96616a497c6SRafael Auler CallFreqs = D.NumCalls ? new (Alloc, 0) uint64_t [D.NumCalls] : nullptr; 96716a497c6SRafael Auler 96816a497c6SRafael Auler // Setup a lookup for calls present in each node (BB) 96916a497c6SRafael Auler NodeToCallsMap *CallMap = new (Alloc) NodeToCallsMap(Alloc, D, NumNodes); 970cc4b2fb6SRafael Auler 971cc4b2fb6SRafael Auler // Perform a bottom-up, BFS traversal of the spanning tree in G. Edges in the 972cc4b2fb6SRafael Auler // spanning tree don't have explicit counters. We must infer their value using 973cc4b2fb6SRafael Auler // a linear combination of other counters (sum of counters of the outgoing 974cc4b2fb6SRafael Auler // edges minus sum of counters of the incoming edges). 97516a497c6SRafael Auler uint32_t *Stack = new (Alloc) uint32_t [NumNodes]; 976cc4b2fb6SRafael Auler uint32_t StackTop = 0; 977cc4b2fb6SRafael Auler enum Status : uint8_t { S_NEW = 0, S_VISITING, S_VISITED }; 97816a497c6SRafael Auler Status *Visited = new (Alloc, 0) Status[NumNodes]; 97916a497c6SRafael Auler uint64_t *LeafFrequency = new (Alloc, 0) uint64_t[NumNodes]; 98016a497c6SRafael Auler uint64_t *EntryAddress = new (Alloc, 0) uint64_t[NumNodes]; 981cc4b2fb6SRafael Auler 982cc4b2fb6SRafael Auler // Setup a fast lookup for frequency of leaf nodes, which have special 983cc4b2fb6SRafael Auler // basic block frequency instrumentation (they are not edge profiled). 98416a497c6SRafael Auler for (int I = 0; I < D.NumLeafNodes; ++I) { 98516a497c6SRafael Auler LeafFrequency[D.LeafNodes[I].Node] = Counters[D.LeafNodes[I].Counter]; 986cc4b2fb6SRafael Auler DEBUG({ 98716a497c6SRafael Auler if (Counters[D.LeafNodes[I].Counter] > 0) { 98816a497c6SRafael Auler reportNumber("Leaf Node# ", D.LeafNodes[I].Node, 10); 98916a497c6SRafael Auler reportNumber(" Counter: ", Counters[D.LeafNodes[I].Counter], 10); 990cc4b2fb6SRafael Auler } 991cc4b2fb6SRafael Auler }); 99216a497c6SRafael Auler } 99316a497c6SRafael Auler for (int I = 0; I < D.NumEntryNodes; ++I) { 99416a497c6SRafael Auler EntryAddress[D.EntryNodes[I].Node] = D.EntryNodes[I].Address; 99516a497c6SRafael Auler DEBUG({ 99616a497c6SRafael Auler reportNumber("Entry Node# ", D.EntryNodes[I].Node, 10); 99716a497c6SRafael Auler reportNumber(" Address: ", D.EntryNodes[I].Address, 16); 99816a497c6SRafael Auler }); 999cc4b2fb6SRafael Auler } 1000cc4b2fb6SRafael Auler // Add all root nodes to the stack 100116a497c6SRafael Auler for (int I = 0; I < NumNodes; ++I) { 100216a497c6SRafael Auler if (SpanningTreeNodes[I].NumInEdges == 0) 1003cc4b2fb6SRafael Auler Stack[StackTop++] = I; 1004cc4b2fb6SRafael Auler } 1005cc4b2fb6SRafael Auler // Empty stack? 1006cc4b2fb6SRafael Auler if (StackTop == 0) { 100716a497c6SRafael Auler DEBUG(report("Empty stack!\n")); 100816a497c6SRafael Auler Alloc.deallocate(EntryAddress); 1009cc4b2fb6SRafael Auler Alloc.deallocate(LeafFrequency); 1010cc4b2fb6SRafael Auler Alloc.deallocate(Visited); 1011cc4b2fb6SRafael Auler Alloc.deallocate(Stack); 101216a497c6SRafael Auler CallMap->~NodeToCallsMap(); 101316a497c6SRafael Auler Alloc.deallocate(CallMap); 101416a497c6SRafael Auler if (CallFreqs) 101516a497c6SRafael Auler Alloc.deallocate(CallFreqs); 101616a497c6SRafael Auler if (EdgeFreqs) 101716a497c6SRafael Auler Alloc.deallocate(EdgeFreqs); 101816a497c6SRafael Auler EdgeFreqs = nullptr; 101916a497c6SRafael Auler CallFreqs = nullptr; 102016a497c6SRafael Auler return; 1021cc4b2fb6SRafael Auler } 1022cc4b2fb6SRafael Auler // Add all known edge counts, will infer the rest 102316a497c6SRafael Auler for (int I = 0; I < D.NumEdges; ++I) { 102416a497c6SRafael Auler const uint32_t C = D.Edges[I].Counter; 1025cc4b2fb6SRafael Auler if (C == 0xffffffff) // inferred counter - we will compute its value 1026cc4b2fb6SRafael Auler continue; 102716a497c6SRafael Auler EdgeFreqs[I] = Counters[C]; 1028cc4b2fb6SRafael Auler } 1029cc4b2fb6SRafael Auler 1030cc4b2fb6SRafael Auler while (StackTop > 0) { 1031cc4b2fb6SRafael Auler const uint32_t Cur = Stack[--StackTop]; 1032cc4b2fb6SRafael Auler DEBUG({ 1033cc4b2fb6SRafael Auler if (Visited[Cur] == S_VISITING) 1034cc4b2fb6SRafael Auler report("(visiting) "); 1035cc4b2fb6SRafael Auler else 1036cc4b2fb6SRafael Auler report("(new) "); 1037cc4b2fb6SRafael Auler reportNumber("Cur: ", Cur, 10); 1038cc4b2fb6SRafael Auler }); 1039cc4b2fb6SRafael Auler 1040cc4b2fb6SRafael Auler // This shouldn't happen in a tree 1041cc4b2fb6SRafael Auler assert(Visited[Cur] != S_VISITED, "should not have visited nodes in stack"); 1042cc4b2fb6SRafael Auler if (Visited[Cur] == S_NEW) { 1043cc4b2fb6SRafael Auler Visited[Cur] = S_VISITING; 1044cc4b2fb6SRafael Auler Stack[StackTop++] = Cur; 104516a497c6SRafael Auler assert(StackTop <= NumNodes, "stack grew too large"); 104616a497c6SRafael Auler for (int I = 0, E = SpanningTreeNodes[Cur].NumOutEdges; I < E; ++I) { 104716a497c6SRafael Auler const uint32_t Succ = SpanningTreeNodes[Cur].OutEdges[I].Node; 1048cc4b2fb6SRafael Auler Stack[StackTop++] = Succ; 104916a497c6SRafael Auler assert(StackTop <= NumNodes, "stack grew too large"); 1050cc4b2fb6SRafael Auler } 1051cc4b2fb6SRafael Auler continue; 1052cc4b2fb6SRafael Auler } 1053cc4b2fb6SRafael Auler Visited[Cur] = S_VISITED; 1054cc4b2fb6SRafael Auler 1055cc4b2fb6SRafael Auler // Establish our node frequency based on outgoing edges, which should all be 1056cc4b2fb6SRafael Auler // resolved by now. 1057cc4b2fb6SRafael Auler int64_t CurNodeFreq = LeafFrequency[Cur]; 1058cc4b2fb6SRafael Auler // Not a leaf? 1059cc4b2fb6SRafael Auler if (!CurNodeFreq) { 106016a497c6SRafael Auler for (int I = 0, E = CFGNodes[Cur].NumOutEdges; I != E; ++I) { 106116a497c6SRafael Auler const uint32_t SuccEdge = CFGNodes[Cur].OutEdges[I].ID; 106216a497c6SRafael Auler CurNodeFreq += EdgeFreqs[SuccEdge]; 1063cc4b2fb6SRafael Auler } 1064cc4b2fb6SRafael Auler } 106516a497c6SRafael Auler if (CurNodeFreq < 0) 106616a497c6SRafael Auler CurNodeFreq = 0; 106716a497c6SRafael Auler 106816a497c6SRafael Auler const uint64_t CallFreq = CallMap->visitAllCallsIn( 106916a497c6SRafael Auler Cur, CurNodeFreq > 0 ? CurNodeFreq : 0, CallFreqs, D, Counters, Ctx); 107016a497c6SRafael Auler 107116a497c6SRafael Auler // Exception handling affected our output flow? Fix with calls info 107216a497c6SRafael Auler DEBUG({ 107316a497c6SRafael Auler if (CallFreq > CurNodeFreq) 107416a497c6SRafael Auler report("Bumping node frequency with call info\n"); 107516a497c6SRafael Auler }); 107616a497c6SRafael Auler CurNodeFreq = CallFreq > CurNodeFreq ? CallFreq : CurNodeFreq; 107716a497c6SRafael Auler 107816a497c6SRafael Auler if (CurNodeFreq > 0) { 107916a497c6SRafael Auler if (uint64_t Addr = EntryAddress[Cur]) { 108016a497c6SRafael Auler DEBUG( 108116a497c6SRafael Auler reportNumber(" Setting flow at entry point address 0x", Addr, 16)); 108216a497c6SRafael Auler DEBUG(reportNumber(" with: ", CurNodeFreq, 10)); 108316a497c6SRafael Auler Ctx.CallFlowTable->get(Addr).Val = CurNodeFreq; 108416a497c6SRafael Auler } 108516a497c6SRafael Auler } 108616a497c6SRafael Auler 108716a497c6SRafael Auler // No parent? Reached a tree root, limit to call frequency updating. 108816a497c6SRafael Auler if (SpanningTreeNodes[Cur].NumInEdges == 0) { 108916a497c6SRafael Auler continue; 109016a497c6SRafael Auler } 109116a497c6SRafael Auler 109216a497c6SRafael Auler assert(SpanningTreeNodes[Cur].NumInEdges == 1, "must have 1 parent"); 109316a497c6SRafael Auler const uint32_t Parent = SpanningTreeNodes[Cur].InEdges[0].Node; 109416a497c6SRafael Auler const uint32_t ParentEdge = SpanningTreeNodes[Cur].InEdges[0].ID; 109516a497c6SRafael Auler 1096cc4b2fb6SRafael Auler // Calculate parent edge freq. 109716a497c6SRafael Auler int64_t ParentEdgeFreq = CurNodeFreq; 109816a497c6SRafael Auler for (int I = 0, E = CFGNodes[Cur].NumInEdges; I != E; ++I) { 109916a497c6SRafael Auler const uint32_t PredEdge = CFGNodes[Cur].InEdges[I].ID; 110016a497c6SRafael Auler ParentEdgeFreq -= EdgeFreqs[PredEdge]; 1101cc4b2fb6SRafael Auler } 110216a497c6SRafael Auler 1103cc4b2fb6SRafael Auler // Sometimes the conservative CFG that BOLT builds will lead to incorrect 1104cc4b2fb6SRafael Auler // flow computation. For example, in a BB that transitively calls the exit 1105cc4b2fb6SRafael Auler // syscall, BOLT will add a fall-through successor even though it should not 1106cc4b2fb6SRafael Auler // have any successors. So this block execution will likely be wrong. We 1107cc4b2fb6SRafael Auler // tolerate this imperfection since this case should be quite infrequent. 1108cc4b2fb6SRafael Auler if (ParentEdgeFreq < 0) { 110916a497c6SRafael Auler DEBUG(dumpEdgeFreqs()); 1110cc4b2fb6SRafael Auler DEBUG(report("WARNING: incorrect flow")); 1111cc4b2fb6SRafael Auler ParentEdgeFreq = 0; 1112cc4b2fb6SRafael Auler } 1113cc4b2fb6SRafael Auler DEBUG(reportNumber(" Setting freq for ParentEdge: ", ParentEdge, 10)); 1114cc4b2fb6SRafael Auler DEBUG(reportNumber(" with ParentEdgeFreq: ", ParentEdgeFreq, 10)); 111516a497c6SRafael Auler EdgeFreqs[ParentEdge] = ParentEdgeFreq; 1116cc4b2fb6SRafael Auler } 1117cc4b2fb6SRafael Auler 111816a497c6SRafael Auler Alloc.deallocate(EntryAddress); 1119cc4b2fb6SRafael Auler Alloc.deallocate(LeafFrequency); 1120cc4b2fb6SRafael Auler Alloc.deallocate(Visited); 1121cc4b2fb6SRafael Auler Alloc.deallocate(Stack); 112216a497c6SRafael Auler CallMap->~NodeToCallsMap(); 112316a497c6SRafael Auler Alloc.deallocate(CallMap); 112416a497c6SRafael Auler DEBUG(dumpEdgeFreqs()); 1125cc4b2fb6SRafael Auler } 1126cc4b2fb6SRafael Auler 112716a497c6SRafael Auler /// Write to \p FD all of the edge profiles for function \p FuncDesc. Uses 112816a497c6SRafael Auler /// \p Alloc to allocate helper dynamic structures used to compute profile for 112916a497c6SRafael Auler /// edges that we do not explictly instrument. 113016a497c6SRafael Auler const uint8_t *writeFunctionProfile(int FD, ProfileWriterContext &Ctx, 113116a497c6SRafael Auler const uint8_t *FuncDesc, 113216a497c6SRafael Auler BumpPtrAllocator &Alloc) { 113316a497c6SRafael Auler const FunctionDescription F(FuncDesc); 113416a497c6SRafael Auler const uint8_t *next = FuncDesc + F.getSize(); 1135cc4b2fb6SRafael Auler 1136*a0dd5b05SAlexander Shaposhnikov #if !defined(__APPLE__) 1137*a0dd5b05SAlexander Shaposhnikov uint64_t *bolt_instr_locations = __bolt_instr_locations; 1138*a0dd5b05SAlexander Shaposhnikov #else 1139*a0dd5b05SAlexander Shaposhnikov uint64_t *bolt_instr_locations = _bolt_instr_locations_getter(); 1140*a0dd5b05SAlexander Shaposhnikov #endif 1141*a0dd5b05SAlexander Shaposhnikov 1142cc4b2fb6SRafael Auler // Skip funcs we know are cold 1143cc4b2fb6SRafael Auler #ifndef ENABLE_DEBUG 114416a497c6SRafael Auler uint64_t CountersFreq = 0; 114516a497c6SRafael Auler for (int I = 0; I < F.NumLeafNodes; ++I) { 1146*a0dd5b05SAlexander Shaposhnikov CountersFreq += bolt_instr_locations[F.LeafNodes[I].Counter]; 1147cc4b2fb6SRafael Auler } 114816a497c6SRafael Auler if (CountersFreq == 0) { 114916a497c6SRafael Auler for (int I = 0; I < F.NumEdges; ++I) { 115016a497c6SRafael Auler const uint32_t C = F.Edges[I].Counter; 115116a497c6SRafael Auler if (C == 0xffffffff) 115216a497c6SRafael Auler continue; 1153*a0dd5b05SAlexander Shaposhnikov CountersFreq += bolt_instr_locations[C]; 115416a497c6SRafael Auler } 115516a497c6SRafael Auler if (CountersFreq == 0) { 115616a497c6SRafael Auler for (int I = 0; I < F.NumCalls; ++I) { 115716a497c6SRafael Auler const uint32_t C = F.Calls[I].Counter; 115816a497c6SRafael Auler if (C == 0xffffffff) 115916a497c6SRafael Auler continue; 1160*a0dd5b05SAlexander Shaposhnikov CountersFreq += bolt_instr_locations[C]; 116116a497c6SRafael Auler } 116216a497c6SRafael Auler if (CountersFreq == 0) 1163cc4b2fb6SRafael Auler return next; 116416a497c6SRafael Auler } 116516a497c6SRafael Auler } 1166cc4b2fb6SRafael Auler #endif 1167cc4b2fb6SRafael Auler 1168*a0dd5b05SAlexander Shaposhnikov Graph *G = new (Alloc) Graph(Alloc, F, bolt_instr_locations, Ctx); 1169cc4b2fb6SRafael Auler DEBUG(G->dump()); 1170*a0dd5b05SAlexander Shaposhnikov 117116a497c6SRafael Auler if (!G->EdgeFreqs && !G->CallFreqs) { 1172cc4b2fb6SRafael Auler G->~Graph(); 1173cc4b2fb6SRafael Auler Alloc.deallocate(G); 1174cc4b2fb6SRafael Auler return next; 1175cc4b2fb6SRafael Auler } 1176cc4b2fb6SRafael Auler 117716a497c6SRafael Auler for (int I = 0; I < F.NumEdges; ++I) { 117816a497c6SRafael Auler const uint64_t Freq = G->EdgeFreqs[I]; 1179cc4b2fb6SRafael Auler if (Freq == 0) 1180cc4b2fb6SRafael Auler continue; 118116a497c6SRafael Auler const EdgeDescription *Desc = &F.Edges[I]; 1182cc4b2fb6SRafael Auler char LineBuf[BufSize]; 1183cc4b2fb6SRafael Auler char *Ptr = LineBuf; 118416a497c6SRafael Auler Ptr = serializeLoc(Ctx, Ptr, Desc->From, BufSize); 118516a497c6SRafael Auler Ptr = serializeLoc(Ctx, Ptr, Desc->To, BufSize - (Ptr - LineBuf)); 1186cc4b2fb6SRafael Auler Ptr = strCopy(Ptr, "0 ", BufSize - (Ptr - LineBuf) - 22); 1187cc4b2fb6SRafael Auler Ptr = intToStr(Ptr, Freq, 10); 1188cc4b2fb6SRafael Auler *Ptr++ = '\n'; 1189cc4b2fb6SRafael Auler __write(FD, LineBuf, Ptr - LineBuf); 1190cc4b2fb6SRafael Auler } 1191cc4b2fb6SRafael Auler 119216a497c6SRafael Auler for (int I = 0; I < F.NumCalls; ++I) { 119316a497c6SRafael Auler const uint64_t Freq = G->CallFreqs[I]; 119416a497c6SRafael Auler if (Freq == 0) 119516a497c6SRafael Auler continue; 119616a497c6SRafael Auler char LineBuf[BufSize]; 119716a497c6SRafael Auler char *Ptr = LineBuf; 119816a497c6SRafael Auler const CallDescription *Desc = &F.Calls[I]; 119916a497c6SRafael Auler Ptr = serializeLoc(Ctx, Ptr, Desc->From, BufSize); 120016a497c6SRafael Auler Ptr = serializeLoc(Ctx, Ptr, Desc->To, BufSize - (Ptr - LineBuf)); 120116a497c6SRafael Auler Ptr = strCopy(Ptr, "0 ", BufSize - (Ptr - LineBuf) - 25); 120216a497c6SRafael Auler Ptr = intToStr(Ptr, Freq, 10); 120316a497c6SRafael Auler *Ptr++ = '\n'; 120416a497c6SRafael Auler __write(FD, LineBuf, Ptr - LineBuf); 120516a497c6SRafael Auler } 120616a497c6SRafael Auler 1207cc4b2fb6SRafael Auler G->~Graph(); 1208cc4b2fb6SRafael Auler Alloc.deallocate(G); 1209cc4b2fb6SRafael Auler return next; 1210cc4b2fb6SRafael Auler } 1211cc4b2fb6SRafael Auler 1212*a0dd5b05SAlexander Shaposhnikov #if !defined(__APPLE__) 121316a497c6SRafael Auler const IndCallTargetDescription * 121416a497c6SRafael Auler ProfileWriterContext::lookupIndCallTarget(uint64_t Target) const { 121516a497c6SRafael Auler uint32_t B = 0; 121616a497c6SRafael Auler uint32_t E = __bolt_instr_num_ind_targets; 121716a497c6SRafael Auler if (E == 0) 121816a497c6SRafael Auler return nullptr; 121916a497c6SRafael Auler do { 122016a497c6SRafael Auler uint32_t I = (E - B) / 2 + B; 122116a497c6SRafael Auler if (IndCallTargets[I].Address == Target) 122216a497c6SRafael Auler return &IndCallTargets[I]; 122316a497c6SRafael Auler if (IndCallTargets[I].Address < Target) 122416a497c6SRafael Auler B = I + 1; 122516a497c6SRafael Auler else 122616a497c6SRafael Auler E = I; 122716a497c6SRafael Auler } while (B < E); 122816a497c6SRafael Auler return nullptr; 1229cc4b2fb6SRafael Auler } 123062aa74f8SRafael Auler 123116a497c6SRafael Auler /// Write a single indirect call <src, target> pair to the fdata file 123216a497c6SRafael Auler void visitIndCallCounter(IndirectCallHashTable::MapEntry &Entry, 123316a497c6SRafael Auler int FD, int CallsiteID, 123416a497c6SRafael Auler ProfileWriterContext *Ctx) { 123516a497c6SRafael Auler if (Entry.Val == 0) 123616a497c6SRafael Auler return; 123716a497c6SRafael Auler DEBUG(reportNumber("Target func 0x", Entry.Key, 16)); 123816a497c6SRafael Auler DEBUG(reportNumber("Target freq: ", Entry.Val, 10)); 123916a497c6SRafael Auler const IndCallDescription *CallsiteDesc = 124016a497c6SRafael Auler &Ctx->IndCallDescriptions[CallsiteID]; 124116a497c6SRafael Auler const IndCallTargetDescription *TargetDesc = 124216a497c6SRafael Auler Ctx->lookupIndCallTarget(Entry.Key); 124316a497c6SRafael Auler if (!TargetDesc) { 124416a497c6SRafael Auler DEBUG(report("Failed to lookup indirect call target\n")); 1245cc4b2fb6SRafael Auler char LineBuf[BufSize]; 124662aa74f8SRafael Auler char *Ptr = LineBuf; 124716a497c6SRafael Auler Ptr = serializeLoc(*Ctx, Ptr, *CallsiteDesc, BufSize); 124816a497c6SRafael Auler Ptr = strCopy(Ptr, "0 [unknown] 0 0 ", BufSize - (Ptr - LineBuf) - 40); 124916a497c6SRafael Auler Ptr = intToStr(Ptr, Entry.Val, 10); 125016a497c6SRafael Auler *Ptr++ = '\n'; 125116a497c6SRafael Auler __write(FD, LineBuf, Ptr - LineBuf); 125216a497c6SRafael Auler return; 125316a497c6SRafael Auler } 125416a497c6SRafael Auler Ctx->CallFlowTable->get(TargetDesc->Address).Calls += Entry.Val; 125516a497c6SRafael Auler char LineBuf[BufSize]; 125616a497c6SRafael Auler char *Ptr = LineBuf; 125716a497c6SRafael Auler Ptr = serializeLoc(*Ctx, Ptr, *CallsiteDesc, BufSize); 125816a497c6SRafael Auler Ptr = serializeLoc(*Ctx, Ptr, TargetDesc->Loc, BufSize - (Ptr - LineBuf)); 1259cc4b2fb6SRafael Auler Ptr = strCopy(Ptr, "0 ", BufSize - (Ptr - LineBuf) - 25); 126016a497c6SRafael Auler Ptr = intToStr(Ptr, Entry.Val, 10); 126162aa74f8SRafael Auler *Ptr++ = '\n'; 1262821480d2SRafael Auler __write(FD, LineBuf, Ptr - LineBuf); 126362aa74f8SRafael Auler } 1264cc4b2fb6SRafael Auler 126516a497c6SRafael Auler /// Write to \p FD all of the indirect call profiles. 126616a497c6SRafael Auler void writeIndirectCallProfile(int FD, ProfileWriterContext &Ctx) { 126716a497c6SRafael Auler for (int I = 0; I < __bolt_instr_num_ind_calls; ++I) { 126816a497c6SRafael Auler DEBUG(reportNumber("IndCallsite #", I, 10)); 126916a497c6SRafael Auler GlobalIndCallCounters[I].forEachElement(visitIndCallCounter, FD, I, &Ctx); 127016a497c6SRafael Auler } 127116a497c6SRafael Auler } 127216a497c6SRafael Auler 127316a497c6SRafael Auler /// Check a single call flow for a callee versus all known callers. If there are 127416a497c6SRafael Auler /// less callers than what the callee expects, write the difference with source 127516a497c6SRafael Auler /// [unknown] in the profile. 127616a497c6SRafael Auler void visitCallFlowEntry(CallFlowHashTable::MapEntry &Entry, int FD, 127716a497c6SRafael Auler ProfileWriterContext *Ctx) { 127816a497c6SRafael Auler DEBUG(reportNumber("Call flow entry address: 0x", Entry.Key, 16)); 127916a497c6SRafael Auler DEBUG(reportNumber("Calls: ", Entry.Calls, 10)); 128016a497c6SRafael Auler DEBUG(reportNumber("Reported entry frequency: ", Entry.Val, 10)); 128116a497c6SRafael Auler DEBUG({ 128216a497c6SRafael Auler if (Entry.Calls > Entry.Val) 128316a497c6SRafael Auler report(" More calls than expected!\n"); 128416a497c6SRafael Auler }); 128516a497c6SRafael Auler if (Entry.Val <= Entry.Calls) 128616a497c6SRafael Auler return; 128716a497c6SRafael Auler DEBUG(reportNumber( 128816a497c6SRafael Auler " Balancing calls with traffic: ", Entry.Val - Entry.Calls, 10)); 128916a497c6SRafael Auler const IndCallTargetDescription *TargetDesc = 129016a497c6SRafael Auler Ctx->lookupIndCallTarget(Entry.Key); 129116a497c6SRafael Auler if (!TargetDesc) { 129216a497c6SRafael Auler // There is probably something wrong with this callee and this should be 129316a497c6SRafael Auler // investigated, but I don't want to assert and lose all data collected. 129416a497c6SRafael Auler DEBUG(report("WARNING: failed to look up call target!\n")); 129516a497c6SRafael Auler return; 129616a497c6SRafael Auler } 129716a497c6SRafael Auler char LineBuf[BufSize]; 129816a497c6SRafael Auler char *Ptr = LineBuf; 129916a497c6SRafael Auler Ptr = strCopy(Ptr, "0 [unknown] 0 ", BufSize); 130016a497c6SRafael Auler Ptr = serializeLoc(*Ctx, Ptr, TargetDesc->Loc, BufSize - (Ptr - LineBuf)); 130116a497c6SRafael Auler Ptr = strCopy(Ptr, "0 ", BufSize - (Ptr - LineBuf) - 25); 130216a497c6SRafael Auler Ptr = intToStr(Ptr, Entry.Val - Entry.Calls, 10); 130316a497c6SRafael Auler *Ptr++ = '\n'; 130416a497c6SRafael Auler __write(FD, LineBuf, Ptr - LineBuf); 130516a497c6SRafael Auler } 130616a497c6SRafael Auler 130716a497c6SRafael Auler /// Open fdata file for writing and return a valid file descriptor, aborting 130816a497c6SRafael Auler /// program upon failure. 130916a497c6SRafael Auler int openProfile() { 131016a497c6SRafael Auler // Build the profile name string by appending our PID 131116a497c6SRafael Auler char Buf[BufSize]; 131216a497c6SRafael Auler char *Ptr = Buf; 131316a497c6SRafael Auler uint64_t PID = __getpid(); 131416a497c6SRafael Auler Ptr = strCopy(Buf, __bolt_instr_filename, BufSize); 131516a497c6SRafael Auler if (__bolt_instr_use_pid) { 131616a497c6SRafael Auler Ptr = strCopy(Ptr, ".", BufSize - (Ptr - Buf + 1)); 131716a497c6SRafael Auler Ptr = intToStr(Ptr, PID, 10); 131816a497c6SRafael Auler Ptr = strCopy(Ptr, ".fdata", BufSize - (Ptr - Buf + 1)); 131916a497c6SRafael Auler } 132016a497c6SRafael Auler *Ptr++ = '\0'; 132116a497c6SRafael Auler uint64_t FD = __open(Buf, 132216a497c6SRafael Auler /*flags=*/0x241 /*O_WRONLY|O_TRUNC|O_CREAT*/, 132316a497c6SRafael Auler /*mode=*/0666); 132416a497c6SRafael Auler if (static_cast<int64_t>(FD) < 0) { 132516a497c6SRafael Auler report("Error while trying to open profile file for writing: "); 132616a497c6SRafael Auler report(Buf); 132716a497c6SRafael Auler reportNumber("\nFailed with error number: 0x", 132816a497c6SRafael Auler 0 - static_cast<int64_t>(FD), 16); 132916a497c6SRafael Auler __exit(1); 133016a497c6SRafael Auler } 133116a497c6SRafael Auler return FD; 133216a497c6SRafael Auler } 1333*a0dd5b05SAlexander Shaposhnikov 1334*a0dd5b05SAlexander Shaposhnikov #endif 1335*a0dd5b05SAlexander Shaposhnikov 133616a497c6SRafael Auler } // anonymous namespace 133716a497c6SRafael Auler 1338*a0dd5b05SAlexander Shaposhnikov #if !defined(__APPLE__) 1339*a0dd5b05SAlexander Shaposhnikov 134016a497c6SRafael Auler /// Reset all counters in case you want to start profiling a new phase of your 134116a497c6SRafael Auler /// program independently of prior phases. 134216a497c6SRafael Auler /// The address of this function is printed by BOLT and this can be called by 134316a497c6SRafael Auler /// any attached debugger during runtime. There is a useful oneliner for gdb: 134416a497c6SRafael Auler /// 134516a497c6SRafael Auler /// gdb -p $(pgrep -xo PROCESSNAME) -ex 'p ((void(*)())0xdeadbeef)()' \ 134616a497c6SRafael Auler /// -ex 'set confirm off' -ex quit 134716a497c6SRafael Auler /// 134816a497c6SRafael Auler /// Where 0xdeadbeef is this function address and PROCESSNAME your binary file 134916a497c6SRafael Auler /// name. 135016a497c6SRafael Auler extern "C" void __bolt_instr_clear_counters() { 135116a497c6SRafael Auler memSet(reinterpret_cast<char *>(__bolt_instr_locations), 0, 135216a497c6SRafael Auler __bolt_num_counters * 8); 135316a497c6SRafael Auler for (int I = 0; I < __bolt_instr_num_ind_calls; ++I) { 135416a497c6SRafael Auler GlobalIndCallCounters[I].resetCounters(); 135516a497c6SRafael Auler } 135616a497c6SRafael Auler } 135716a497c6SRafael Auler 135816a497c6SRafael Auler /// This is the entry point for profile writing. 135916a497c6SRafael Auler /// There are three ways of getting here: 136016a497c6SRafael Auler /// 136116a497c6SRafael Auler /// * Program execution ended, finalization methods are running and BOLT 136216a497c6SRafael Auler /// hooked into FINI from your binary dynamic section; 136316a497c6SRafael Auler /// * You used the sleep timer option and during initialization we forked 136416a497c6SRafael Auler /// a separete process that will call this function periodically; 136516a497c6SRafael Auler /// * BOLT prints this function address so you can attach a debugger and 136616a497c6SRafael Auler /// call this function directly to get your profile written to disk 136716a497c6SRafael Auler /// on demand. 136816a497c6SRafael Auler /// 136916a497c6SRafael Auler extern "C" void __bolt_instr_data_dump() { 137016a497c6SRafael Auler // Already dumping 137116a497c6SRafael Auler if (!GlobalWriteProfileMutex->acquire()) 137216a497c6SRafael Auler return; 137316a497c6SRafael Auler 137416a497c6SRafael Auler BumpPtrAllocator HashAlloc; 137516a497c6SRafael Auler HashAlloc.setMaxSize(0x6400000); 137616a497c6SRafael Auler ProfileWriterContext Ctx = readDescriptions(); 137716a497c6SRafael Auler Ctx.CallFlowTable = new (HashAlloc, 0) CallFlowHashTable(HashAlloc); 137816a497c6SRafael Auler 137916a497c6SRafael Auler DEBUG(printStats(Ctx)); 138016a497c6SRafael Auler 138116a497c6SRafael Auler int FD = openProfile(); 138216a497c6SRafael Auler 1383cc4b2fb6SRafael Auler BumpPtrAllocator Alloc; 138416a497c6SRafael Auler const uint8_t *FuncDesc = Ctx.FuncDescriptions; 1385cc4b2fb6SRafael Auler for (int I = 0, E = __bolt_instr_num_funcs; I < E; ++I) { 138616a497c6SRafael Auler FuncDesc = writeFunctionProfile(FD, Ctx, FuncDesc, Alloc); 138716a497c6SRafael Auler Alloc.clear(); 1388cc4b2fb6SRafael Auler DEBUG(reportNumber("FuncDesc now: ", (uint64_t)FuncDesc, 16)); 1389cc4b2fb6SRafael Auler } 139016a497c6SRafael Auler assert(FuncDesc == (void *)Ctx.Strings, 1391cc4b2fb6SRafael Auler "FuncDesc ptr must be equal to stringtable"); 1392cc4b2fb6SRafael Auler 139316a497c6SRafael Auler writeIndirectCallProfile(FD, Ctx); 139416a497c6SRafael Auler Ctx.CallFlowTable->forEachElement(visitCallFlowEntry, FD, &Ctx); 139516a497c6SRafael Auler 1396821480d2SRafael Auler __close(FD); 139716a497c6SRafael Auler __munmap(Ctx.MMapPtr, Ctx.MMapSize); 139816a497c6SRafael Auler __close(Ctx.FileDesc); 139916a497c6SRafael Auler HashAlloc.destroy(); 140016a497c6SRafael Auler GlobalWriteProfileMutex->release(); 140116a497c6SRafael Auler DEBUG(report("Finished writing profile.\n")); 140216a497c6SRafael Auler } 140316a497c6SRafael Auler 140416a497c6SRafael Auler /// Event loop for our child process spawned during setup to dump profile data 140516a497c6SRafael Auler /// at user-specified intervals 140616a497c6SRafael Auler void watchProcess() { 140716a497c6SRafael Auler timespec ts, rem; 140816a497c6SRafael Auler uint64_t Ellapsed = 0ull; 140916a497c6SRafael Auler ts.tv_sec = 1; 141016a497c6SRafael Auler ts.tv_nsec = 0; 141116a497c6SRafael Auler while (1) { 141216a497c6SRafael Auler __nanosleep(&ts, &rem); 141316a497c6SRafael Auler // This means our parent process died, so no need for us to keep dumping. 141416a497c6SRafael Auler // Notice that make and some systems will wait until all child processes 141516a497c6SRafael Auler // of a command finishes before proceeding, so it is important to exit as 141616a497c6SRafael Auler // early as possible once our parent dies. 141716a497c6SRafael Auler if (__getppid() == 1) { 141816a497c6SRafael Auler break; 141916a497c6SRafael Auler } 142016a497c6SRafael Auler if (++Ellapsed < __bolt_instr_sleep_time) 142116a497c6SRafael Auler continue; 142216a497c6SRafael Auler Ellapsed = 0; 142316a497c6SRafael Auler __bolt_instr_data_dump(); 142416a497c6SRafael Auler __bolt_instr_clear_counters(); 142516a497c6SRafael Auler } 142616a497c6SRafael Auler DEBUG(report("My parent process is dead, bye!\n")); 142716a497c6SRafael Auler __exit(0); 142816a497c6SRafael Auler } 142916a497c6SRafael Auler 143016a497c6SRafael Auler extern "C" void __bolt_instr_indirect_call(); 143116a497c6SRafael Auler extern "C" void __bolt_instr_indirect_tailcall(); 143216a497c6SRafael Auler 143316a497c6SRafael Auler /// Initialization code 143416a497c6SRafael Auler extern "C" void __bolt_instr_setup() { 143516a497c6SRafael Auler const uint64_t CountersStart = 143616a497c6SRafael Auler reinterpret_cast<uint64_t>(&__bolt_instr_locations[0]); 143716a497c6SRafael Auler const uint64_t CountersEnd = alignTo( 143816a497c6SRafael Auler reinterpret_cast<uint64_t>(&__bolt_instr_locations[__bolt_num_counters]), 143916a497c6SRafael Auler 0x1000); 144016a497c6SRafael Auler DEBUG(reportNumber("replace mmap start: ", CountersStart, 16)); 144116a497c6SRafael Auler DEBUG(reportNumber("replace mmap stop: ", CountersEnd, 16)); 144216a497c6SRafael Auler assert (CountersEnd > CountersStart, "no counters"); 144316a497c6SRafael Auler // Maps our counters to be shared instead of private, so we keep counting for 144416a497c6SRafael Auler // forked processes 144516a497c6SRafael Auler __mmap(CountersStart, CountersEnd - CountersStart, 144616a497c6SRafael Auler 0x3 /*PROT_READ|PROT_WRITE*/, 144716a497c6SRafael Auler 0x31 /*MAP_ANONYMOUS | MAP_SHARED | MAP_FIXED*/, -1, 0); 144816a497c6SRafael Auler 144916a497c6SRafael Auler __bolt_trampoline_ind_call = __bolt_instr_indirect_call; 145016a497c6SRafael Auler __bolt_trampoline_ind_tailcall = __bolt_instr_indirect_tailcall; 145116a497c6SRafael Auler // Conservatively reserve 100MiB shared pages 145216a497c6SRafael Auler GlobalAlloc.setMaxSize(0x6400000); 145316a497c6SRafael Auler GlobalAlloc.setShared(true); 145416a497c6SRafael Auler GlobalWriteProfileMutex = new (GlobalAlloc, 0) Mutex(); 145516a497c6SRafael Auler if (__bolt_instr_num_ind_calls > 0) 145616a497c6SRafael Auler GlobalIndCallCounters = 145716a497c6SRafael Auler new (GlobalAlloc, 0) IndirectCallHashTable[__bolt_instr_num_ind_calls]; 145816a497c6SRafael Auler 145916a497c6SRafael Auler if (__bolt_instr_sleep_time != 0) { 146016a497c6SRafael Auler if (auto PID = __fork()) 146116a497c6SRafael Auler return; 146216a497c6SRafael Auler watchProcess(); 146316a497c6SRafael Auler } 146416a497c6SRafael Auler } 146516a497c6SRafael Auler 146616a497c6SRafael Auler extern "C" void instrumentIndirectCall(uint64_t Target, uint64_t IndCallID) { 146716a497c6SRafael Auler GlobalIndCallCounters[IndCallID].incrementVal(Target, GlobalAlloc); 146816a497c6SRafael Auler } 146916a497c6SRafael Auler 147016a497c6SRafael Auler /// We receive as in-stack arguments the identifier of the indirect call site 147116a497c6SRafael Auler /// as well as the target address for the call 147216a497c6SRafael Auler extern "C" __attribute((naked)) void __bolt_instr_indirect_call() 147316a497c6SRafael Auler { 147416a497c6SRafael Auler __asm__ __volatile__(SAVE_ALL 1475c6799a68SRafael Auler "mov 0x90(%%rsp), %%rdi\n" 1476c6799a68SRafael Auler "mov 0x88(%%rsp), %%rsi\n" 147716a497c6SRafael Auler "call instrumentIndirectCall\n" 147816a497c6SRafael Auler RESTORE_ALL 147916a497c6SRafael Auler "pop %%rdi\n" 148016a497c6SRafael Auler "add $16, %%rsp\n" 148116a497c6SRafael Auler "xchg (%%rsp), %%rdi\n" 148216a497c6SRafael Auler "jmp *-8(%%rsp)\n" 148316a497c6SRafael Auler :::); 148416a497c6SRafael Auler } 148516a497c6SRafael Auler 148616a497c6SRafael Auler extern "C" __attribute((naked)) void __bolt_instr_indirect_tailcall() 148716a497c6SRafael Auler { 148816a497c6SRafael Auler __asm__ __volatile__(SAVE_ALL 1489c6799a68SRafael Auler "mov 0x88(%%rsp), %%rdi\n" 1490c6799a68SRafael Auler "mov 0x80(%%rsp), %%rsi\n" 149116a497c6SRafael Auler "call instrumentIndirectCall\n" 149216a497c6SRafael Auler RESTORE_ALL 149316a497c6SRafael Auler "add $16, %%rsp\n" 149416a497c6SRafael Auler "pop %%rdi\n" 149516a497c6SRafael Auler "jmp *-16(%%rsp)\n" 149616a497c6SRafael Auler :::); 149716a497c6SRafael Auler } 149816a497c6SRafael Auler 149916a497c6SRafael Auler /// This is hooking ELF's entry, it needs to save all machine state. 150016a497c6SRafael Auler extern "C" __attribute((naked)) void __bolt_instr_start() 150116a497c6SRafael Auler { 150216a497c6SRafael Auler __asm__ __volatile__(SAVE_ALL 150316a497c6SRafael Auler "call __bolt_instr_setup\n" 150416a497c6SRafael Auler RESTORE_ALL 15058c7f524aSAlexander Shaposhnikov "jmp *__bolt_instr_init_ptr(%%rip)\n" 150616a497c6SRafael Auler :::); 150716a497c6SRafael Auler } 150816a497c6SRafael Auler 150916a497c6SRafael Auler /// This is hooking into ELF's DT_FINI 151016a497c6SRafael Auler extern "C" void __bolt_instr_fini() { 151116a497c6SRafael Auler __bolt_instr_fini_ptr(); 151216a497c6SRafael Auler if (__bolt_instr_sleep_time == 0) 151316a497c6SRafael Auler __bolt_instr_data_dump(); 151416a497c6SRafael Auler DEBUG(report("Finished.\n")); 151562aa74f8SRafael Auler } 1516bbd9d610SAlexander Shaposhnikov 15173b876cc3SAlexander Shaposhnikov #endif 15183b876cc3SAlexander Shaposhnikov 15193b876cc3SAlexander Shaposhnikov #if defined(__APPLE__) 1520bbd9d610SAlexander Shaposhnikov 1521*a0dd5b05SAlexander Shaposhnikov extern "C" void __bolt_instr_data_dump() { 1522*a0dd5b05SAlexander Shaposhnikov ProfileWriterContext Ctx = readDescriptions(); 1523*a0dd5b05SAlexander Shaposhnikov 1524*a0dd5b05SAlexander Shaposhnikov int FD = 2; 1525*a0dd5b05SAlexander Shaposhnikov BumpPtrAllocator Alloc; 1526*a0dd5b05SAlexander Shaposhnikov const uint8_t *FuncDesc = Ctx.FuncDescriptions; 1527*a0dd5b05SAlexander Shaposhnikov uint32_t bolt_instr_num_funcs = _bolt_instr_num_funcs_getter(); 1528*a0dd5b05SAlexander Shaposhnikov 1529*a0dd5b05SAlexander Shaposhnikov for (int I = 0, E = bolt_instr_num_funcs; I < E; ++I) { 1530*a0dd5b05SAlexander Shaposhnikov FuncDesc = writeFunctionProfile(FD, Ctx, FuncDesc, Alloc); 1531*a0dd5b05SAlexander Shaposhnikov Alloc.clear(); 1532*a0dd5b05SAlexander Shaposhnikov DEBUG(reportNumber("FuncDesc now: ", (uint64_t)FuncDesc, 16)); 1533*a0dd5b05SAlexander Shaposhnikov } 1534*a0dd5b05SAlexander Shaposhnikov assert(FuncDesc == (void *)Ctx.Strings, 1535*a0dd5b05SAlexander Shaposhnikov "FuncDesc ptr must be equal to stringtable"); 1536*a0dd5b05SAlexander Shaposhnikov } 1537*a0dd5b05SAlexander Shaposhnikov 1538bbd9d610SAlexander Shaposhnikov // On OSX/iOS the final symbol name of an extern "C" function/variable contains 1539bbd9d610SAlexander Shaposhnikov // one extra leading underscore: _bolt_instr_setup -> __bolt_instr_setup. 15403b876cc3SAlexander Shaposhnikov extern "C" 15413b876cc3SAlexander Shaposhnikov __attribute__((section("__TEXT,__setup"))) 15423b876cc3SAlexander Shaposhnikov __attribute__((force_align_arg_pointer)) 15433b876cc3SAlexander Shaposhnikov void _bolt_instr_setup() { 1544*a0dd5b05SAlexander Shaposhnikov __asm__ __volatile__(SAVE_ALL :::); 15453b876cc3SAlexander Shaposhnikov 1546*a0dd5b05SAlexander Shaposhnikov report("Hello!\n"); 15473b876cc3SAlexander Shaposhnikov 1548*a0dd5b05SAlexander Shaposhnikov __asm__ __volatile__(RESTORE_ALL :::); 15491cf23e5eSAlexander Shaposhnikov } 1550bbd9d610SAlexander Shaposhnikov 15513b876cc3SAlexander Shaposhnikov extern "C" 15523b876cc3SAlexander Shaposhnikov __attribute__((section("__TEXT,__fini"))) 15533b876cc3SAlexander Shaposhnikov __attribute__((force_align_arg_pointer)) 15543b876cc3SAlexander Shaposhnikov void _bolt_instr_fini() { 1555*a0dd5b05SAlexander Shaposhnikov report("Bye!\n"); 1556*a0dd5b05SAlexander Shaposhnikov __bolt_instr_data_dump(); 1557e067f2adSAlexander Shaposhnikov } 1558e067f2adSAlexander Shaposhnikov 1559bbd9d610SAlexander Shaposhnikov #endif 1560