19#include "llvm/Config/config.h"
47#define JIT_LANG "llvm-IR"
48#define LLVM_PERF_JIT_MAGIC \
49 ((uint32_t)'J' << 24 | (uint32_t)'i' << 16 | (uint32_t)'T' << 8 | \
51#define LLVM_PERF_JIT_VERSION 1
55#define JITDUMP_FLAGS_ARCH_TIMESTAMP (1ULL << 0)
57struct LLVMPerfJitHeader;
61 PerfJITEventListener();
62 ~PerfJITEventListener() {
72 bool InitDebuggingDir();
75 static bool FillMachine(LLVMPerfJitHeader &hdr);
91 std::unique_ptr<raw_fd_ostream> Dumpstream;
97 void *MarkerAddr = NULL;
100 bool SuccessfullyInitialized =
false;
108enum LLVMPerfJitRecordType {
118struct LLVMPerfJitHeader {
130struct LLVMPerfJitRecordPrefix {
136struct LLVMPerfJitRecordCodeLoad {
137 LLVMPerfJitRecordPrefix
Prefix;
147struct LLVMPerfJitDebugEntry {
154struct LLVMPerfJitRecordDebugInfo {
155 LLVMPerfJitRecordPrefix
Prefix;
162static inline uint64_t timespec_to_ns(
const struct timespec *ts) {
163 const uint64_t NanoSecPerSec = 1000000000;
164 return ((
uint64_t)ts->tv_sec * NanoSecPerSec) + ts->tv_nsec;
167static inline uint64_t perf_get_timestamp(
void) {
171 ret = clock_gettime(CLOCK_MONOTONIC, &ts);
175 return timespec_to_ns(&ts);
178PerfJITEventListener::PerfJITEventListener()
179 : Pid(sys::
Process::getProcessId()) {
181 if (!perf_get_timestamp()) {
182 errs() <<
"kernel does not support CLOCK_MONOTONIC\n";
186 if (!InitDebuggingDir()) {
187 errs() <<
"could not initialize debugging directory\n";
193 FilenameBuf << JitPath <<
"/jit-" << Pid <<
".dump";
201 errs() <<
"could not open JIT dump file " << FilenameBuf.str() <<
": "
202 <<
EC.message() <<
"\n";
206 Dumpstream = std::make_unique<raw_fd_ostream>(DumpFd,
true);
208 LLVMPerfJitHeader Header = {0, 0, 0, 0, 0, 0, 0, 0};
209 if (!FillMachine(Header))
219 Header.TotalSize =
sizeof(Header);
221 Header.Timestamp = perf_get_timestamp();
222 Dumpstream->write(
reinterpret_cast<const char *
>(&Header),
sizeof(Header));
225 if (!Dumpstream->has_error())
226 SuccessfullyInitialized =
true;
229void PerfJITEventListener::notifyObjectLoaded(
233 if (!SuccessfullyInitialized)
245 std::string SourceFileName;
273 if (
auto SectOrErr =
Sym.getSection())
275 SectionIndex = SectOrErr.get()->getIndex();
280 {*AddrOrErr, SectionIndex},
Size, FileLineInfoKind::AbsoluteFilePath);
282 NotifyDebug(*AddrOrErr, Lines);
287 std::lock_guard<sys::Mutex> Guard(
Mutex);
292void PerfJITEventListener::notifyFreeingObject(ObjectKey K) {
297bool PerfJITEventListener::InitDebuggingDir() {
300 char TimeBuffer[
sizeof(
"YYYYMMDD")];
304 if (
const char *BaseDir = getenv(
"JITDUMPDIR"))
305 Path.append(BaseDir);
310 Path +=
"/.debug/jit/";
312 errs() <<
"could not create jit cache directory " <<
Path <<
": "
313 <<
EC.message() <<
"\n";
319 localtime_r(&Time, &LocalTime);
320 strftime(TimeBuffer,
sizeof(TimeBuffer),
"%Y%m%d", &LocalTime);
328 errs() <<
"could not create unique jit cache directory " << UniqueDebugDir
329 <<
": " <<
EC.message() <<
"\n";
333 JitPath = std::string(UniqueDebugDir.
str());
338bool PerfJITEventListener::OpenMarker() {
348 PROT_READ | PROT_EXEC, MAP_PRIVATE, DumpFd, 0);
350 if (MarkerAddr == MAP_FAILED) {
351 errs() <<
"could not mmap JIT marker\n";
357void PerfJITEventListener::CloseMarker() {
362 MarkerAddr =
nullptr;
365bool PerfJITEventListener::FillMachine(LLVMPerfJitHeader &hdr) {
372 size_t RequiredMemory =
sizeof(id) +
sizeof(
info);
386 errs() <<
"could not open /proc/self/exe: " <<
EC.message() <<
"\n";
390 memcpy(&
id, (*MB)->getBufferStart(),
sizeof(
id));
391 memcpy(&
info, (*MB)->getBufferStart() +
sizeof(
id),
sizeof(
info));
394 if (
id[0] != 0x7f ||
id[1] !=
'E' ||
id[2] !=
'L' ||
id[3] !=
'F') {
395 errs() <<
"invalid elf signature\n";
399 hdr.ElfMach =
info.e_machine;
406 assert(SuccessfullyInitialized);
412 LLVMPerfJitRecordCodeLoad rec;
414 rec.Prefix.TotalSize =
sizeof(rec) +
417 rec.Prefix.Timestamp = perf_get_timestamp();
419 rec.CodeSize = CodeSize;
421 rec.CodeAddr = CodeAddr;
426 std::lock_guard<sys::Mutex> Guard(
Mutex);
428 rec.CodeIndex = CodeGeneration++;
430 Dumpstream->write(
reinterpret_cast<const char *
>(&rec),
sizeof(rec));
432 Dumpstream->write(
reinterpret_cast<const char *
>(CodeAddr), CodeSize);
435void PerfJITEventListener::NotifyDebug(
uint64_t CodeAddr,
437 assert(SuccessfullyInitialized);
443 LLVMPerfJitRecordDebugInfo rec;
445 rec.Prefix.TotalSize =
sizeof(rec);
446 rec.Prefix.Timestamp = perf_get_timestamp();
447 rec.CodeAddr = CodeAddr;
448 rec.NrEntry =
Lines.size();
455 rec.Prefix.TotalSize +=
sizeof(LLVMPerfJitDebugEntry);
456 rec.Prefix.TotalSize += line.
FileName.size() + 1;
468 std::lock_guard<sys::Mutex> Guard(
Mutex);
470 Dumpstream->write(
reinterpret_cast<const char *
>(&rec),
sizeof(rec));
473 LLVMPerfJitDebugEntry LineInfo;
476 LineInfo.Addr = It->first;
480 LineInfo.Addr += 0x40;
481 LineInfo.Lineno =
Line.Line;
482 LineInfo.Discrim =
Line.Discriminator;
484 Dumpstream->write(
reinterpret_cast<const char *
>(&LineInfo),
486 Dumpstream->write(
Line.FileName.c_str(),
Line.FileName.size() + 1);
496 static PerfJITEventListener PerfListener;
497 return &PerfListener;
#define LLVM_PERF_JIT_MAGIC
DILineInfoSpecifier::FileLineInfoKind FileLineInfoKind
#define LLVM_PERF_JIT_VERSION
Provides a library for accessing information about this process and other processes on the operating ...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static std::unique_ptr< DWARFContext > create(const object::ObjectFile &Obj, ProcessDebugRelocations RelocAction=ProcessDebugRelocations::Process, const LoadedObjectInfo *L=nullptr, std::string DWPName="", std::function< void(Error)> RecoverableErrorHandler=WithColor::defaultErrorHandler, std::function< void(Error)> WarningHandler=WithColor::defaultWarningHandler, bool ThreadSafe=false)
Represents either an error or a value T.
std::error_code getError() const
Tagged union holding either a T or a Error.
Error takeError()
Take ownership of the stored error.
JITEventListener - Abstract interface for use by the JIT to notify clients about significant events d...
virtual void notifyFreeingObject(ObjectKey K)
notifyFreeingObject - Called just before the memory associated with a previously emitted object is re...
virtual void notifyObjectLoaded(ObjectKey K, const object::ObjectFile &Obj, const RuntimeDyld::LoadedObjectInfo &L)
notifyObjectLoaded - Called after an object has had its sections allocated and addresses assigned to ...
static JITEventListener * createPerfJITEventListener()
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFileSlice(const Twine &Filename, uint64_t MapSize, uint64_t Offset, bool IsVolatile=false, std::optional< Align > Alignment=std::nullopt)
Map a subrange of the specified file as a MemoryBuffer.
Information about the loaded object.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
StringRef str() const
Explicit conversion to StringRef.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This class is the base class for all object file types.
virtual section_iterator section_end() const =0
This is a value type class that represents a single symbol in the list of symbols in the object file.
A raw_ostream that writes to an std::string.
A collection of legacy interfaces for querying information about the current executing process.
static unsigned getPageSizeEstimate()
Get the process's estimated page size.
LLVMJITEventListenerRef LLVMCreatePerfJITEventListener(void)
struct LLVMOpaqueJITEventListener * LLVMJITEventListenerRef
std::vector< std::pair< SymbolRef, uint64_t > > computeSymbolSizes(const ObjectFile &O)
@ JIT_CODE_UNWINDING_INFO
std::error_code openFileForReadWrite(const Twine &Name, int &ResultFD, CreationDisposition Disp, OpenFlags Flags, unsigned Mode=0666)
Opens the file with the given name in a write-only or read-write mode, returning its open file descri...
@ CD_CreateNew
CD_CreateNew - When opening a file:
std::error_code openFileForWrite(const Twine &Name, int &ResultFD, CreationDisposition Disp=CD_CreateAlways, OpenFlags Flags=OF_None, unsigned Mode=0666)
Opens the file with the given name in a write-only or read-write mode, returning its open file descri...
std::error_code create_directories(const Twine &path, bool IgnoreExisting=true, perms Perms=owner_all|group_all)
Create all the non-existent directories in path.
std::error_code createUniqueDirectory(const Twine &Prefix, SmallVectorImpl< char > &ResultPath)
bool home_directory(SmallVectorImpl< char > &result)
Get the user's home directory.
SmartMutex< false > Mutex
Mutex - A standard, always enforced mutex.
This is an optimization pass for GlobalISel generic memory operations.
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
uint64_t get_threadid()
Return the current thread id, as used in various OS system calls.
LLVMAttributeRef wrap(Attribute Attr)
void consumeError(Error Err)
Consume a Error without doing anything.
A format-neutral container for source line information.
static const uint64_t UndefSection