clang-tools 24.0.0git
ClangDocBenchmark.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// This file contains basic benchmarks for clang-doc's implementation and
11/// library components.
12///
13//===----------------------------------------------------------------------===//
14
15#include "BitcodeReader.h"
16#include "BitcodeWriter.h"
17#include "ClangDoc.h"
18#include "Generators.h"
19#include "Representation.h"
20#include "Serialize.h"
21#include "benchmark/benchmark.h"
22#include "clang/AST/ASTContext.h"
23#include "clang/AST/RecursiveASTVisitor.h"
24#include "clang/Tooling/Execution.h"
25#include "clang/Tooling/Tooling.h"
26#include "llvm/Bitstream/BitstreamWriter.h"
27#include <memory>
28#include <random>
29#include <string>
30#include <vector>
31
32namespace clang {
33namespace doc {
34
35class BenchmarkVisitor : public RecursiveASTVisitor<BenchmarkVisitor> {
36public:
37 explicit BenchmarkVisitor(const FunctionDecl *&Func) : Func(Func) {}
38
39 bool VisitFunctionDecl(const FunctionDecl *D) {
40 if (D->getName() == "f") {
41 Func = D;
42 return false;
43 }
44 return true;
45 }
46
47private:
48 const FunctionDecl *&Func;
49};
50
51// --- Mapper Benchmarks ---
52
53static void BM_EmitInfoFunction(benchmark::State &State) {
54 std::string Code = "void f() {}";
55 std::unique_ptr<clang::ASTUnit> AST = clang::tooling::buildASTFromCode(Code);
56 const FunctionDecl *Func = nullptr;
57 BenchmarkVisitor Visitor(Func);
58 Visitor.TraverseDecl(AST->getASTContext().getTranslationUnitDecl());
59 assert(Func);
60
61 clang::comments::FullComment *FC = nullptr;
62 Location Loc;
63
64 for (auto _ : State) {
65 serialize::Serializer Serializer;
66 auto Result = Serializer.emitInfo(Func, FC, Loc, /*PublicOnly=*/false);
67 benchmark::DoNotOptimize(Result);
68 }
69}
71
72static void BM_Mapper_Scale(benchmark::State &State) {
73 std::string Code;
74 for (int i = 0; i < State.range(0); ++i) {
75 Code += "void f" + std::to_string(i) + "() {}\n";
76 }
77
78 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
79 DiagnosticOptions DiagOpts;
80 DiagnosticsEngine Diags(DiagID, DiagOpts, new IgnoringDiagConsumer());
81
82 for (auto _ : State) {
83 tooling::InMemoryToolResults Results;
84 tooling::ExecutionContext ECtx(&Results);
85 ClangDocContext CDCtx(&ECtx, "test-project", false, "", "", "", "", "", {},
86 Diags, OutputFormatTy::json, false);
87 auto ActionFactory = doc::newMapperActionFactory(CDCtx);
88 std::unique_ptr<FrontendAction> Action = ActionFactory->create();
89 tooling::runToolOnCode(std::move(Action), Code, "test.cpp");
90 }
91}
92BENCHMARK(BM_Mapper_Scale)->Range(10, 10000);
93
94// --- Reducer Benchmarks ---
95
96static void BM_SerializeFunctionInfo(benchmark::State &State) {
98 I->Name = "f";
99 I->DefLoc = Location(0, 0, "test.cpp");
100 I->ReturnType = TypeInfo("void");
101 I->IT = InfoType::IT_function;
102
103 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
104 DiagnosticOptions DiagOpts;
105 DiagnosticsEngine Diags(DiagID, DiagOpts, new IgnoringDiagConsumer());
106
107 Info *InfoPtr = I;
108
109 for (auto _ : State) {
110 auto Result = serialize::serialize(*InfoPtr, Diags);
111 benchmark::DoNotOptimize(Result);
112 }
113}
115
116static void BM_MergeInfos_Scale(benchmark::State &State) {
117 SymbolID USR = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
118 11, 12, 13, 14, 15, 16, 17, 18, 19, 20};
119
120 for (auto _ : State) {
121 State.PauseTiming();
123 Input.reserve(State.range(0));
124 for (int Idx = 0; Idx < State.range(0); ++Idx) {
126 I->Name = "f";
127 I->USR = USR;
128 I->DefLoc = Location(10, Idx, "test.cpp");
129 Input.push_back(std::move(I));
130 }
131 State.ResumeTiming();
132
133 auto Result = doc::mergeInfos(Input);
134 if (!Result) {
135 State.SkipWithError("mergeInfos failed");
136 llvm::consumeError(Result.takeError());
137 }
138 benchmark::DoNotOptimize(Result);
139 }
140}
142
143static void BM_BitcodeReader_Scale(benchmark::State &State) {
144 int NumRecords = State.range(0);
145
146 SmallString<0> Buffer;
147 llvm::BitstreamWriter Stream(Buffer);
148 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
149 DiagnosticOptions DiagOpts;
150 DiagnosticsEngine Diags(DiagID, DiagOpts, new IgnoringDiagConsumer());
151
152 ClangDocBitcodeWriter Writer(Stream, Diags);
153 for (int i = 0; i < NumRecords; ++i) {
154 RecordInfo RI;
155 RI.Name = internString("Record" + std::to_string(i));
156 RI.USR = {(uint8_t)(i & 0xFF)};
157 Writer.emitBlock(RI);
158 }
159
160 std::string BitcodeData = Buffer.str().str();
161
162 for (auto _ : State) {
163 llvm::BitstreamCursor Cursor(llvm::ArrayRef<uint8_t>(
164 (const uint8_t *)BitcodeData.data(), BitcodeData.size()));
165 ClangDocBitcodeReader Reader(Cursor, Diags);
166 auto Result = Reader.readBitcode();
167 if (!Result) {
168 State.SkipWithError("readBitcode failed");
169 llvm::consumeError(Result.takeError());
170 }
171 benchmark::DoNotOptimize(Result);
172 }
173}
175
176// --- Generator Benchmarks ---
177
178static void BM_JSONGenerator_Scale(benchmark::State &State) {
179 auto G = doc::findGeneratorByName("json");
180 if (!G) {
181 State.SkipWithError("JSON Generator not found");
182 llvm::consumeError(G.takeError());
183 return;
184 }
185 int NumRecords = State.range(0);
187 NI->Name = "GlobalNamespace";
188 for (int i = 0; i < NumRecords; ++i) {
189 NI->Children.Records.push_back(*allocateListNodeTransient<Reference>(
190 SymbolID{(uint8_t)(i & 0xFF)}, "Record" + std::to_string(i),
192 }
193
194 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
195 DiagnosticOptions DiagOpts;
196 DiagnosticsEngine Diags(DiagID, DiagOpts, new IgnoringDiagConsumer());
197 ClangDocContext CDCtx(nullptr, "test-project", false, "", "", "", "", "", {},
198 Diags, OutputFormatTy::json, false);
199
200 std::string Output;
201 llvm::raw_string_ostream OS(Output);
202
203 for (auto _ : State) {
204 Output.clear();
205 auto Err = (*G)->generateDocForInfo(NI, OS, CDCtx);
206 if (Err) {
207 State.SkipWithError("generateDocForInfo failed");
208 llvm::consumeError(std::move(Err));
209 }
210 benchmark::DoNotOptimize(Output);
211 }
212}
214
215// --- Index Benchmarks ---
216
217static void BM_Index_Insertion(benchmark::State &State) {
218 for (auto _ : State) {
219 Index Idx;
220 for (int i = 0; i < State.range(0); ++i) {
221 RecordInfo I;
222 I.Name = internString("Record" + std::to_string(i));
223 // Vary USR to ensure unique entries
224 I.USR = {(uint8_t)(i & 0xFF), (uint8_t)((i >> 8) & 0xFF)};
225 I.Path = internString("path/to/record");
227 }
228 benchmark::DoNotOptimize(Idx);
229 }
230}
231BENCHMARK(BM_Index_Insertion)->Range(10, 10000);
232
233// --- String Pool Benchmarks ---
234
235static std::unique_ptr<ConcurrentStringPool> &getBenchmarkStringPool() {
236 static std::unique_ptr<ConcurrentStringPool> Pool;
237 return Pool;
238}
239
240static const std::vector<llvm::StringRef> &getBenchmarkTrace() {
241 static const std::vector<std::string> Corpus = [] {
242 constexpr size_t NumUniqueStrings = 1 << 18;
243 std::vector<std::string> V(NumUniqueStrings);
244 for (size_t I = 0; I < V.size(); ++I)
245 V[I] = "/usr/local/include/clang/AST/Decl_" + std::to_string(I) + ".h";
246 return V;
247 }();
248
249 static const std::vector<llvm::StringRef> Trace = [] {
250 constexpr size_t NumHotStrings = 64;
251 constexpr size_t TraceSize = 1 << 20;
252 std::minstd_rand Rng;
253 std::bernoulli_distribution IsHot(0.8);
254 std::uniform_int_distribution<size_t> HotDist(0, NumHotStrings - 1);
255 std::uniform_int_distribution<size_t> ColdDist(0, Corpus.size() - 1);
256
257 std::vector<llvm::StringRef> T(TraceSize);
258 for (llvm::StringRef &S : T)
259 S = Corpus[IsHot(Rng) ? HotDist(Rng) : ColdDist(Rng)];
260 return T;
261 }();
262 return Trace;
263}
264
265static void BM_StringPool_ConcurrentStringPool(benchmark::State &State) {
266 auto &SharedPool = *getBenchmarkStringPool();
267 const auto &Trace = getBenchmarkTrace();
268 const size_t Mask = Trace.size() - 1;
269 size_t Idx = State.thread_index() * (Trace.size() / State.threads());
270
271 for (auto _ : State) {
272 llvm::StringRef Res = SharedPool.save(Trace[Idx & Mask]);
273 benchmark::DoNotOptimize(Res);
274 ++Idx;
275 }
276}
277
279 ->ThreadRange(1, 128)
280 ->UseRealTime()
281 ->Setup([](const benchmark::State &) {
282 getBenchmarkStringPool() = std::make_unique<ConcurrentStringPool>();
283 })
284 ->Teardown([](const benchmark::State &) {
285 getBenchmarkStringPool().reset();
286 });
287
288} // namespace doc
289} // namespace clang
290
BENCHMARK_MAIN()
bool VisitFunctionDecl(const FunctionDecl *D)
BenchmarkVisitor(const FunctionDecl *&Func)
llvm::Expected< std::vector< Info * > > readBitcode()
void emitBlock(const NamespaceInfo &I)
static void addInfoToIndex(Index &Idx, const doc::Info *Info)
std::pair< Info *, Info * > emitInfo(const NamespaceDecl *D, const FullComment *FC, Location Loc, bool PublicOnly)
static std::string serialize(const T &I, DiagnosticsEngine &Diags)
static void BM_BitcodeReader_Scale(benchmark::State &State)
static const std::vector< llvm::StringRef > & getBenchmarkTrace()
static void BM_MergeInfos_Scale(benchmark::State &State)
std::unique_ptr< tooling::FrontendActionFactory > newMapperActionFactory(ClangDocContext CDCtx)
Definition ClangDoc.cpp:52
llvm::Expected< std::unique_ptr< Generator > > findGeneratorByName(llvm::StringRef Format)
T * allocateTransient(Args &&...args)
static void BM_StringPool_ConcurrentStringPool(benchmark::State &State)
static std::unique_ptr< ConcurrentStringPool > & getBenchmarkStringPool()
BENCHMARK(BM_EmitInfoFunction)
static void BM_EmitInfoFunction(benchmark::State &State)
static void BM_Index_Insertion(benchmark::State &State)
static void BM_SerializeFunctionInfo(benchmark::State &State)
StringRef internString(const Twine &T)
llvm::Expected< Info * > mergeInfos(SmallVectorImpl< Info * > &Values)
InfoNode< T > * allocateListNodeTransient(Args &&...args)
std::array< uint8_t, 20 > SymbolID
static void BM_JSONGenerator_Scale(benchmark::State &State)
static void BM_Mapper_Scale(benchmark::State &State)
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
A base struct for Infos.