rustc_data_structures/
profiling.rs

1//! # Rust Compiler Self-Profiling
2//!
3//! This module implements the basic framework for the compiler's self-
4//! profiling support. It provides the `SelfProfiler` type which enables
5//! recording "events". An event is something that starts and ends at a given
6//! point in time and has an ID and a kind attached to it. This allows for
7//! tracing the compiler's activity.
8//!
9//! Internally this module uses the custom tailored [measureme][mm] crate for
10//! efficiently recording events to disk in a compact format that can be
11//! post-processed and analyzed by the suite of tools in the `measureme`
12//! project. The highest priority for the tracing framework is on incurring as
13//! little overhead as possible.
14//!
15//!
16//! ## Event Overview
17//!
18//! Events have a few properties:
19//!
20//! - The `event_kind` designates the broad category of an event (e.g. does it
21//!   correspond to the execution of a query provider or to loading something
22//!   from the incr. comp. on-disk cache, etc).
23//! - The `event_id` designates the query invocation or function call it
24//!   corresponds to, possibly including the query key or function arguments.
25//! - Each event stores the ID of the thread it was recorded on.
26//! - The timestamp stores beginning and end of the event, or the single point
27//!   in time it occurred at for "instant" events.
28//!
29//!
30//! ## Event Filtering
31//!
32//! Event generation can be filtered by event kind. Recording all possible
33//! events generates a lot of data, much of which is not needed for most kinds
34//! of analysis. So, in order to keep overhead as low as possible for a given
35//! use case, the `SelfProfiler` will only record the kinds of events that
36//! pass the filter specified as a command line argument to the compiler.
37//!
38//!
39//! ## `event_id` Assignment
40//!
41//! As far as `measureme` is concerned, `event_id`s are just strings. However,
42//! it would incur too much overhead to generate and persist each `event_id`
43//! string at the point where the event is recorded. In order to make this more
44//! efficient `measureme` has two features:
45//!
46//! - Strings can share their content, so that re-occurring parts don't have to
47//!   be copied over and over again. One allocates a string in `measureme` and
48//!   gets back a `StringId`. This `StringId` is then used to refer to that
49//!   string. `measureme` strings are actually DAGs of string components so that
50//!   arbitrary sharing of substrings can be done efficiently. This is useful
51//!   because `event_id`s contain lots of redundant text like query names or
52//!   def-path components.
53//!
54//! - `StringId`s can be "virtual" which means that the client picks a numeric
55//!   ID according to some application-specific scheme and can later make that
56//!   ID be mapped to an actual string. This is used to cheaply generate
57//!   `event_id`s while the events actually occur, causing little timing
58//!   distortion, and then later map those `StringId`s, in bulk, to actual
59//!   `event_id` strings. This way the largest part of the tracing overhead is
60//!   localized to one contiguous chunk of time.
61//!
62//! How are these `event_id`s generated in the compiler? For things that occur
63//! infrequently (e.g. "generic activities"), we just allocate the string the
64//! first time it is used and then keep the `StringId` in a hash table. This
65//! is implemented in `SelfProfiler::get_or_alloc_cached_string()`.
66//!
67//! For queries it gets more interesting: First we need a unique numeric ID for
68//! each query invocation (the `QueryInvocationId`). This ID is used as the
69//! virtual `StringId` we use as `event_id` for a given event. This ID has to
70//! be available both when the query is executed and later, together with the
71//! query key, when we allocate the actual `event_id` strings in bulk.
72//!
73//! We could make the compiler generate and keep track of such an ID for each
74//! query invocation but luckily we already have something that fits all the
75//! the requirements: the query's `DepNodeIndex`. So we use the numeric value
76//! of the `DepNodeIndex` as `event_id` when recording the event and then,
77//! just before the query context is dropped, we walk the entire query cache
78//! (which stores the `DepNodeIndex` along with the query key for each
79//! invocation) and allocate the corresponding strings together with a mapping
80//! for `DepNodeIndex as StringId`.
81//!
82//! [mm]: https://github.com/rust-lang/measureme/
83
84use std::borrow::Borrow;
85use std::collections::hash_map::Entry;
86use std::error::Error;
87use std::fmt::Display;
88use std::intrinsics::unlikely;
89use std::path::Path;
90use std::sync::Arc;
91use std::time::{Duration, Instant};
92use std::{fs, process};
93
94pub use measureme::EventId;
95use measureme::{EventIdBuilder, Profiler, SerializableString, StringId};
96use parking_lot::RwLock;
97use smallvec::SmallVec;
98use tracing::warn;
99
100use crate::fx::FxHashMap;
101use crate::outline;
102
103bitflags::bitflags! {
104    #[derive(Clone, Copy)]
105    struct EventFilter: u16 {
106        const GENERIC_ACTIVITIES  = 1 << 0;
107        const QUERY_PROVIDERS     = 1 << 1;
108        const QUERY_CACHE_HITS    = 1 << 2;
109        const QUERY_BLOCKED       = 1 << 3;
110        const INCR_CACHE_LOADS    = 1 << 4;
111
112        const QUERY_KEYS          = 1 << 5;
113        const FUNCTION_ARGS       = 1 << 6;
114        const LLVM                = 1 << 7;
115        const INCR_RESULT_HASHING = 1 << 8;
116        const ARTIFACT_SIZES = 1 << 9;
117
118        const DEFAULT = Self::GENERIC_ACTIVITIES.bits() |
119                        Self::QUERY_PROVIDERS.bits() |
120                        Self::QUERY_BLOCKED.bits() |
121                        Self::INCR_CACHE_LOADS.bits() |
122                        Self::INCR_RESULT_HASHING.bits() |
123                        Self::ARTIFACT_SIZES.bits();
124
125        const ARGS = Self::QUERY_KEYS.bits() | Self::FUNCTION_ARGS.bits();
126    }
127}
128
129// keep this in sync with the `-Z self-profile-events` help message in rustc_session/options.rs
130const EVENT_FILTERS_BY_NAME: &[(&str, EventFilter)] = &[
131    ("none", EventFilter::empty()),
132    ("all", EventFilter::all()),
133    ("default", EventFilter::DEFAULT),
134    ("generic-activity", EventFilter::GENERIC_ACTIVITIES),
135    ("query-provider", EventFilter::QUERY_PROVIDERS),
136    ("query-cache-hit", EventFilter::QUERY_CACHE_HITS),
137    ("query-blocked", EventFilter::QUERY_BLOCKED),
138    ("incr-cache-load", EventFilter::INCR_CACHE_LOADS),
139    ("query-keys", EventFilter::QUERY_KEYS),
140    ("function-args", EventFilter::FUNCTION_ARGS),
141    ("args", EventFilter::ARGS),
142    ("llvm", EventFilter::LLVM),
143    ("incr-result-hashing", EventFilter::INCR_RESULT_HASHING),
144    ("artifact-sizes", EventFilter::ARTIFACT_SIZES),
145];
146
147/// Something that uniquely identifies a query invocation.
148pub struct QueryInvocationId(pub u32);
149
150/// Which format to use for `-Z time-passes`
151#[derive(Clone, Copy, PartialEq, Hash, Debug)]
152pub enum TimePassesFormat {
153    /// Emit human readable text
154    Text,
155    /// Emit structured JSON
156    Json,
157}
158
159/// A reference to the SelfProfiler. It can be cloned and sent across thread
160/// boundaries at will.
161#[derive(Clone)]
162pub struct SelfProfilerRef {
163    // This field is `None` if self-profiling is disabled for the current
164    // compilation session.
165    profiler: Option<Arc<SelfProfiler>>,
166
167    // We store the filter mask directly in the reference because that doesn't
168    // cost anything and allows for filtering with checking if the profiler is
169    // actually enabled.
170    event_filter_mask: EventFilter,
171
172    // Print verbose generic activities to stderr.
173    print_verbose_generic_activities: Option<TimePassesFormat>,
174}
175
176impl SelfProfilerRef {
177    pub fn new(
178        profiler: Option<Arc<SelfProfiler>>,
179        print_verbose_generic_activities: Option<TimePassesFormat>,
180    ) -> SelfProfilerRef {
181        // If there is no SelfProfiler then the filter mask is set to NONE,
182        // ensuring that nothing ever tries to actually access it.
183        let event_filter_mask =
184            profiler.as_ref().map_or(EventFilter::empty(), |p| p.event_filter_mask);
185
186        SelfProfilerRef { profiler, event_filter_mask, print_verbose_generic_activities }
187    }
188
189    /// This shim makes sure that calls only get executed if the filter mask
190    /// lets them pass. It also contains some trickery to make sure that
191    /// code is optimized for non-profiling compilation sessions, i.e. anything
192    /// past the filter check is never inlined so it doesn't clutter the fast
193    /// path.
194    #[inline(always)]
195    fn exec<F>(&self, event_filter: EventFilter, f: F) -> TimingGuard<'_>
196    where
197        F: for<'a> FnOnce(&'a SelfProfiler) -> TimingGuard<'a>,
198    {
199        #[inline(never)]
200        #[cold]
201        fn cold_call<F>(profiler_ref: &SelfProfilerRef, f: F) -> TimingGuard<'_>
202        where
203            F: for<'a> FnOnce(&'a SelfProfiler) -> TimingGuard<'a>,
204        {
205            let profiler = profiler_ref.profiler.as_ref().unwrap();
206            f(profiler)
207        }
208
209        if self.event_filter_mask.contains(event_filter) {
210            cold_call(self, f)
211        } else {
212            TimingGuard::none()
213        }
214    }
215
216    /// Start profiling a verbose generic activity. Profiling continues until the
217    /// VerboseTimingGuard returned from this call is dropped. In addition to recording
218    /// a measureme event, "verbose" generic activities also print a timing entry to
219    /// stderr if the compiler is invoked with -Ztime-passes.
220    pub fn verbose_generic_activity(&self, event_label: &'static str) -> VerboseTimingGuard<'_> {
221        let message_and_format =
222            self.print_verbose_generic_activities.map(|format| (event_label.to_owned(), format));
223
224        VerboseTimingGuard::start(message_and_format, self.generic_activity(event_label))
225    }
226
227    /// Like `verbose_generic_activity`, but with an extra arg.
228    pub fn verbose_generic_activity_with_arg<A>(
229        &self,
230        event_label: &'static str,
231        event_arg: A,
232    ) -> VerboseTimingGuard<'_>
233    where
234        A: Borrow<str> + Into<String>,
235    {
236        let message_and_format = self
237            .print_verbose_generic_activities
238            .map(|format| (format!("{}({})", event_label, event_arg.borrow()), format));
239
240        VerboseTimingGuard::start(
241            message_and_format,
242            self.generic_activity_with_arg(event_label, event_arg),
243        )
244    }
245
246    /// Start profiling a generic activity. Profiling continues until the
247    /// TimingGuard returned from this call is dropped.
248    #[inline(always)]
249    pub fn generic_activity(&self, event_label: &'static str) -> TimingGuard<'_> {
250        self.exec(EventFilter::GENERIC_ACTIVITIES, |profiler| {
251            let event_label = profiler.get_or_alloc_cached_string(event_label);
252            let event_id = EventId::from_label(event_label);
253            TimingGuard::start(profiler, profiler.generic_activity_event_kind, event_id)
254        })
255    }
256
257    /// Start profiling with some event filter for a given event. Profiling continues until the
258    /// TimingGuard returned from this call is dropped.
259    #[inline(always)]
260    pub fn generic_activity_with_event_id(&self, event_id: EventId) -> TimingGuard<'_> {
261        self.exec(EventFilter::GENERIC_ACTIVITIES, |profiler| {
262            TimingGuard::start(profiler, profiler.generic_activity_event_kind, event_id)
263        })
264    }
265
266    /// Start profiling a generic activity. Profiling continues until the
267    /// TimingGuard returned from this call is dropped.
268    #[inline(always)]
269    pub fn generic_activity_with_arg<A>(
270        &self,
271        event_label: &'static str,
272        event_arg: A,
273    ) -> TimingGuard<'_>
274    where
275        A: Borrow<str> + Into<String>,
276    {
277        self.exec(EventFilter::GENERIC_ACTIVITIES, |profiler| {
278            let builder = EventIdBuilder::new(&profiler.profiler);
279            let event_label = profiler.get_or_alloc_cached_string(event_label);
280            let event_id = if profiler.event_filter_mask.contains(EventFilter::FUNCTION_ARGS) {
281                let event_arg = profiler.get_or_alloc_cached_string(event_arg);
282                builder.from_label_and_arg(event_label, event_arg)
283            } else {
284                builder.from_label(event_label)
285            };
286            TimingGuard::start(profiler, profiler.generic_activity_event_kind, event_id)
287        })
288    }
289
290    /// Start profiling a generic activity, allowing costly arguments to be recorded. Profiling
291    /// continues until the `TimingGuard` returned from this call is dropped.
292    ///
293    /// If the arguments to a generic activity are cheap to create, use `generic_activity_with_arg`
294    /// or `generic_activity_with_args` for their simpler API. However, if they are costly or
295    /// require allocation in sufficiently hot contexts, then this allows for a closure to be called
296    /// only when arguments were asked to be recorded via `-Z self-profile-events=args`.
297    ///
298    /// In this case, the closure will be passed a `&mut EventArgRecorder`, to help with recording
299    /// one or many arguments within the generic activity being profiled, by calling its
300    /// `record_arg` method for example.
301    ///
302    /// This `EventArgRecorder` may implement more specific traits from other rustc crates, e.g. for
303    /// richer handling of rustc-specific argument types, while keeping this single entry-point API
304    /// for recording arguments.
305    ///
306    /// Note: recording at least one argument is *required* for the self-profiler to create the
307    /// `TimingGuard`. A panic will be triggered if that doesn't happen. This function exists
308    /// explicitly to record arguments, so it fails loudly when there are none to record.
309    ///
310    #[inline(always)]
311    pub fn generic_activity_with_arg_recorder<F>(
312        &self,
313        event_label: &'static str,
314        mut f: F,
315    ) -> TimingGuard<'_>
316    where
317        F: FnMut(&mut EventArgRecorder<'_>),
318    {
319        // Ensure this event will only be recorded when self-profiling is turned on.
320        self.exec(EventFilter::GENERIC_ACTIVITIES, |profiler| {
321            let builder = EventIdBuilder::new(&profiler.profiler);
322            let event_label = profiler.get_or_alloc_cached_string(event_label);
323
324            // Ensure the closure to create event arguments will only be called when argument
325            // recording is turned on.
326            let event_id = if profiler.event_filter_mask.contains(EventFilter::FUNCTION_ARGS) {
327                // Set up the builder and call the user-provided closure to record potentially
328                // costly event arguments.
329                let mut recorder = EventArgRecorder { profiler, args: SmallVec::new() };
330                f(&mut recorder);
331
332                // It is expected that the closure will record at least one argument. If that
333                // doesn't happen, it's a bug: we've been explicitly called in order to record
334                // arguments, so we fail loudly when there are none to record.
335                if recorder.args.is_empty() {
336                    panic!(
337                        "The closure passed to `generic_activity_with_arg_recorder` needs to \
338                         record at least one argument"
339                    );
340                }
341
342                builder.from_label_and_args(event_label, &recorder.args)
343            } else {
344                builder.from_label(event_label)
345            };
346            TimingGuard::start(profiler, profiler.generic_activity_event_kind, event_id)
347        })
348    }
349
350    /// Record the size of an artifact that the compiler produces
351    ///
352    /// `artifact_kind` is the class of artifact (e.g., query_cache, object_file, etc.)
353    /// `artifact_name` is an identifier to the specific artifact being stored (usually a filename)
354    #[inline(always)]
355    pub fn artifact_size<A>(&self, artifact_kind: &str, artifact_name: A, size: u64)
356    where
357        A: Borrow<str> + Into<String>,
358    {
359        drop(self.exec(EventFilter::ARTIFACT_SIZES, |profiler| {
360            let builder = EventIdBuilder::new(&profiler.profiler);
361            let event_label = profiler.get_or_alloc_cached_string(artifact_kind);
362            let event_arg = profiler.get_or_alloc_cached_string(artifact_name);
363            let event_id = builder.from_label_and_arg(event_label, event_arg);
364            let thread_id = get_thread_id();
365
366            profiler.profiler.record_integer_event(
367                profiler.artifact_size_event_kind,
368                event_id,
369                thread_id,
370                size,
371            );
372
373            TimingGuard::none()
374        }))
375    }
376
377    #[inline(always)]
378    pub fn generic_activity_with_args(
379        &self,
380        event_label: &'static str,
381        event_args: &[String],
382    ) -> TimingGuard<'_> {
383        self.exec(EventFilter::GENERIC_ACTIVITIES, |profiler| {
384            let builder = EventIdBuilder::new(&profiler.profiler);
385            let event_label = profiler.get_or_alloc_cached_string(event_label);
386            let event_id = if profiler.event_filter_mask.contains(EventFilter::FUNCTION_ARGS) {
387                let event_args: Vec<_> = event_args
388                    .iter()
389                    .map(|s| profiler.get_or_alloc_cached_string(&s[..]))
390                    .collect();
391                builder.from_label_and_args(event_label, &event_args)
392            } else {
393                builder.from_label(event_label)
394            };
395            TimingGuard::start(profiler, profiler.generic_activity_event_kind, event_id)
396        })
397    }
398
399    /// Start profiling a query provider. Profiling continues until the
400    /// TimingGuard returned from this call is dropped.
401    #[inline(always)]
402    pub fn query_provider(&self) -> TimingGuard<'_> {
403        self.exec(EventFilter::QUERY_PROVIDERS, |profiler| {
404            TimingGuard::start(profiler, profiler.query_event_kind, EventId::INVALID)
405        })
406    }
407
408    /// Record a query in-memory cache hit.
409    #[inline(always)]
410    pub fn query_cache_hit(&self, query_invocation_id: QueryInvocationId) {
411        #[inline(never)]
412        #[cold]
413        fn cold_call(profiler_ref: &SelfProfilerRef, query_invocation_id: QueryInvocationId) {
414            profiler_ref.instant_query_event(
415                |profiler| profiler.query_cache_hit_event_kind,
416                query_invocation_id,
417            );
418        }
419
420        if unlikely(self.event_filter_mask.contains(EventFilter::QUERY_CACHE_HITS)) {
421            cold_call(self, query_invocation_id);
422        }
423    }
424
425    /// Start profiling a query being blocked on a concurrent execution.
426    /// Profiling continues until the TimingGuard returned from this call is
427    /// dropped.
428    #[inline(always)]
429    pub fn query_blocked(&self) -> TimingGuard<'_> {
430        self.exec(EventFilter::QUERY_BLOCKED, |profiler| {
431            TimingGuard::start(profiler, profiler.query_blocked_event_kind, EventId::INVALID)
432        })
433    }
434
435    /// Start profiling how long it takes to load a query result from the
436    /// incremental compilation on-disk cache. Profiling continues until the
437    /// TimingGuard returned from this call is dropped.
438    #[inline(always)]
439    pub fn incr_cache_loading(&self) -> TimingGuard<'_> {
440        self.exec(EventFilter::INCR_CACHE_LOADS, |profiler| {
441            TimingGuard::start(
442                profiler,
443                profiler.incremental_load_result_event_kind,
444                EventId::INVALID,
445            )
446        })
447    }
448
449    /// Start profiling how long it takes to hash query results for incremental compilation.
450    /// Profiling continues until the TimingGuard returned from this call is dropped.
451    #[inline(always)]
452    pub fn incr_result_hashing(&self) -> TimingGuard<'_> {
453        self.exec(EventFilter::INCR_RESULT_HASHING, |profiler| {
454            TimingGuard::start(
455                profiler,
456                profiler.incremental_result_hashing_event_kind,
457                EventId::INVALID,
458            )
459        })
460    }
461
462    #[inline(always)]
463    fn instant_query_event(
464        &self,
465        event_kind: fn(&SelfProfiler) -> StringId,
466        query_invocation_id: QueryInvocationId,
467    ) {
468        let event_id = StringId::new_virtual(query_invocation_id.0);
469        let thread_id = get_thread_id();
470        let profiler = self.profiler.as_ref().unwrap();
471        profiler.profiler.record_instant_event(
472            event_kind(profiler),
473            EventId::from_virtual(event_id),
474            thread_id,
475        );
476    }
477
478    pub fn with_profiler(&self, f: impl FnOnce(&SelfProfiler)) {
479        if let Some(profiler) = &self.profiler {
480            f(profiler)
481        }
482    }
483
484    /// Gets a `StringId` for the given string. This method makes sure that
485    /// any strings going through it will only be allocated once in the
486    /// profiling data.
487    /// Returns `None` if the self-profiling is not enabled.
488    pub fn get_or_alloc_cached_string(&self, s: &str) -> Option<StringId> {
489        self.profiler.as_ref().map(|p| p.get_or_alloc_cached_string(s))
490    }
491
492    #[inline]
493    pub fn enabled(&self) -> bool {
494        self.profiler.is_some()
495    }
496
497    #[inline]
498    pub fn llvm_recording_enabled(&self) -> bool {
499        self.event_filter_mask.contains(EventFilter::LLVM)
500    }
501    #[inline]
502    pub fn get_self_profiler(&self) -> Option<Arc<SelfProfiler>> {
503        self.profiler.clone()
504    }
505}
506
507/// A helper for recording costly arguments to self-profiling events. Used with
508/// `SelfProfilerRef::generic_activity_with_arg_recorder`.
509pub struct EventArgRecorder<'p> {
510    /// The `SelfProfiler` used to intern the event arguments that users will ask to record.
511    profiler: &'p SelfProfiler,
512
513    /// The interned event arguments to be recorded in the generic activity event.
514    ///
515    /// The most common case, when actually recording event arguments, is to have one argument. Then
516    /// followed by recording two, in a couple places.
517    args: SmallVec<[StringId; 2]>,
518}
519
520impl EventArgRecorder<'_> {
521    /// Records a single argument within the current generic activity being profiled.
522    ///
523    /// Note: when self-profiling with costly event arguments, at least one argument
524    /// needs to be recorded. A panic will be triggered if that doesn't happen.
525    pub fn record_arg<A>(&mut self, event_arg: A)
526    where
527        A: Borrow<str> + Into<String>,
528    {
529        let event_arg = self.profiler.get_or_alloc_cached_string(event_arg);
530        self.args.push(event_arg);
531    }
532}
533
534pub struct SelfProfiler {
535    profiler: Profiler,
536    event_filter_mask: EventFilter,
537
538    string_cache: RwLock<FxHashMap<String, StringId>>,
539
540    query_event_kind: StringId,
541    generic_activity_event_kind: StringId,
542    incremental_load_result_event_kind: StringId,
543    incremental_result_hashing_event_kind: StringId,
544    query_blocked_event_kind: StringId,
545    query_cache_hit_event_kind: StringId,
546    artifact_size_event_kind: StringId,
547}
548
549impl SelfProfiler {
550    pub fn new(
551        output_directory: &Path,
552        crate_name: Option<&str>,
553        event_filters: Option<&[String]>,
554        counter_name: &str,
555    ) -> Result<SelfProfiler, Box<dyn Error + Send + Sync>> {
556        fs::create_dir_all(output_directory)?;
557
558        let crate_name = crate_name.unwrap_or("unknown-crate");
559        // HACK(eddyb) we need to pad the PID, strange as it may seem, as its
560        // length can behave as a source of entropy for heap addresses, when
561        // ASLR is disabled and the heap is otherwise deterministic.
562        let pid: u32 = process::id();
563        let filename = format!("{crate_name}-{pid:07}.rustc_profile");
564        let path = output_directory.join(filename);
565        let profiler =
566            Profiler::with_counter(&path, measureme::counters::Counter::by_name(counter_name)?)?;
567
568        let query_event_kind = profiler.alloc_string("Query");
569        let generic_activity_event_kind = profiler.alloc_string("GenericActivity");
570        let incremental_load_result_event_kind = profiler.alloc_string("IncrementalLoadResult");
571        let incremental_result_hashing_event_kind =
572            profiler.alloc_string("IncrementalResultHashing");
573        let query_blocked_event_kind = profiler.alloc_string("QueryBlocked");
574        let query_cache_hit_event_kind = profiler.alloc_string("QueryCacheHit");
575        let artifact_size_event_kind = profiler.alloc_string("ArtifactSize");
576
577        let mut event_filter_mask = EventFilter::empty();
578
579        if let Some(event_filters) = event_filters {
580            let mut unknown_events = vec![];
581            for item in event_filters {
582                if let Some(&(_, mask)) =
583                    EVENT_FILTERS_BY_NAME.iter().find(|&(name, _)| name == item)
584                {
585                    event_filter_mask |= mask;
586                } else {
587                    unknown_events.push(item.clone());
588                }
589            }
590
591            // Warn about any unknown event names
592            if !unknown_events.is_empty() {
593                unknown_events.sort();
594                unknown_events.dedup();
595
596                warn!(
597                    "Unknown self-profiler events specified: {}. Available options are: {}.",
598                    unknown_events.join(", "),
599                    EVENT_FILTERS_BY_NAME
600                        .iter()
601                        .map(|&(name, _)| name.to_string())
602                        .collect::<Vec<_>>()
603                        .join(", ")
604                );
605            }
606        } else {
607            event_filter_mask = EventFilter::DEFAULT;
608        }
609
610        Ok(SelfProfiler {
611            profiler,
612            event_filter_mask,
613            string_cache: RwLock::new(FxHashMap::default()),
614            query_event_kind,
615            generic_activity_event_kind,
616            incremental_load_result_event_kind,
617            incremental_result_hashing_event_kind,
618            query_blocked_event_kind,
619            query_cache_hit_event_kind,
620            artifact_size_event_kind,
621        })
622    }
623
624    /// Allocates a new string in the profiling data. Does not do any caching
625    /// or deduplication.
626    pub fn alloc_string<STR: SerializableString + ?Sized>(&self, s: &STR) -> StringId {
627        self.profiler.alloc_string(s)
628    }
629
630    /// Gets a `StringId` for the given string. This method makes sure that
631    /// any strings going through it will only be allocated once in the
632    /// profiling data.
633    pub fn get_or_alloc_cached_string<A>(&self, s: A) -> StringId
634    where
635        A: Borrow<str> + Into<String>,
636    {
637        // Only acquire a read-lock first since we assume that the string is
638        // already present in the common case.
639        {
640            let string_cache = self.string_cache.read();
641
642            if let Some(&id) = string_cache.get(s.borrow()) {
643                return id;
644            }
645        }
646
647        let mut string_cache = self.string_cache.write();
648        // Check if the string has already been added in the small time window
649        // between dropping the read lock and acquiring the write lock.
650        match string_cache.entry(s.into()) {
651            Entry::Occupied(e) => *e.get(),
652            Entry::Vacant(e) => {
653                let string_id = self.profiler.alloc_string(&e.key()[..]);
654                *e.insert(string_id)
655            }
656        }
657    }
658
659    pub fn map_query_invocation_id_to_string(&self, from: QueryInvocationId, to: StringId) {
660        let from = StringId::new_virtual(from.0);
661        self.profiler.map_virtual_to_concrete_string(from, to);
662    }
663
664    pub fn bulk_map_query_invocation_id_to_single_string<I>(&self, from: I, to: StringId)
665    where
666        I: Iterator<Item = QueryInvocationId> + ExactSizeIterator,
667    {
668        let from = from.map(|qid| StringId::new_virtual(qid.0));
669        self.profiler.bulk_map_virtual_to_single_concrete_string(from, to);
670    }
671
672    pub fn query_key_recording_enabled(&self) -> bool {
673        self.event_filter_mask.contains(EventFilter::QUERY_KEYS)
674    }
675
676    pub fn event_id_builder(&self) -> EventIdBuilder<'_> {
677        EventIdBuilder::new(&self.profiler)
678    }
679}
680
681#[must_use]
682pub struct TimingGuard<'a>(Option<measureme::TimingGuard<'a>>);
683
684impl<'a> TimingGuard<'a> {
685    #[inline]
686    pub fn start(
687        profiler: &'a SelfProfiler,
688        event_kind: StringId,
689        event_id: EventId,
690    ) -> TimingGuard<'a> {
691        let thread_id = get_thread_id();
692        let raw_profiler = &profiler.profiler;
693        let timing_guard =
694            raw_profiler.start_recording_interval_event(event_kind, event_id, thread_id);
695        TimingGuard(Some(timing_guard))
696    }
697
698    #[inline]
699    pub fn finish_with_query_invocation_id(self, query_invocation_id: QueryInvocationId) {
700        if let Some(guard) = self.0 {
701            outline(|| {
702                let event_id = StringId::new_virtual(query_invocation_id.0);
703                let event_id = EventId::from_virtual(event_id);
704                guard.finish_with_override_event_id(event_id);
705            });
706        }
707    }
708
709    #[inline]
710    pub fn none() -> TimingGuard<'a> {
711        TimingGuard(None)
712    }
713
714    #[inline(always)]
715    pub fn run<R>(self, f: impl FnOnce() -> R) -> R {
716        let _timer = self;
717        f()
718    }
719}
720
721struct VerboseInfo {
722    start_time: Instant,
723    start_rss: Option<usize>,
724    message: String,
725    format: TimePassesFormat,
726}
727
728#[must_use]
729pub struct VerboseTimingGuard<'a> {
730    info: Option<VerboseInfo>,
731    _guard: TimingGuard<'a>,
732}
733
734impl<'a> VerboseTimingGuard<'a> {
735    pub fn start(
736        message_and_format: Option<(String, TimePassesFormat)>,
737        _guard: TimingGuard<'a>,
738    ) -> Self {
739        VerboseTimingGuard {
740            _guard,
741            info: message_and_format.map(|(message, format)| VerboseInfo {
742                start_time: Instant::now(),
743                start_rss: get_resident_set_size(),
744                message,
745                format,
746            }),
747        }
748    }
749
750    #[inline(always)]
751    pub fn run<R>(self, f: impl FnOnce() -> R) -> R {
752        let _timer = self;
753        f()
754    }
755}
756
757impl Drop for VerboseTimingGuard<'_> {
758    fn drop(&mut self) {
759        if let Some(info) = &self.info {
760            let end_rss = get_resident_set_size();
761            let dur = info.start_time.elapsed();
762            print_time_passes_entry(&info.message, dur, info.start_rss, end_rss, info.format);
763        }
764    }
765}
766
767struct JsonTimePassesEntry<'a> {
768    pass: &'a str,
769    time: f64,
770    start_rss: Option<usize>,
771    end_rss: Option<usize>,
772}
773
774impl Display for JsonTimePassesEntry<'_> {
775    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
776        let Self { pass: what, time, start_rss, end_rss } = self;
777        write!(f, r#"{{"pass":"{what}","time":{time},"rss_start":"#).unwrap();
778        match start_rss {
779            Some(rss) => write!(f, "{rss}")?,
780            None => write!(f, "null")?,
781        }
782        write!(f, r#","rss_end":"#)?;
783        match end_rss {
784            Some(rss) => write!(f, "{rss}")?,
785            None => write!(f, "null")?,
786        }
787        write!(f, "}}")?;
788        Ok(())
789    }
790}
791
792pub fn print_time_passes_entry(
793    what: &str,
794    dur: Duration,
795    start_rss: Option<usize>,
796    end_rss: Option<usize>,
797    format: TimePassesFormat,
798) {
799    match format {
800        TimePassesFormat::Json => {
801            let entry =
802                JsonTimePassesEntry { pass: what, time: dur.as_secs_f64(), start_rss, end_rss };
803
804            eprintln!(r#"time: {entry}"#);
805            return;
806        }
807        TimePassesFormat::Text => (),
808    }
809
810    // Print the pass if its duration is greater than 5 ms, or it changed the
811    // measured RSS.
812    let is_notable = || {
813        if dur.as_millis() > 5 {
814            return true;
815        }
816
817        if let (Some(start_rss), Some(end_rss)) = (start_rss, end_rss) {
818            let change_rss = end_rss.abs_diff(start_rss);
819            if change_rss > 0 {
820                return true;
821            }
822        }
823
824        false
825    };
826    if !is_notable() {
827        return;
828    }
829
830    let rss_to_mb = |rss| (rss as f64 / 1_000_000.0).round() as usize;
831    let rss_change_to_mb = |rss| (rss as f64 / 1_000_000.0).round() as i128;
832
833    let mem_string = match (start_rss, end_rss) {
834        (Some(start_rss), Some(end_rss)) => {
835            let change_rss = end_rss as i128 - start_rss as i128;
836
837            format!(
838                "; rss: {:>4}MB -> {:>4}MB ({:>+5}MB)",
839                rss_to_mb(start_rss),
840                rss_to_mb(end_rss),
841                rss_change_to_mb(change_rss),
842            )
843        }
844        (Some(start_rss), None) => format!("; rss start: {:>4}MB", rss_to_mb(start_rss)),
845        (None, Some(end_rss)) => format!("; rss end: {:>4}MB", rss_to_mb(end_rss)),
846        (None, None) => String::new(),
847    };
848
849    eprintln!("time: {:>7}{}\t{}", duration_to_secs_str(dur), mem_string, what);
850}
851
852// Hack up our own formatting for the duration to make it easier for scripts
853// to parse (always use the same number of decimal places and the same unit).
854pub fn duration_to_secs_str(dur: std::time::Duration) -> String {
855    format!("{:.3}", dur.as_secs_f64())
856}
857
858fn get_thread_id() -> u32 {
859    std::thread::current().id().as_u64().get() as u32
860}
861
862// Memory reporting
863cfg_match! {
864    windows => {
865        pub fn get_resident_set_size() -> Option<usize> {
866            use windows::{
867                Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS},
868                Win32::System::Threading::GetCurrentProcess,
869            };
870
871            let mut pmc = PROCESS_MEMORY_COUNTERS::default();
872            let pmc_size = size_of_val(&pmc);
873            unsafe {
874                K32GetProcessMemoryInfo(
875                    GetCurrentProcess(),
876                    &mut pmc,
877                    pmc_size as u32,
878                )
879            }
880            .ok()
881            .ok()?;
882
883            Some(pmc.WorkingSetSize)
884        }
885    }
886    target_os = "macos" => {
887        pub fn get_resident_set_size() -> Option<usize> {
888            use libc::{c_int, c_void, getpid, proc_pidinfo, proc_taskinfo, PROC_PIDTASKINFO};
889            use std::mem;
890            const PROC_TASKINFO_SIZE: c_int = size_of::<proc_taskinfo>() as c_int;
891
892            unsafe {
893                let mut info: proc_taskinfo = mem::zeroed();
894                let info_ptr = &mut info as *mut proc_taskinfo as *mut c_void;
895                let pid = getpid() as c_int;
896                let ret = proc_pidinfo(pid, PROC_PIDTASKINFO, 0, info_ptr, PROC_TASKINFO_SIZE);
897                if ret == PROC_TASKINFO_SIZE {
898                    Some(info.pti_resident_size as usize)
899                } else {
900                    None
901                }
902            }
903        }
904    }
905    unix => {
906        pub fn get_resident_set_size() -> Option<usize> {
907            let field = 1;
908            let contents = fs::read("/proc/self/statm").ok()?;
909            let contents = String::from_utf8(contents).ok()?;
910            let s = contents.split_whitespace().nth(field)?;
911            let npages = s.parse::<usize>().ok()?;
912            Some(npages * 4096)
913        }
914    }
915    _ => {
916        pub fn get_resident_set_size() -> Option<usize> {
917            None
918        }
919    }
920}
921
922#[cfg(test)]
923mod tests;