LLVM 20.0.0git
DebugCounter.cpp
Go to the documentation of this file.
2
3#include "DebugOptions.h"
4
7
8using namespace llvm;
9
10namespace llvm {
11
13 if (Begin == End)
14 OS << Begin;
15 else
16 OS << Begin << "-" << End;
17}
18
20 if (Chunks.empty()) {
21 OS << "empty";
22 } else {
23 bool IsFirst = true;
24 for (auto E : Chunks) {
25 if (!IsFirst)
26 OS << ':';
27 else
28 IsFirst = false;
29 E.print(OS);
30 }
31 }
32}
33
35 StringRef Remaining = Str;
36
37 auto ConsumeInt = [&]() -> int64_t {
39 Remaining.take_until([](char c) { return c < '0' || c > '9'; });
40 int64_t Res;
41 if (Number.getAsInteger(10, Res)) {
42 errs() << "Failed to parse int at : " << Remaining << "\n";
43 return -1;
44 }
45 Remaining = Remaining.drop_front(Number.size());
46 return Res;
47 };
48
49 while (1) {
50 int64_t Num = ConsumeInt();
51 if (Num == -1)
52 return true;
53 if (!Chunks.empty() && Num <= Chunks[Chunks.size() - 1].End) {
54 errs() << "Expected Chunks to be in increasing order " << Num
55 << " <= " << Chunks[Chunks.size() - 1].End << "\n";
56 return true;
57 }
58 if (Remaining.starts_with("-")) {
59 Remaining = Remaining.drop_front();
60 int64_t Num2 = ConsumeInt();
61 if (Num2 == -1)
62 return true;
63 if (Num >= Num2) {
64 errs() << "Expected " << Num << " < " << Num2 << " in " << Num << "-"
65 << Num2 << "\n";
66 return true;
67 }
68
69 Chunks.push_back({Num, Num2});
70 } else {
71 Chunks.push_back({Num, Num});
72 }
73 if (Remaining.starts_with(":")) {
74 Remaining = Remaining.drop_front();
75 continue;
76 }
77 if (Remaining.empty())
78 break;
79 errs() << "Failed to parse at : " << Remaining;
80 return true;
81 }
82 return false;
83}
84
85} // namespace llvm
86
87namespace {
88// This class overrides the default list implementation of printing so we
89// can pretty print the list of debug counter options. This type of
90// dynamic option is pretty rare (basically this and pass lists).
91class DebugCounterList : public cl::list<std::string, DebugCounter> {
92private:
94
95public:
96 template <class... Mods>
97 explicit DebugCounterList(Mods &&... Ms) : Base(std::forward<Mods>(Ms)...) {}
98
99private:
100 void printOptionInfo(size_t GlobalWidth) const override {
101 // This is a variant of from generic_parser_base::printOptionInfo. Sadly,
102 // it's not easy to make it more usable. We could get it to print these as
103 // options if we were a cl::opt and registered them, but lists don't have
104 // options, nor does the parser for std::string. The other mechanisms for
105 // options are global and would pollute the global namespace with our
106 // counters. Rather than go that route, we have just overridden the
107 // printing, which only a few things call anyway.
108 outs() << " -" << ArgStr;
109 // All of the other options in CommandLine.cpp use ArgStr.size() + 6 for
110 // width, so we do the same.
111 Option::printHelpStr(HelpStr, GlobalWidth, ArgStr.size() + 6);
112 const auto &CounterInstance = DebugCounter::instance();
113 for (const auto &Name : CounterInstance) {
114 const auto Info =
115 CounterInstance.getCounterInfo(CounterInstance.getCounterId(Name));
116 size_t NumSpaces = GlobalWidth - Info.first.size() - 8;
117 outs() << " =" << Info.first;
118 outs().indent(NumSpaces) << " - " << Info.second << '\n';
119 }
120 }
121};
122
123// All global objects associated to the DebugCounter, including the DebugCounter
124// itself, are owned by a single global instance of the DebugCounterOwner
125// struct. This makes it easier to control the order in which constructors and
126// destructors are run.
127struct DebugCounterOwner : DebugCounter {
128 DebugCounterList DebugCounterOption{
129 "debug-counter", cl::Hidden,
130 cl::desc("Comma separated list of debug counter skip and count"),
131 cl::CommaSeparated, cl::location<DebugCounter>(*this)};
132 cl::opt<bool, true> PrintDebugCounter{
133 "print-debug-counter",
136 cl::location(this->ShouldPrintCounter),
137 cl::init(false),
138 cl::desc("Print out debug counter info after all counters accumulated")};
139 cl::opt<bool, true> BreakOnLastCount{
140 "debug-counter-break-on-last",
143 cl::location(this->BreakOnLast),
144 cl::init(false),
145 cl::desc("Insert a break point on the last enabled count of a "
146 "chunks list")};
147
148 DebugCounterOwner() {
149 // Our destructor uses the debug stream. By referencing it here, we
150 // ensure that its destructor runs after our destructor.
151 (void)dbgs();
152 }
153
154 // Print information when destroyed, iff command line option is specified.
155 ~DebugCounterOwner() {
156 if (ShouldPrintCounter)
157 print(dbgs());
158 }
159};
160
161} // anonymous namespace
162
164
166 static DebugCounterOwner O;
167 return O;
168}
169
170// This is called by the command line parser when it sees a value for the
171// debug-counter option defined above.
172void DebugCounter::push_back(const std::string &Val) {
173 if (Val.empty())
174 return;
175
176 // The strings should come in as counter=chunk_list
177 auto CounterPair = StringRef(Val).split('=');
178 if (CounterPair.second.empty()) {
179 errs() << "DebugCounter Error: " << Val << " does not have an = in it\n";
180 return;
181 }
182 StringRef CounterName = CounterPair.first;
183 SmallVector<Chunk> Chunks;
184
185 if (parseChunks(CounterPair.second, Chunks)) {
186 return;
187 }
188
189 unsigned CounterID = getCounterId(std::string(CounterName));
190 if (!CounterID) {
191 errs() << "DebugCounter Error: " << CounterName
192 << " is not a registered counter\n";
193 return;
194 }
196
197 CounterInfo &Counter = Counters[CounterID];
198 Counter.IsSet = true;
199 Counter.Chunks = std::move(Chunks);
200}
201
205 sort(CounterNames);
206
207 auto &Us = instance();
208 OS << "Counters and values:\n";
209 for (auto &CounterName : CounterNames) {
210 unsigned CounterID = getCounterId(std::string(CounterName));
211 OS << left_justify(RegisteredCounters[CounterID], 32) << ": {"
212 << Us.Counters[CounterID].Count << ",";
213 printChunks(OS, Us.Counters[CounterID].Chunks);
214 OS << "}\n";
215 }
216}
217
218bool DebugCounter::shouldExecuteImpl(unsigned CounterName) {
219 auto &Us = instance();
220 auto Result = Us.Counters.find(CounterName);
221 if (Result != Us.Counters.end()) {
222 auto &CounterInfo = Result->second;
223 int64_t CurrCount = CounterInfo.Count++;
225
226 if (CounterInfo.Chunks.empty())
227 return true;
228 if (CurrIdx >= CounterInfo.Chunks.size())
229 return false;
230
231 bool Res = CounterInfo.Chunks[CurrIdx].contains(CurrCount);
232 if (Us.BreakOnLast && CurrIdx == (CounterInfo.Chunks.size() - 1) &&
233 CurrCount == CounterInfo.Chunks[CurrIdx].End) {
235 }
236 if (CurrCount > CounterInfo.Chunks[CurrIdx].End) {
238
239 /// Handle consecutive blocks.
241 CurrCount == CounterInfo.Chunks[CounterInfo.CurrChunkIdx].Begin)
242 return true;
243 }
244 return Res;
245 }
246 // Didn't find the counter, should we warn?
247 return true;
248}
249
251 print(dbgs());
252}
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
Analysis containing CSE Info
Definition: CSEInfo.cpp:27
#define LLVM_BUILTIN_DEBUGTRAP
LLVM_BUILTIN_DEBUGTRAP - On compilers which support it, expands to an expression which causes the pro...
Definition: Compiler.h:388
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition: Compiler.h:533
This file provides an implementation of debug counters.
std::string Name
raw_pwrite_stream & OS
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:160
static void printChunks(raw_ostream &OS, ArrayRef< Chunk >)
DenseMap< unsigned, CounterInfo > Counters
Definition: DebugCounter.h:178
CounterVector RegisteredCounters
Definition: DebugCounter.h:179
void push_back(const std::string &)
unsigned getCounterId(const std::string &Name) const
Definition: DebugCounter.h:127
static bool shouldExecuteImpl(unsigned CounterName)
static void enableAllCounters()
Definition: DebugCounter.h:151
static bool parseChunks(StringRef Str, SmallVector< Chunk > &Res)
Return true on parsing error and print the error message on the llvm::errs()
static DebugCounter & instance()
Returns a reference to the singleton instance.
void print(raw_ostream &OS) const
LLVM_DUMP_METHOD void dump() const
bool empty() const
Definition: SmallVector.h:94
size_t size() const
Definition: SmallVector.h:91
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition: StringRef.h:685
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:250
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:134
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
Definition: StringRef.h:594
StringRef take_until(function_ref< bool(char)> F) const
Return the longest prefix of 'this' such that no character in the prefix satisfies the given predicat...
Definition: StringRef.h:588
iterator end()
Return an iterator to the end of the vector.
Definition: UniqueVector.h:81
iterator begin()
Return an iterator to the start of the vector.
Definition: UniqueVector.h:75
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
@ CommaSeparated
Definition: CommandLine.h:163
LocationClass< Ty > location(Ty &L)
Definition: CommandLine.h:463
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
raw_fd_ostream & outs()
This returns a reference to a raw_fd_ostream for standard output.
void initDebugCounterOptions()
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1647
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
FormattedString left_justify(StringRef Str, unsigned Width)
left_justify - append spaces after string so total output is Width characters.
Definition: Format.h:146
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
void print(llvm::raw_ostream &OS)
SmallVector< Chunk > Chunks
Definition: DebugCounter.h:175