Debian Codegraph @

js/src/jit/PerfSpewer.cpp

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 #include "mozilla/IntegerPrintfMacros.h"
8 #include "mozilla/Printf.h"
9
10 #if defined(JS_ION_PERF) && defined(XP_UNIX)
11 # include <fcntl.h>
12 # include <sys/mman.h>
13 # include <sys/stat.h>
14 # include <unistd.h>
15 #endif
16
17 #if defined(JS_ION_PERF) && defined(XP_LINUX) && !defined(ANDROID) && \
18 defined(__GLIBC__)
19 # include <dlfcn.h>
20 # include <sys/syscall.h>
21 # include <sys/types.h>
22 # include <unistd.h>
23 # define gettid() static_cast<pid_t>(syscall(__NR_gettid))
24 #endif
25
26 #if defined(JS_ION_PERF) && (defined(ANDROID) || defined(XP_DARWIN))
27 # include <limits.h>
28 # include <stdlib.h>
29 # include <unistd.h>
30 char* get_current_dir_name() {
31 char* buffer = (char*)malloc(PATH_MAX * sizeof(char));
32 if (buffer == nullptr) {
33 return nullptr;
34 }
35
36 if (getcwd(buffer, PATH_MAX) == nullptr) {
37 free(buffer);
38 return nullptr;
39 }
40
41 return buffer;
42 }
43 #endif
44
45 #if defined(JS_ION_PERF) && defined(XP_DARWIN)
46 # include <pthread.h>
47 # include <unistd.h>
48
49 pid_t gettid_pthread() {
50 uint64_t tid;
51 if (pthread_threadid_np(nullptr, &tid) != 0) {
52 return 0;
53 }
54 // Truncate the tid to 32 bits. macOS thread IDs are usually small enough.
55 // And even if we do end up truncating, it doesn't matter much for Jitdump
56 // as long as the process ID is correct.
57 return pid_t(tid);
58 }
59 # define gettid() gettid_pthread()
60 #endif
61
62 #include "jit/PerfSpewer.h"
63
64 #include <atomic>
65
66 #include "jit/BaselineFrameInfo.h"
67 #include "jit/CacheIR.h"
68 #include "jit/Jitdump.h"
69 #include "jit/JitSpewer.h"
70 #include "jit/LIR.h"
71 #include "jit/MIR-wasm.h"
72 #include "jit/MIR.h"
73 #include "js/ColumnNumber.h" // JS::LimitedColumnNumberOneOrigin, JS::ColumnNumberOffset
74 #include "js/Printf.h"
75 #include "vm/BytecodeUtil.h"
76 #include "vm/MutexIDs.h"
77
78 #ifdef XP_WIN
79 # include "util/WindowsWrapper.h"
80 # include <codecvt>
81 # include <evntprov.h>
82 # include <locale>
83 # include <string>
84
85 const GUID PROVIDER_JSCRIPT9 = {
86 0x57277741,
87 0x3638,
88 0x4a4b,
89 {0xbd, 0xba, 0x0a, 0xc6, 0xe4, 0x5d, 0xa5, 0x6c}};
90 const EVENT_DESCRIPTOR MethodLoad = {0x9, 0x0, 0x0, 0x4, 0xa, 0x1, 0x1};
91
92 static REGHANDLE sETWRegistrationHandle = NULL;
93
94 static std::atomic<bool> etwCollection = false;
95 #endif
96
97 using namespace js;
98 using namespace js::jit;
99
100 enum class PerfModeType { None, Function, Source, IR, IROperands };
101
102 static std::atomic<bool> geckoProfiling = false;
103 static std::atomic<PerfModeType> PerfMode = PerfModeType::None;
104
105 // Mutex to guard access to the profiler vectors and jitdump file if perf
106 // profiling is enabled.
107 MOZ_RUNINIT static js::Mutex PerfMutex(mutexid::PerfSpewer);
108
109 #ifdef JS_ION_PERF
110 MOZ_RUNINIT static UniqueChars spew_dir;
111 static FILE* JitDumpFilePtr = nullptr;
112 static void* mmap_address = nullptr;
113 static bool IsPerfProfiling() { return JitDumpFilePtr != nullptr; }
114 #endif
115
116 AutoLockPerfSpewer::AutoLockPerfSpewer() { PerfMutex.lock(); }
117
118 AutoLockPerfSpewer::~AutoLockPerfSpewer() { PerfMutex.unlock(); }
119
120 #ifdef JS_ION_PERF
121 static uint64_t GetMonotonicTimestamp() {
122 using mozilla::TimeStamp;
123 # ifdef XP_LINUX
124 return TimeStamp::Now().RawClockMonotonicNanosecondsSinceBoot();
125 # elif XP_WIN
126 return TimeStamp::Now().RawQueryPerformanceCounterValue().value();
127 # elif XP_DARWIN
128 return TimeStamp::Now().RawMachAbsoluteTimeNanoseconds();
129 # else
130 MOZ_CRASH("no timestamp");
131 # endif
132 }
133
134 // values are from /usr/include/elf.h
135 static uint32_t GetMachineEncoding() {
136 # if defined(JS_CODEGEN_X86)
137 return 3; // EM_386
138 # elif defined(JS_CODEGEN_X64)
139 return 62; // EM_X86_64
140 # elif defined(JS_CODEGEN_ARM)
141 return 40; // EM_ARM
142 # elif defined(JS_CODEGEN_ARM64)
143 return 183; // EM_AARCH64
144 # elif defined(JS_CODEGEN_MIPS64)
145 return 8; // EM_MIPS
146 # else
147 return 0; // Unsupported
148 # endif
149 }
150
151 static void WriteToJitDumpFile(const void* addr, uint32_t size,
152 AutoLockPerfSpewer& lock) {
153 MOZ_RELEASE_ASSERT(JitDumpFilePtr);
154 size_t rv = fwrite(addr, 1, size, JitDumpFilePtr);
155 MOZ_RELEASE_ASSERT(rv == size);
156 }
157
158 static void WriteJitDumpDebugEntry(uint64_t addr, const char* filename,
159 uint32_t lineno,
160 JS::LimitedColumnNumberOneOrigin colno,
161 AutoLockPerfSpewer& lock) {
162 JitDumpDebugEntry entry = {addr, lineno, colno.oneOriginValue()};
163 WriteToJitDumpFile(&entry, sizeof(entry), lock);
164 WriteToJitDumpFile(filename, strlen(filename) + 1, lock);
165 }
166
167 static void writeJitDumpHeader(AutoLockPerfSpewer& lock) {
168 JitDumpHeader header = {};
169 header.magic = 0x4A695444;
170 header.version = 1;
171 header.total_size = sizeof(header);
172 header.elf_mach = GetMachineEncoding();
173 header.pad1 = 0;
174 header.pid = getpid();
175 header.timestamp = GetMonotonicTimestamp();
176 header.flags = 0;
177
178 WriteToJitDumpFile(&header, sizeof(header), lock);
179 }
180
181 static bool openJitDump() {
182 if (JitDumpFilePtr) {
183 return true;
184 }
185 AutoLockPerfSpewer lock;
186
187 const ssize_t bufferSize = 256;
188 char filenameBuffer[bufferSize];
189
190 // We want to write absolute filenames into the debug info or else we get the
191 // filenames in the perf report
192 if (getenv("PERF_SPEW_DIR")) {
193 char* env_dir = getenv("PERF_SPEW_DIR");
194 if (env_dir[0] == '/') {
195 spew_dir = JS_smprintf("%s", env_dir);
196 } else {
197 const char* dir = get_current_dir_name();
198 if (!dir) {
199 fprintf(stderr, "couldn't get current dir name\n");
200 return false;
201 }
202 spew_dir = JS_smprintf("%s/%s", dir, env_dir);
203 free((void*)dir);
204 }
205 } else {
206 fprintf(stderr, "Please define PERF_SPEW_DIR as an output directory.\n");
207 return false;
208 }
209
210 if (SprintfBuf(filenameBuffer, bufferSize, "%s/jit-%d.dump", spew_dir.get(),
211 getpid()) >= bufferSize) {
212 return false;
213 }
214
215 MOZ_ASSERT(!JitDumpFilePtr);
216
217 int fd = open(filenameBuffer, O_CREAT | O_TRUNC | O_RDWR, 0666);
218 JitDumpFilePtr = fdopen(fd, "w+");
219
220 if (!JitDumpFilePtr) {
221 return false;
222 }
223
224 # ifdef XP_LINUX
225 // We need to mmap the jitdump file for perf to find it.
226 long page_size = sysconf(_SC_PAGESIZE);
227 int prot = PROT_READ | PROT_EXEC;
228 // The mmap call fails on some Android devices if PROT_EXEC is specified, and
229 // it does not appear to be required by simpleperf, so omit it on Android.
230 # ifdef ANDROID
231 prot &= ~PROT_EXEC;
232 # endif
233 mmap_address = mmap(nullptr, page_size, prot, MAP_PRIVATE, fd, 0);
234 if (mmap_address == MAP_FAILED) {
235 PerfMode = PerfModeType::None;
236 return false;
237 }
238 # endif
239
240 writeJitDumpHeader(lock);
241 return true;
242 }
243
244 static void CheckPerf() {
245 static bool PerfChecked = false;
246
247 if (!PerfChecked) {
248 const char* env = getenv("IONPERF");
249 if (env == nullptr) {
250 PerfMode = PerfModeType::None;
251 } else if (!strcmp(env, "src")) {
252 PerfMode = PerfModeType::Source;
253 } else if (!strcmp(env, "ir")) {
254 PerfMode = PerfModeType::IR;
255 } else if (!strcmp(env, "ir-ops")) {
256 # ifdef JS_JITSPEW
257 PerfMode = PerfModeType::IROperands;
258 # else
259 fprintf(stderr,
260 "Warning: IONPERF=ir-ops requires --enable-jitspew to be "
261 "enabled, defaulting to IONPERF=ir\n");
262 PerfMode = PerfModeType::IR;
263 # endif
264 } else if (!strcmp(env, "func")) {
265 PerfMode = PerfModeType::Function;
266 } else {
267 fprintf(stderr, "Use IONPERF=func to record at function granularity\n");
268 fprintf(stderr,
269 "Use IONPERF=ir to record and annotate assembly with IR\n");
270 fprintf(stderr,
271 "Use IONPERF=src to record and annotate assembly with source, if "
272 "available locally\n");
273 exit(0);
274 }
275
276 if (PerfMode != PerfModeType::None) {
277 if (openJitDump()) {
278 PerfChecked = true;
279 return;
280 }
281
282 fprintf(stderr, "Failed to open perf map file. Disabling IONPERF.\n");
283 PerfMode = PerfModeType::None;
284 }
285 PerfChecked = true;
286 }
287 }
288 #endif
289
290 #ifdef XP_WIN
291 void NTAPI ETWEnableCallback(LPCGUID aSourceId, ULONG aIsEnabled, UCHAR aLevel,
292 ULONGLONG aMatchAnyKeyword,
293 ULONGLONG aMatchAllKeyword,
294 PEVENT_FILTER_DESCRIPTOR aFilterData,
295 PVOID aCallbackContext) {
296 // This is called on a CRT worker thread. This means this might race with
297 // our main thread, but that is okay.
298 etwCollection = aIsEnabled;
299 PerfMode = aIsEnabled ? PerfModeType::Function : PerfModeType::None;
300 }
301
302 void RegisterETW() {
303 static bool sHasRegisteredETW = false;
304 if (!sHasRegisteredETW) {
305 if (getenv("ETW_ENABLED")) {
306 EventRegister(&PROVIDER_JSCRIPT9, // GUID that identifies the provider
307 ETWEnableCallback, // Callback for enabling collection
308 NULL, // Context not used
309 &sETWRegistrationHandle // Used when calling EventWrite
310 // and EventUnregister
311 );
312 }
313 sHasRegisteredETW = true;
314 }
315 }
316 #endif
317
318 /* static */
319 void PerfSpewer::Init() {
320 #ifdef JS_ION_PERF
321 CheckPerf();
322 #endif
323 #ifdef XP_WIN
324 RegisterETW();
325 #endif
326 }
327
328 static void DisablePerfSpewer(AutoLockPerfSpewer& lock) {
329 fprintf(stderr, "Warning: Disabling PerfSpewer.");
330
331 geckoProfiling = false;
332 #ifdef XP_WIN
333 etwCollection = false;
334 #endif
335 PerfMode = PerfModeType::None;
336 #ifdef JS_ION_PERF
337 long page_size = sysconf(_SC_PAGESIZE);
338 munmap(mmap_address, page_size);
339 fclose(JitDumpFilePtr);
340 JitDumpFilePtr = nullptr;
341 #endif
342 }
343
344 static void DisablePerfSpewer() {
345 AutoLockPerfSpewer lock;
346 DisablePerfSpewer(lock);
347 }
348
349 static bool PerfSrcEnabled() {
350 return PerfMode == PerfModeType::Source || geckoProfiling;
351 }
352
353 #ifdef JS_JITSPEW
354 static bool PerfIROpsEnabled() { return PerfMode == PerfModeType::IROperands; }
355 #endif
356
357 static bool PerfIREnabled() {
358 return (PerfMode == PerfModeType::IROperands) ||
359 (PerfMode == PerfModeType::IR) || geckoProfiling;
360 }
361
362 static bool PerfFuncEnabled() {
363 return PerfMode == PerfModeType::Function || geckoProfiling;
364 }
365
366 bool js::jit::PerfEnabled() {
367 return PerfSrcEnabled() || PerfIREnabled() || PerfFuncEnabled();
368 }
369
370 void InlineCachePerfSpewer::recordInstruction(MacroAssembler& masm,
371 const CacheOp& op) {
372 if (!PerfIREnabled()) {
373 return;
374 }
375 AutoLockPerfSpewer lock;
376
377 if (!opcodes_.emplaceBack(masm.currentOffset() - startOffset_,
378 static_cast<uint32_t>(op))) {
379 opcodes_.clear();
380 DisablePerfSpewer(lock);
381 }
382 }
383
384 #define CHECK_RETURN(x) \
385 if (!(x)) { \
386 DisablePerfSpewer(); \
387 return; \
388 }
389
390 void IonPerfSpewer::recordInstruction(MacroAssembler& masm, LInstruction* ins) {
391 if (!PerfIREnabled() && !PerfSrcEnabled()) {
392 return;
393 }
394
395 LNode::Opcode op = ins->op();
396 UniqueChars opcodeStr;
397
398 jsbytecode* bytecodepc = nullptr;
399 if (MDefinition* mir = ins->mirRaw()) {
400 bytecodepc = mir->trackedSite()->pc();
401 }
402
403 #ifdef JS_JITSPEW
404 if (PerfIROpsEnabled()) {
405 Sprinter buf;
406 CHECK_RETURN(buf.init());
407 buf.put(LIRCodeName(op));
408 ins->printOperands(buf);
409 opcodeStr = buf.release();
410 }
411 #endif
412 if (!opcodes_.emplaceBack(masm.currentOffset() - startOffset_,
413 static_cast<uint32_t>(op), opcodeStr, bytecodepc)) {
414 opcodes_.clear();
415 DisablePerfSpewer();
416 }
417 }
418
419 #ifdef JS_JITSPEW
420 static void PrintStackValue(JSContext* maybeCx, StackValue* stackVal,
421 CompilerFrameInfo& frame, Sprinter& buf) {
422 switch (stackVal->kind()) {
423 /****** Constant ******/
424 case StackValue::Constant: {
425 js::Value constantVal = stackVal->constant();
426 if (constantVal.isInt32()) {
427 buf.printf("%d", constantVal.toInt32());
428 } else if (constantVal.isObjectOrNull()) {
429 buf.printf("obj:%p", constantVal.toObjectOrNull());
430 } else if (constantVal.isString()) {
431 if (maybeCx) {
432 buf.put("str:");
433 buf.putString(maybeCx, constantVal.toString());
434 } else {
435 buf.put("str");
436 }
437 } else if (constantVal.isNumber()) {
438 buf.printf("num:%f", constantVal.toNumber());
439 } else if (constantVal.isSymbol()) {
440 if (maybeCx) {
441 buf.put("sym:");
442 constantVal.toSymbol()->dump(buf);
443 } else {
444 buf.put("sym");
445 }
446 } else {
447 buf.printf("raw:%" PRIx64, constantVal.asRawBits());
448 }
449 } break;
450 /****** Register ******/
451 case StackValue::Register: {
452 Register reg = stackVal->reg().payloadOrValueReg();
453 buf.put(reg.name());
454 } break;
455 /****** Stack ******/
456 case StackValue::Stack:
457 buf.put("stack");
458 break;
459 /****** ThisSlot ******/
460 case StackValue::ThisSlot: {
461 # ifdef JS_HAS_HIDDEN_SP
462 buf.put("this");
463 # else
464 Address addr = frame.addressOfThis();
465 buf.printf("this:%s(%d)", addr.base.name(), addr.offset);
466 # endif
467 } break;
468 /****** LocalSlot ******/
469 case StackValue::LocalSlot:
470 buf.printf("local:%u", stackVal->localSlot());
471 break;
472 /****** ArgSlot ******/
473 case StackValue::ArgSlot:
474 buf.printf("arg:%u", stackVal->argSlot());
475 break;
476
477 default:
478 MOZ_CRASH("Unexpected kind");
479 break;
480 }
481 }
482 #endif
483
484 [[nodiscard]] bool WasmBaselinePerfSpewer::needsToRecordInstruction() const {
485 return PerfIREnabled() || PerfSrcEnabled();
486 }
487
488 void WasmBaselinePerfSpewer::recordInstruction(MacroAssembler& masm,
489 const wasm::OpBytes& op) {
490 MOZ_ASSERT(needsToRecordInstruction());
491
492 if (!opcodes_.emplaceBack(masm.currentOffset() - startOffset_,
493 op.toPacked())) {
494 opcodes_.clear();
495 DisablePerfSpewer();
496 }
497 }
498
499 void BaselinePerfSpewer::recordInstruction(MacroAssembler& masm, jsbytecode* pc,
500 CompilerFrameInfo& frame) {
501 if (!PerfIREnabled() && !PerfSrcEnabled()) {
502 return;
503 }
504
505 JSOp op = JSOp(*pc);
506 UniqueChars opcodeStr;
507
508 #ifdef JS_JITSPEW
509 if (PerfIROpsEnabled()) {
510 JSScript* script = frame.script;
511 unsigned numOperands = js::StackUses(op, pc);
512
513 JSContext* maybeCx = TlsContext.get();
514 Sprinter buf(maybeCx);
515 CHECK_RETURN(buf.init());
516 buf.put(js::CodeName(op));
517
518 if (maybeCx) {
519 switch (op) {
520 case JSOp::SetName:
521 case JSOp::SetGName:
522 case JSOp::BindName:
523 case JSOp::BindUnqualifiedName:
524 case JSOp::BindUnqualifiedGName:
525 case JSOp::GetName:
526 case JSOp::GetGName: {
527 // Emit the name used for these ops
528 Rooted<PropertyName*> name(maybeCx, script->getName(pc));
529 buf.put(" ");
530 buf.putString(maybeCx, name);
531 } break;
532 default:
533 break;
534 }
535
536 // Output should be "JSOp (operand1), (operand2), ..."
537 for (unsigned i = 1; i <= numOperands; i++) {
538 buf.put(" (");
539 StackValue* stackVal = frame.peek(-int(i));
540 PrintStackValue(maybeCx, stackVal, frame, buf);
541
542 if (i < numOperands) {
543 buf.put("),");
544 } else {
545 buf.put(")");
546 }
547 }
548 }
549 opcodeStr = buf.release();
550 }
551 #endif
552
553 if (!opcodes_.emplaceBack(masm.currentOffset() - startOffset_,
554 static_cast<uint32_t>(op), opcodeStr, pc)) {
555 opcodes_.clear();
556 DisablePerfSpewer();
557 }
558 }
559
560 const char* BaselinePerfSpewer::CodeName(uint32_t op) {
561 return js::CodeName(static_cast<JSOp>(op));
562 }
563
564 const char* BaselineInterpreterPerfSpewer::CodeName(uint32_t op) {
565 return js::CodeName(static_cast<JSOp>(op));
566 }
567
568 const char* IonPerfSpewer::CodeName(uint32_t op) {
569 return js::jit::LIRCodeName(static_cast<LNode::Opcode>(op));
570 }
571
572 const char* WasmBaselinePerfSpewer::CodeName(uint32_t op) {
573 return wasm::OpBytes::fromPacked(op).toString();
574 }
575
576 const char* InlineCachePerfSpewer::CodeName(uint32_t op) {
577 return js::jit::CacheIRCodeName(static_cast<CacheOp>(op));
578 }
579
580 void PerfSpewer::CollectJitCodeInfo(UniqueChars& function_name, JitCode* code,
581 AutoLockPerfSpewer& lock) {
582 CollectJitCodeInfo(function_name, reinterpret_cast<void*>(code->raw()),
583 code->instructionsSize(), lock);
584 }
585
586 void PerfSpewer::CollectJitCodeInfo(UniqueChars& function_name, void* code_addr,
587 uint64_t code_size,
588 AutoLockPerfSpewer& lock) {
589 #ifdef JS_ION_PERF
590 static uint64_t codeIndex = 1;
591
592 if (IsPerfProfiling()) {
593 JitDumpLoadRecord record = {};
594
595 record.header.id = JIT_CODE_LOAD;
596 record.header.total_size =
597 sizeof(record) + strlen(function_name.get()) + 1 + code_size;
598 record.header.timestamp = GetMonotonicTimestamp();
599 record.pid = getpid();
600 record.tid = gettid();
601 record.vma = uint64_t(code_addr);
602 record.code_addr = uint64_t(code_addr);
603 record.code_size = code_size;
604 record.code_index = codeIndex++;
605
606 WriteToJitDumpFile(&record, sizeof(record), lock);
607 WriteToJitDumpFile(function_name.get(), strlen(function_name.get()) + 1,
608 lock);
609 WriteToJitDumpFile(code_addr, code_size, lock);
610 }
611 #endif
612 #ifdef XP_WIN
613 if (etwCollection) {
614 void* scriptContextId = NULL;
615 uint32_t flags = 0;
616 uint64_t map = 0;
617 uint64_t assembly = 0;
618 uint32_t line_col = 0;
619 uint32_t method = 0;
620
621 int name_len = strlen(function_name.get());
622 std::wstring name(name_len + 1, '\0');
623 if (MultiByteToWideChar(CP_UTF8, 0, function_name.get(), name_len,
624 name.data(), name.size()) == 0) {
625 DisablePerfSpewer(lock);
626 return;
627 }
628
629 EVENT_DATA_DESCRIPTOR EventData[10];
630
631 EventDataDescCreate(&EventData[0], &scriptContextId, sizeof(PVOID));
632 EventDataDescCreate(&EventData[1], &code_addr, sizeof(PVOID));
633 EventDataDescCreate(&EventData[2], &code_size, sizeof(unsigned __int64));
634 EventDataDescCreate(&EventData[3], &method, sizeof(uint32_t));
635 EventDataDescCreate(&EventData[4], &flags, sizeof(const unsigned short));
636 EventDataDescCreate(&EventData[5], &map, sizeof(const unsigned short));
637 EventDataDescCreate(&EventData[6], &assembly, sizeof(unsigned __int64));
638 EventDataDescCreate(&EventData[7], &line_col, sizeof(const unsigned int));
639 EventDataDescCreate(&EventData[8], &line_col, sizeof(const unsigned int));
640 EventDataDescCreate(&EventData[9], name.c_str(),
641 sizeof(wchar_t) * (name.length() + 1));
642
643 ULONG result = EventWrite(
644 sETWRegistrationHandle, // From EventRegister
645 &MethodLoad, // EVENT_DESCRIPTOR generated from the manifest
646 (ULONG)10, // Size of the array of EVENT_DATA_DESCRIPTORs
647 EventData // Array of descriptors that contain the event data
648 );
649
650 if (result != ERROR_SUCCESS) {
651 DisablePerfSpewer(lock);
652 return;
653 }
654 }
655 #endif
656 }
657
658 void PerfSpewer::recordOffset(MacroAssembler& masm, const char* msg) {
659 if (!PerfIREnabled()) {
660 return;
661 }
662
663 UniqueChars offsetStr = DuplicateString(msg);
664 if (!opcodes_.emplaceBack(masm.currentOffset() - startOffset_, offsetStr)) {
665 opcodes_.clear();
666 DisablePerfSpewer();
667 }
668 }
669
670 void PerfSpewer::saveIRInfo(uintptr_t base, AutoLockPerfSpewer& lock) {
671 #ifdef JS_ION_PERF
672 static uint32_t filenameCounter = 0;
673 UniqueChars scriptFilename;
674 FILE* scriptFile = nullptr;
675
676 if (!IsPerfProfiling()) {
677 return;
678 }
679
680 scriptFilename = JS_smprintf("%s/jitdump-script-%u.%u.txt", spew_dir.get(),
681 filenameCounter++, getpid());
682 scriptFile = fopen(scriptFilename.get(), "w");
683 if (!scriptFile) {
684 DisablePerfSpewer(lock);
685 return;
686 }
687
688 JitDumpDebugRecord debug_record = {};
689 uint64_t n_records = opcodes_.length();
690
691 debug_record.header.id = JIT_CODE_DEBUG_INFO;
692 debug_record.header.total_size =
693 sizeof(debug_record) + n_records * (sizeof(JitDumpDebugEntry) +
694 strlen(scriptFilename.get()) + 1);
695 debug_record.header.timestamp = GetMonotonicTimestamp();
696 debug_record.code_addr = uint64_t(base);
697 debug_record.nr_entry = n_records;
698
699 WriteToJitDumpFile(&debug_record, sizeof(debug_record), lock);
700
701 for (size_t i = 0; i < opcodes_.length(); i++) {
702 OpcodeEntry& entry = opcodes_[i];
703 // If a string was recorded for this offset, use that instead.
704 if (entry.str) {
705 fprintf(scriptFile, "%s\n", entry.str.get());
706 } else {
707 fprintf(scriptFile, "%s\n", CodeName(entry.opcode));
708 }
709 uint64_t addr = uint64_t(base) + entry.offset;
710 uint64_t lineno = i + 1;
711 WriteJitDumpDebugEntry(addr, scriptFilename.get(), lineno,
712 JS::LimitedColumnNumberOneOrigin(), lock);
713 }
714
715 opcodes_.clear();
716 fclose(scriptFile);
717 #endif
718 }
719
720 void PerfSpewer::saveJitCodeSourceInfo(JSScript* script, JitCode* code,
721 AutoLockPerfSpewer& lock) {
722 #ifdef JS_ION_PERF
723 if (IsPerfProfiling()) {
724 const char* filename = script->filename();
725 if (!filename) {
726 return;
727 }
728
729 JitDumpDebugRecord debug_record = {};
730
731 uint64_t n_records = 0;
732 for (OpcodeEntry& entry : opcodes_) {
733 if (entry.bytecodepc) {
734 n_records++;
735 }
736 }
737
738 debug_record.header.id = JIT_CODE_DEBUG_INFO;
739 debug_record.header.total_size =
740 sizeof(debug_record) +
741 n_records * (sizeof(JitDumpDebugEntry) + strlen(filename) + 1);
742 debug_record.header.timestamp = GetMonotonicTimestamp();
743 debug_record.code_addr = uint64_t(code->raw());
744 debug_record.nr_entry = n_records;
745
746 WriteToJitDumpFile(&debug_record, sizeof(debug_record), lock);
747
748 uint32_t lineno = 0;
749 JS::LimitedColumnNumberOneOrigin colno;
750
751 for (OpcodeEntry& entry : opcodes_) {
752 jsbytecode* pc = entry.bytecodepc;
753 if (!pc) {
754 continue;
755 }
756 // We could probably make this a bit faster by caching the previous pc
757 // offset, but it currently doesn't seem noticeable when testing.
758 lineno = PCToLineNumber(script, pc, &colno);
759
760 WriteJitDumpDebugEntry(uint64_t(code->raw()) + entry.offset, filename,
761 lineno, colno, lock);
762 }
763 }
764 #endif
765 }
766
767 static UniqueChars GetFunctionDesc(const char* tierName, JSContext* cx,
768 JSScript* script,
769 const char* stubName = nullptr) {
770 MOZ_ASSERT(script && tierName && cx);
771 UniqueChars funName;
772 if (script->function() && script->function()->maybePartialDisplayAtom()) {
773 funName = AtomToPrintableString(
774 cx, script->function()->maybePartialDisplayAtom());
775 }
776
777 if (stubName) {
778 return JS_smprintf("%s: %s : %s (%s:%u:%u)", tierName, stubName,
779 funName ? funName.get() : "*", script->filename(),
780 script->lineno(), script->column().oneOriginValue());
781 }
782 return JS_smprintf("%s: %s (%s:%u:%u)", tierName,
783 funName ? funName.get() : "*", script->filename(),
784 script->lineno(), script->column().oneOriginValue());
785 }
786
787 void PerfSpewer::saveJitCodeDebugInfo(JSScript* script, JitCode* code,
788 AutoLockPerfSpewer& lock) {
789 MOZ_ASSERT(code);
790 if (PerfIREnabled()) {
791 saveIRInfo(uintptr_t(code->raw()), lock);
792 } else if (PerfSrcEnabled() && script) {
793 saveJitCodeSourceInfo(script, code, lock);
794 }
795 }
796
797 void PerfSpewer::saveWasmCodeDebugInfo(uintptr_t base,
798 AutoLockPerfSpewer& lock) {
799 if (PerfIREnabled()) {
800 saveIRInfo(base, lock);
801 }
802 }
803
804 void PerfSpewer::saveJSProfile(JitCode* code, UniqueChars& desc,
805 JSScript* script) {
806 MOZ_ASSERT(PerfEnabled());
807 MOZ_ASSERT(code && desc);
808 AutoLockPerfSpewer lock;
809
810 saveJitCodeDebugInfo(script, code, lock);
811 CollectJitCodeInfo(desc, code, lock);
812 }
813
814 void PerfSpewer::saveWasmProfile(uintptr_t base, size_t size,
815 UniqueChars& desc) {
816 MOZ_ASSERT(PerfEnabled());
817 MOZ_ASSERT(desc);
818 AutoLockPerfSpewer lock;
819
820 saveWasmCodeDebugInfo(base, lock);
821 PerfSpewer::CollectJitCodeInfo(desc, reinterpret_cast<void*>(base),
822 uint64_t(size), lock);
823 }
824
825 IonICPerfSpewer::IonICPerfSpewer(jsbytecode* pc) {
826 if (!PerfEnabled()) {
827 return;
828 }
829
830 if (!opcodes_.emplaceBack(pc)) {
831 opcodes_.clear();
832 DisablePerfSpewer();
833 }
834 }
835
836 void IonICPerfSpewer::saveJitCodeSourceInfo(JSScript* script, JitCode* code,
837 AutoLockPerfSpewer& lock) {
838 #ifdef JS_ION_PERF
839 if (!IsPerfProfiling()) {
840 return;
841 }
842
843 MOZ_ASSERT(script && code);
844 MOZ_ASSERT(opcodes_.length() == 1);
845 jsbytecode* pc = opcodes_[0].bytecodepc;
846
847 if (!pc) {
848 return;
849 }
850
851 const char* filename = script->filename();
852 if (!filename) {
853 return;
854 }
855
856 JitDumpDebugRecord debug_record = {};
857 uint64_t n_records = 1;
858
859 debug_record.header.id = JIT_CODE_DEBUG_INFO;
860 debug_record.header.total_size =
861 sizeof(debug_record) +
862 n_records * (sizeof(JitDumpDebugEntry) + strlen(filename) + 1);
863
864 debug_record.header.timestamp = GetMonotonicTimestamp();
865 debug_record.code_addr = uint64_t(code->raw());
866 debug_record.nr_entry = n_records;
867
868 WriteToJitDumpFile(&debug_record, sizeof(debug_record), lock);
869
870 uint32_t lineno;
871 JS::LimitedColumnNumberOneOrigin colno;
872 lineno = PCToLineNumber(script, pc, &colno);
873
874 WriteJitDumpDebugEntry(uint64_t(code->raw()), filename, lineno, colno, lock);
875 #endif
876 }
877
878 void IonICPerfSpewer::saveProfile(JSContext* cx, JSScript* script,
879 JitCode* code, const char* stubName) {
880 if (!PerfEnabled()) {
881 return;
882 }
883 UniqueChars desc = GetFunctionDesc("IonIC", cx, script, stubName);
884 PerfSpewer::saveJSProfile(code, desc, script);
885 }
886
887 void BaselineICPerfSpewer::saveProfile(JitCode* code, const char* stubName) {
888 if (!PerfEnabled()) {
889 return;
890 }
891 UniqueChars desc = JS_smprintf("BaselineIC: %s", stubName);
892 PerfSpewer::saveJSProfile(code, desc, nullptr);
893 }
894
895 void BaselinePerfSpewer::saveProfile(JSContext* cx, JSScript* script,
896 JitCode* code) {
897 if (!PerfEnabled()) {
898 return;
899 }
900 UniqueChars desc = GetFunctionDesc("Baseline", cx, script);
901 PerfSpewer::saveJSProfile(code, desc, script);
902 }
903
904 void BaselineInterpreterPerfSpewer::saveProfile(JitCode* code) {
905 if (!PerfEnabled()) {
906 return;
907 }
908
909 enum class SpewKind { Uninitialized, SingleSym, MultiSym };
910
911 // Check which type of Baseline Interpreter Spew is requested.
912 static SpewKind kind = SpewKind::Uninitialized;
913 if (kind == SpewKind::Uninitialized) {
914 if (getenv("IONPERF_SINGLE_BLINTERP")) {
915 kind = SpewKind::SingleSym;
916 } else {
917 kind = SpewKind::MultiSym;
918 }
919 }
920
921 // For SingleSym, just emit one "BaselineInterpreter" symbol
922 // and emit the opcodes as IR if IONPERF=ir is used.
923 if (kind == SpewKind::SingleSym) {
924 UniqueChars desc = DuplicateString("BaselineInterpreter");
925 PerfSpewer::saveJSProfile(code, desc, nullptr);
926 return;
927 }
928
929 // For MultiSym, split up each opcode into its own symbol.
930 // No IR is emitted in this case, so we can skip PerfSpewer::saveProfile.
931 MOZ_ASSERT(kind == SpewKind::MultiSym);
932 for (size_t i = 1; i < opcodes_.length(); i++) {
933 uintptr_t base = uintptr_t(code->raw()) + opcodes_[i - 1].offset;
934 uintptr_t size = opcodes_[i].offset - opcodes_[i - 1].offset;
935
936 UniqueChars rangeName;
937 if (opcodes_[i - 1].str) {
938 rangeName = JS_smprintf("BlinterpOp: %s", opcodes_[i - 1].str.get());
939 } else {
940 rangeName =
941 JS_smprintf("BlinterpOp: %s", CodeName(opcodes_[i - 1].opcode));
942 }
943
944 // If rangeName is empty, we probably went OOM.
945 if (!rangeName) {
946 DisablePerfSpewer();
947 return;
948 }
949
950 MOZ_ASSERT(base + size <=
951 uintptr_t(code->raw()) + code->instructionsSize());
952 CollectPerfSpewerJitCodeProfile(base, size, rangeName.get());
953 }
954 }
955
956 void BaselineInterpreterPerfSpewer::recordOffset(MacroAssembler& masm,
957 const JSOp& op) {
958 if (!PerfEnabled()) {
959 return;
960 }
961
962 if (!opcodes_.emplaceBack(masm.currentOffset() - startOffset_,
963 unsigned(op))) {
964 opcodes_.clear();
965 DisablePerfSpewer();
966 }
967 }
968
969 void BaselineInterpreterPerfSpewer::recordOffset(MacroAssembler& masm,
970 const char* name) {
971 if (!PerfEnabled()) {
972 return;
973 }
974
975 UniqueChars desc = DuplicateString(name);
976 if (!opcodes_.emplaceBack(masm.currentOffset() - startOffset_, desc)) {
977 opcodes_.clear();
978 DisablePerfSpewer();
979 }
980 }
981
982 void IonPerfSpewer::saveJSProfile(JSContext* cx, JSScript* script,
983 JitCode* code) {
984 if (!PerfEnabled()) {
985 return;
986 }
987 UniqueChars desc = GetFunctionDesc("Ion", cx, script);
988 PerfSpewer::saveJSProfile(code, desc, script);
989 }
990
991 void IonPerfSpewer::saveWasmProfile(uintptr_t codeBase, size_t codeSize,
992 UniqueChars& desc) {
993 if (!PerfEnabled()) {
994 return;
995 }
996 PerfSpewer::saveWasmProfile(codeBase, codeSize, desc);
997 }
998
999 void WasmBaselinePerfSpewer::saveProfile(uintptr_t codeBase, size_t codeSize,
1000 UniqueChars& desc) {
1001 if (!PerfEnabled()) {
1002 return;
1003 }
1004 PerfSpewer::saveWasmProfile(codeBase, codeSize, desc);
1005 }
1006
1007 void js::jit::CollectPerfSpewerJitCodeProfile(JitCode* code, const char* msg) {
1008 if (!code || !PerfEnabled()) {
1009 return;
1010 }
1011
1012 size_t size = code->instructionsSize();
1013 if (size > 0) {
1014 AutoLockPerfSpewer lock;
1015
1016 UniqueChars desc = JS_smprintf("%s", msg);
1017 PerfSpewer::CollectJitCodeInfo(desc, code, lock);
1018 }
1019 }
1020
1021 void js::jit::CollectPerfSpewerJitCodeProfile(uintptr_t base, uint64_t size,
1022 const char* msg) {
1023 if (!PerfEnabled()) {
1024 return;
1025 }
1026
1027 if (size > 0) {
1028 AutoLockPerfSpewer lock;
1029
1030 UniqueChars desc = JS_smprintf("%s", msg);
1031 PerfSpewer::CollectJitCodeInfo(desc, reinterpret_cast<void*>(base), size,
1032 lock);
1033 }
1034 }
1035
1036 void js::jit::CollectPerfSpewerWasmMap(uintptr_t base, uintptr_t size,
1037 UniqueChars&& desc) {
1038 if (size == 0U || !PerfEnabled()) {
1039 return;
1040 }
1041 AutoLockPerfSpewer lock;
1042
1043 PerfSpewer::CollectJitCodeInfo(desc, reinterpret_cast<void*>(base),
1044 uint64_t(size), lock);
1045 }
1046
1047 void js::jit::PerfSpewerRangeRecorder::appendEntry(UniqueChars& desc) {
1048 if (!ranges.append(std::make_pair(masm.currentOffset(), std::move(desc)))) {
1049 DisablePerfSpewer();
1050 ranges.clear();
1051 }
1052 }
1053
1054 void js::jit::PerfSpewerRangeRecorder::recordOffset(const char* name) {
1055 if (!PerfEnabled()) {
1056 return;
1057 }
1058 UniqueChars desc = DuplicateString(name);
1059 appendEntry(desc);
1060 }
1061
1062 void js::jit::PerfSpewerRangeRecorder::recordVMWrapperOffset(const char* name) {
1063 if (!PerfEnabled()) {
1064 return;
1065 }
1066
1067 UniqueChars desc = JS_smprintf("VMWrapper: %s", name);
1068 appendEntry(desc);
1069 }
1070
1071 void js::jit::PerfSpewerRangeRecorder::recordOffset(const char* name,
1072 JSContext* cx,
1073 JSScript* script) {
1074 if (!PerfEnabled()) {
1075 return;
1076 }
1077 UniqueChars desc = GetFunctionDesc(name, cx, script);
1078 appendEntry(desc);
1079 }
1080
1081 void js::jit::PerfSpewerRangeRecorder::collectRangesForJitCode(JitCode* code) {
1082 if (!PerfEnabled() || ranges.empty()) {
1083 return;
1084 }
1085
1086 uintptr_t basePtr = uintptr_t(code->raw());
1087 uintptr_t offsetStart = 0;
1088
1089 for (OffsetPair& pair : ranges) {
1090 uint32_t offsetEnd = std::get<0>(pair);
1091 uintptr_t rangeSize = uintptr_t(offsetEnd - offsetStart);
1092 const char* rangeName = std::get<1>(pair).get();
1093
1094 CollectPerfSpewerJitCodeProfile(basePtr + offsetStart, rangeSize,
1095 rangeName);
1096 offsetStart = offsetEnd;
1097 }
1098
1099 MOZ_ASSERT(offsetStart <= code->instructionsSize());
1100 ranges.clear();
1101 }