Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:44:34

0001 //===- llvm/Support/TimeProfiler.h - Hierarchical Time Profiler -*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 //
0009 // This provides lightweight and dependency-free machinery to trace execution
0010 // time around arbitrary code. Two API flavors are available.
0011 //
0012 // The primary API uses a RAII object to trigger tracing:
0013 //
0014 // \code
0015 //   {
0016 //     TimeTraceScope scope("my_event_name");
0017 //     ...my code...
0018 //   }
0019 // \endcode
0020 //
0021 // If the code to be profiled does not have a natural lexical scope then
0022 // it is also possible to start and end events with respect to an implicit
0023 // per-thread stack of profiling entries:
0024 //
0025 // \code
0026 //   timeTraceProfilerBegin("my_event_name");
0027 //   ...my code...
0028 //   timeTraceProfilerEnd();  // must be called on all control flow paths
0029 // \endcode
0030 //
0031 // Time profiling entries can be given an arbitrary name and, optionally,
0032 // an arbitrary 'detail' string. The resulting trace will include 'Total'
0033 // entries summing the time spent for each name. Thus, it's best to choose
0034 // names to be fairly generic, and rely on the detail field to capture
0035 // everything else of interest.
0036 //
0037 // To avoid lifetime issues name and detail strings are copied into the event
0038 // entries at their time of creation. Care should be taken to make string
0039 // construction cheap to prevent 'Heisenperf' effects. In particular, the
0040 // 'detail' argument may be a string-returning closure:
0041 //
0042 // \code
0043 //   int n;
0044 //   {
0045 //     TimeTraceScope scope("my_event_name",
0046 //                          [n]() { return (Twine("x=") + Twine(n)).str(); });
0047 //     ...my code...
0048 //   }
0049 // \endcode
0050 // The closure will not be called if tracing is disabled. Otherwise, the
0051 // resulting string will be directly moved into the entry.
0052 //
0053 // The main process should begin with a timeTraceProfilerInitialize, and
0054 // finish with timeTraceProfileWrite and timeTraceProfilerCleanup calls.
0055 // Each new thread should begin with a timeTraceProfilerInitialize, and
0056 // finish with a timeTraceProfilerFinishThread call.
0057 //
0058 // Timestamps come from std::chrono::stable_clock. Note that threads need
0059 // not see the same time from that clock, and the resolution may not be
0060 // the best available.
0061 //
0062 // Currently, there are a number of compatible viewers:
0063 //  - chrome://tracing is the original chromium trace viewer.
0064 //  - http://ui.perfetto.dev is the replacement for the above, under active
0065 //    development by Google as part of the 'Perfetto' project.
0066 //  - https://www.speedscope.app/ has also been reported as an option.
0067 //
0068 // Future work:
0069 //  - Support akin to LLVM_DEBUG for runtime enable/disable of named tracing
0070 //    families for non-debug builds which wish to support optional tracing.
0071 //  - Evaluate the detail closures at profile write time to avoid
0072 //    stringification costs interfering with tracing.
0073 //
0074 //===----------------------------------------------------------------------===//
0075 
0076 #ifndef LLVM_SUPPORT_TIMEPROFILER_H
0077 #define LLVM_SUPPORT_TIMEPROFILER_H
0078 
0079 #include "llvm/ADT/STLFunctionalExtras.h"
0080 #include "llvm/Support/Error.h"
0081 
0082 namespace llvm {
0083 
0084 class raw_pwrite_stream;
0085 
0086 // Type of the time trace event.
0087 enum class TimeTraceEventType {
0088   // Complete events have a duration (start and end time points) and are marked
0089   // by the "X" phase type.
0090   CompleteEvent,
0091   // Instant events don't have a duration, they happen at an instant in time.
0092   // They are marked with "i" phase type. The field End is ignored for them.
0093   InstantEvent,
0094   // Async events mark asynchronous operations and are specified by the "b"
0095   // (start) and "e" (end) phase types.
0096   AsyncEvent
0097 };
0098 
0099 struct TimeTraceMetadata {
0100   std::string Detail;
0101   // Source file and line number information for the event.
0102   std::string File;
0103   int Line = 0;
0104 
0105   bool isEmpty() const { return Detail.empty() && File.empty(); }
0106 };
0107 
0108 struct TimeTraceProfiler;
0109 TimeTraceProfiler *getTimeTraceProfilerInstance();
0110 
0111 bool isTimeTraceVerbose();
0112 
0113 struct TimeTraceProfilerEntry;
0114 
0115 /// Initialize the time trace profiler.
0116 /// This sets up the global \p TimeTraceProfilerInstance
0117 /// variable to be the profiler instance.
0118 void timeTraceProfilerInitialize(unsigned TimeTraceGranularity,
0119                                  StringRef ProcName,
0120                                  bool TimeTraceVerbose = false);
0121 
0122 /// Cleanup the time trace profiler, if it was initialized.
0123 void timeTraceProfilerCleanup();
0124 
0125 /// Finish a time trace profiler running on a worker thread.
0126 void timeTraceProfilerFinishThread();
0127 
0128 /// Is the time trace profiler enabled, i.e. initialized?
0129 inline bool timeTraceProfilerEnabled() {
0130   return getTimeTraceProfilerInstance() != nullptr;
0131 }
0132 
0133 /// Write profiling data to output stream.
0134 /// Data produced is JSON, in Chrome "Trace Event" format, see
0135 /// https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview
0136 void timeTraceProfilerWrite(raw_pwrite_stream &OS);
0137 
0138 /// Write profiling data to a file.
0139 /// The function will write to \p PreferredFileName if provided, if not
0140 /// then will write to \p FallbackFileName appending .time-trace.
0141 /// Returns a StringError indicating a failure if the function is
0142 /// unable to open the file for writing.
0143 Error timeTraceProfilerWrite(StringRef PreferredFileName,
0144                              StringRef FallbackFileName);
0145 
0146 /// Manually begin a time section, with the given \p Name and \p Detail.
0147 /// Profiler copies the string data, so the pointers can be given into
0148 /// temporaries. Time sections can be hierarchical; every Begin must have a
0149 /// matching End pair but they can nest.
0150 TimeTraceProfilerEntry *timeTraceProfilerBegin(StringRef Name,
0151                                                StringRef Detail);
0152 TimeTraceProfilerEntry *
0153 timeTraceProfilerBegin(StringRef Name,
0154                        llvm::function_ref<std::string()> Detail);
0155 
0156 TimeTraceProfilerEntry *
0157 timeTraceProfilerBegin(StringRef Name,
0158                        llvm::function_ref<TimeTraceMetadata()> MetaData);
0159 
0160 /// Manually begin a time section, with the given \p Name and \p Detail.
0161 /// This starts Async Events having \p Name as a category which is shown
0162 /// separately from other traces. See
0163 /// https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview#heading=h.jh64i9l3vwa1
0164 /// for more details.
0165 TimeTraceProfilerEntry *timeTraceAsyncProfilerBegin(StringRef Name,
0166                                                     StringRef Detail);
0167 
0168 // Mark an instant event.
0169 void timeTraceAddInstantEvent(StringRef Name,
0170                               llvm::function_ref<std::string()> Detail);
0171 
0172 /// Manually end the last time section.
0173 void timeTraceProfilerEnd();
0174 void timeTraceProfilerEnd(TimeTraceProfilerEntry *E);
0175 
0176 /// The TimeTraceScope is a helper class to call the begin and end functions
0177 /// of the time trace profiler.  When the object is constructed, it begins
0178 /// the section; and when it is destroyed, it stops it. If the time profiler
0179 /// is not initialized, the overhead is a single branch.
0180 class TimeTraceScope {
0181 public:
0182   TimeTraceScope() = delete;
0183   TimeTraceScope(const TimeTraceScope &) = delete;
0184   TimeTraceScope &operator=(const TimeTraceScope &) = delete;
0185   TimeTraceScope(TimeTraceScope &&) = delete;
0186   TimeTraceScope &operator=(TimeTraceScope &&) = delete;
0187 
0188   TimeTraceScope(StringRef Name)
0189       : Entry(timeTraceProfilerBegin(Name, StringRef())) {}
0190   TimeTraceScope(StringRef Name, StringRef Detail)
0191       : Entry(timeTraceProfilerBegin(Name, Detail)) {}
0192   TimeTraceScope(StringRef Name, llvm::function_ref<std::string()> Detail)
0193       : Entry(timeTraceProfilerBegin(Name, Detail)) {}
0194   TimeTraceScope(StringRef Name,
0195                  llvm::function_ref<TimeTraceMetadata()> Metadata)
0196       : Entry(timeTraceProfilerBegin(Name, Metadata)) {}
0197   ~TimeTraceScope() {
0198     if (Entry)
0199       timeTraceProfilerEnd(Entry);
0200   }
0201 
0202 private:
0203   TimeTraceProfilerEntry *Entry = nullptr;
0204 };
0205 
0206 } // end namespace llvm
0207 
0208 #endif