tokenized_buffer_benchmark.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include <benchmark/benchmark.h>
  5. #include <algorithm>
  6. #include <utility>
  7. #include "absl/random/random.h"
  8. #include "common/check.h"
  9. #include "common/raw_string_ostream.h"
  10. #include "llvm/ADT/Sequence.h"
  11. #include "llvm/ADT/StringExtras.h"
  12. #include "testing/base/source_gen.h"
  13. #include "toolchain/base/shared_value_stores.h"
  14. #include "toolchain/diagnostics/diagnostic_emitter.h"
  15. #include "toolchain/diagnostics/null_diagnostics.h"
  16. #include "toolchain/lex/lex.h"
  17. #include "toolchain/lex/token_kind.h"
  18. #include "toolchain/lex/tokenized_buffer.h"
  19. namespace Carbon::Lex {
  20. namespace {
  21. // A large value for measurement stability without making benchmarking too slow.
  22. // Needs to be a multiple of 100 so we can easily divide it up into percentages,
  23. // and 1% itself needs to not be too tiny. This makes 100,000 a great balance.
  24. constexpr int NumTokens = 100'000;
  25. // Compute a random sequence of just identifiers.
  26. static auto RandomIdentifierSeq(int min_length, int max_length, bool uniform,
  27. llvm::StringRef separator = " ")
  28. -> std::string {
  29. auto& gen = Testing::SourceGen::Global();
  30. llvm::SmallVector<llvm::StringRef> ids =
  31. gen.GetShuffledIdentifiers(NumTokens, min_length, max_length, uniform);
  32. return llvm::join(ids, separator);
  33. }
  34. auto GetSymbolTokenTable() -> llvm::ArrayRef<TokenKind> {
  35. // Build our own table of symbols so we can use repetitions to skew the
  36. // distribution.
  37. static auto symbol_token_table_storage = [] {
  38. llvm::SmallVector<TokenKind> table;
  39. #define CARBON_SYMBOL_TOKEN(TokenName, Spelling) \
  40. table.push_back(TokenKind::TokenName);
  41. #define CARBON_OPENING_GROUP_SYMBOL_TOKEN(TokenName, Spelling, ClosingName)
  42. #define CARBON_CLOSING_GROUP_SYMBOL_TOKEN(TokenName, Spelling, OpeningName)
  43. #include "toolchain/lex/token_kind.def"
  44. table.insert(table.end(), 32, TokenKind::Semi);
  45. table.insert(table.end(), 16, TokenKind::Comma);
  46. table.insert(table.end(), 12, TokenKind::Period);
  47. table.insert(table.end(), 8, TokenKind::Colon);
  48. table.insert(table.end(), 8, TokenKind::Equal);
  49. table.insert(table.end(), 4, TokenKind::Amp);
  50. table.insert(table.end(), 4, TokenKind::ColonExclaim);
  51. table.insert(table.end(), 4, TokenKind::EqualEqual);
  52. table.insert(table.end(), 4, TokenKind::ExclaimEqual);
  53. table.insert(table.end(), 4, TokenKind::MinusGreater);
  54. table.insert(table.end(), 4, TokenKind::Star);
  55. return table;
  56. }();
  57. return symbol_token_table_storage;
  58. }
  59. struct RandomSourceOptions {
  60. int symbol_percent = 0;
  61. int keyword_percent = 0;
  62. int numeric_literal_percent = 0;
  63. int string_literal_percent = 0;
  64. int tokens_per_line = NumTokens;
  65. int comment_line_percent = 0;
  66. int blank_line_percent = 0;
  67. void Validate() {
  68. auto is_percentage = [](int n) { return 0 <= n && n <= 100; };
  69. CARBON_CHECK(is_percentage(symbol_percent));
  70. CARBON_CHECK(is_percentage(keyword_percent));
  71. CARBON_CHECK(is_percentage(numeric_literal_percent));
  72. CARBON_CHECK(is_percentage(string_literal_percent));
  73. CARBON_CHECK(is_percentage(symbol_percent + keyword_percent +
  74. numeric_literal_percent +
  75. string_literal_percent));
  76. CARBON_CHECK(tokens_per_line <= NumTokens);
  77. CARBON_CHECK(
  78. NumTokens % tokens_per_line == 0,
  79. "Tokens per line of {0} does not divide the number of tokens {1}",
  80. tokens_per_line, NumTokens);
  81. CARBON_CHECK(is_percentage(comment_line_percent));
  82. CARBON_CHECK(is_percentage(blank_line_percent));
  83. // Ensure that comment and blank lines are less than 100% so we eventually
  84. // produce a token line.
  85. CARBON_CHECK(comment_line_percent + blank_line_percent < 100);
  86. }
  87. };
  88. // Based on measurements of LLVM's source code, a rough approximation of the
  89. // distribution of these kinds of tokens.
  90. constexpr RandomSourceOptions DefaultSourceDist = {
  91. .symbol_percent = 50,
  92. .keyword_percent = 7,
  93. .numeric_literal_percent = 17,
  94. .string_literal_percent = 1,
  95. // The median for LLVM is roughly 5.
  96. .tokens_per_line = 5,
  97. // Observed percentage of lines in LLVM.
  98. .comment_line_percent = 22,
  99. .blank_line_percent = 15,
  100. };
  101. // Compute random source code with a mixture of tokens and whitespace according
  102. // to the options. The source isn't designed to be valid, or directly
  103. // representative of real-world Carbon code. However, it tries to provide
  104. // reasonable coverage of the different aspects of Carbon's lexer, such that for
  105. // real world source code with distributions similar to the options provided the
  106. // lexer performance will be roughly representative.
  107. //
  108. // TODO: Does not yet support generating numeric or string literals.
  109. //
  110. // TODO: The shape of lines is handled very arbitrarily and should vary more to
  111. // avoid over-fitting to a specific shape (number of tokens, length of comment).
  112. auto RandomSource(RandomSourceOptions options) -> std::string {
  113. options.Validate();
  114. static_assert((NumTokens % 100) == 0,
  115. "The number of tokens must be divisible by 100 so that we can "
  116. "easily scale integer percentages up to it.");
  117. // Get static pools of symbols, keywords, and identifiers.
  118. llvm::ArrayRef<TokenKind> symbols = GetSymbolTokenTable();
  119. llvm::ArrayRef<TokenKind> keywords = TokenKind::KeywordTokens;
  120. // Build a list of StringRefs from the different types with the desired
  121. // distribution, then shuffle that list.
  122. llvm::OwningArrayRef<llvm::StringRef> tokens(NumTokens);
  123. int num_symbols = (NumTokens / 100) * options.symbol_percent;
  124. int num_keywords = (NumTokens / 100) * options.keyword_percent;
  125. int num_identifiers = NumTokens - num_symbols - num_keywords;
  126. CARBON_CHECK(
  127. num_identifiers == 0 || num_identifiers > 500,
  128. "We require at least 500 identifiers as we need to collect a reasonable "
  129. "number of samples to end up with a reasonable distribution of lengths.");
  130. llvm::SmallVector<llvm::StringRef> ids =
  131. Testing::SourceGen::Global().GetIdentifiers(num_identifiers);
  132. for (int i : llvm::seq(num_symbols)) {
  133. tokens[i] = symbols[i % symbols.size()].fixed_spelling();
  134. }
  135. for (int i : llvm::seq(num_keywords)) {
  136. tokens[num_symbols + i] = keywords[i % keywords.size()].fixed_spelling();
  137. }
  138. for (int i : llvm::seq(num_identifiers)) {
  139. // We always have enough identifiers, so no need to mod here.
  140. tokens[num_symbols + num_keywords + i] = ids[i];
  141. }
  142. std::shuffle(tokens.begin(), tokens.end(), absl::BitGen());
  143. // Distribute the tokens across lines as well as horizontal whitespace. The
  144. // goal isn't to make any one line representative of anything, but to make the
  145. // rough density of different kinds of whitespace roughly representative.
  146. //
  147. // TODO: This is a really coarse approach that just picks a fixed number of
  148. // tokens per line rather than using some distribution with this as the median
  149. // or mean.
  150. llvm::SmallVector<std::string> lines;
  151. // First place tokens onto each line.
  152. for (auto i : llvm::seq(NumTokens / options.tokens_per_line)) {
  153. lines.push_back("");
  154. RawStringOstream os;
  155. // Arbitrarily indent each line by two spaces.
  156. os << " ";
  157. llvm::ListSeparator sep(" ");
  158. for (int j : llvm::seq(options.tokens_per_line)) {
  159. os << sep << tokens[i * options.tokens_per_line + j];
  160. }
  161. lines.push_back(os.TakeStr());
  162. }
  163. // Next, synthesize blank and comment lines with the correct distribution.
  164. int token_line_percent =
  165. 100 - options.blank_line_percent - options.comment_line_percent;
  166. CARBON_CHECK(token_line_percent > 0);
  167. int num_token_lines = lines.size();
  168. int num_lines = num_token_lines * 100 / token_line_percent;
  169. int num_blank_lines = num_lines * options.blank_line_percent / 100;
  170. int num_comment_lines = num_lines - num_blank_lines - num_token_lines;
  171. CARBON_CHECK(num_comment_lines >= 0);
  172. lines.resize(num_lines);
  173. for (auto& line :
  174. llvm::MutableArrayRef(lines).slice(num_lines - num_comment_lines)) {
  175. // TODO: We should vary the content and length, especially as the
  176. // distribution is weirdly shaped with just over half the comment lines
  177. // being blank and the median length of non-black comment lines being 64!
  178. // This is a *very* coarse approximation of the mean at 30 characters long.
  179. line = " // abcdefghijklmnopqrstuvwxyz";
  180. }
  181. // Now shuffle the lines.
  182. std::shuffle(lines.begin(), lines.end(), absl::BitGen());
  183. // And join them into the source string.
  184. return llvm::join(lines, "\n");
  185. }
  186. class LexerBenchHelper {
  187. public:
  188. explicit LexerBenchHelper(llvm::StringRef text)
  189. : source_(MakeSourceBuffer(text)) {}
  190. auto Lex() -> TokenizedBuffer {
  191. DiagnosticConsumer& consumer = NullDiagnosticConsumer();
  192. return Lex::Lex(value_stores_, source_, consumer);
  193. }
  194. auto DiagnoseErrors() -> std::string {
  195. RawStringOstream result;
  196. StreamDiagnosticConsumer consumer(result,
  197. /*include_diagnostic_kind=*/false);
  198. auto buffer = Lex::Lex(value_stores_, source_, consumer);
  199. consumer.Flush();
  200. CARBON_CHECK(buffer.has_errors(),
  201. "Asked to diagnose errors but none found!");
  202. return result.TakeStr();
  203. }
  204. auto source_text() -> llvm::StringRef { return source_.text(); }
  205. private:
  206. auto MakeSourceBuffer(llvm::StringRef text) -> SourceBuffer {
  207. CARBON_CHECK(fs_.addFile(filename_, /*ModificationTime=*/0,
  208. llvm::MemoryBuffer::getMemBuffer(text)));
  209. return std::move(*SourceBuffer::MakeFromFile(fs_, filename_,
  210. ConsoleDiagnosticConsumer()));
  211. }
  212. SharedValueStores value_stores_;
  213. llvm::vfs::InMemoryFileSystem fs_;
  214. std::string filename_ = "test.carbon";
  215. SourceBuffer source_;
  216. };
  217. void BM_ValidKeywords(benchmark::State& state) {
  218. absl::BitGen gen;
  219. std::array<llvm::StringRef, NumTokens> tokens;
  220. for (int i : llvm::seq(NumTokens)) {
  221. tokens[i] = TokenKind::KeywordTokens[i % TokenKind::KeywordTokens.size()]
  222. .fixed_spelling();
  223. }
  224. std::shuffle(tokens.begin(), tokens.end(), gen);
  225. std::string source = llvm::join(tokens, " ");
  226. LexerBenchHelper helper(source);
  227. for (auto _ : state) {
  228. TokenizedBuffer buffer = helper.Lex();
  229. CARBON_CHECK(!buffer.has_errors());
  230. }
  231. state.SetBytesProcessed(state.iterations() * source.size());
  232. state.counters["tokens_per_second"] = benchmark::Counter(
  233. NumTokens, benchmark::Counter::kIsIterationInvariantRate);
  234. }
  235. BENCHMARK(BM_ValidKeywords);
  236. void BM_ValidKeywordsAsRawIdentifiers(benchmark::State& state) {
  237. absl::BitGen gen;
  238. std::array<llvm::StringRef, NumTokens> tokens;
  239. for (int i : llvm::seq(NumTokens)) {
  240. tokens[i] = TokenKind::KeywordTokens[i % TokenKind::KeywordTokens.size()]
  241. .fixed_spelling();
  242. }
  243. std::shuffle(tokens.begin(), tokens.end(), gen);
  244. std::string source("r#");
  245. source.append(llvm::join(tokens, " r#"));
  246. LexerBenchHelper helper(source);
  247. for (auto _ : state) {
  248. TokenizedBuffer buffer = helper.Lex();
  249. CARBON_CHECK(!buffer.has_errors());
  250. }
  251. state.SetBytesProcessed(state.iterations() * source.size());
  252. state.counters["tokens_per_second"] = benchmark::Counter(
  253. NumTokens, benchmark::Counter::kIsIterationInvariantRate);
  254. }
  255. BENCHMARK(BM_ValidKeywordsAsRawIdentifiers);
  256. // This benchmark does a 50-50 split of r-prefixed and r#-prefixed identifiers
  257. // to directly compare raw and non-raw performance.
  258. void BM_RawIdentifierFocus(benchmark::State& state) {
  259. llvm::SmallVector<llvm::StringRef> ids =
  260. Testing::SourceGen::Global().GetIdentifiers(NumTokens / 2);
  261. llvm::SmallVector<std::string> modified_ids;
  262. // As we resize, start with the in-use prefix. Note that `r#` uses the first
  263. // character of the original identifier.
  264. modified_ids.resize(NumTokens / 2, "r#");
  265. modified_ids.resize(NumTokens, "r");
  266. for (int i : llvm::seq(NumTokens / 2)) {
  267. // Use the same identifier both ways.
  268. modified_ids[i].append(ids[i]);
  269. modified_ids[i + NumTokens / 2].append(
  270. llvm::StringRef(ids[i]).drop_front());
  271. }
  272. absl::BitGen gen;
  273. std::array<llvm::StringRef, NumTokens> tokens;
  274. for (int i : llvm::seq(NumTokens)) {
  275. tokens[i] = modified_ids[i];
  276. }
  277. std::shuffle(tokens.begin(), tokens.end(), gen);
  278. std::string source = llvm::join(tokens, " ");
  279. LexerBenchHelper helper(source);
  280. for (auto _ : state) {
  281. TokenizedBuffer buffer = helper.Lex();
  282. CARBON_CHECK(!buffer.has_errors());
  283. }
  284. state.SetBytesProcessed(state.iterations() * source.size());
  285. state.counters["tokens_per_second"] = benchmark::Counter(
  286. NumTokens, benchmark::Counter::kIsIterationInvariantRate);
  287. }
  288. BENCHMARK(BM_RawIdentifierFocus);
  289. template <int MinLength, int MaxLength, bool Uniform>
  290. void BM_ValidIdentifiers(benchmark::State& state) {
  291. std::string source = RandomIdentifierSeq(MinLength, MaxLength, Uniform);
  292. LexerBenchHelper helper(source);
  293. for (auto _ : state) {
  294. TokenizedBuffer buffer = helper.Lex();
  295. CARBON_CHECK(!buffer.has_errors(), "{0}", helper.DiagnoseErrors());
  296. }
  297. state.SetBytesProcessed(state.iterations() * source.size());
  298. state.counters["tokens_per_second"] = benchmark::Counter(
  299. NumTokens, benchmark::Counter::kIsIterationInvariantRate);
  300. }
  301. // Benchmark the non-uniform distribution we observe in C++ code.
  302. BENCHMARK(BM_ValidIdentifiers<1, 64, /*Uniform=*/false>);
  303. // Also benchmark a few uniform distribution ranges of identifier widths to
  304. // cover different patterns that emerge with small, medium, and longer
  305. // identifiers.
  306. BENCHMARK(BM_ValidIdentifiers<1, 1, /*Uniform=*/true>);
  307. BENCHMARK(BM_ValidIdentifiers<3, 5, /*Uniform=*/true>);
  308. BENCHMARK(BM_ValidIdentifiers<3, 16, /*Uniform=*/true>);
  309. BENCHMARK(BM_ValidIdentifiers<12, 64, /*Uniform=*/true>);
  310. BENCHMARK(BM_ValidIdentifiers<16, 16, /*Uniform=*/true>);
  311. BENCHMARK(BM_ValidIdentifiers<24, 24, /*Uniform=*/true>);
  312. BENCHMARK(BM_ValidIdentifiers<32, 32, /*Uniform=*/true>);
  313. BENCHMARK(BM_ValidIdentifiers<48, 48, /*Uniform=*/true>);
  314. BENCHMARK(BM_ValidIdentifiers<64, 64, /*Uniform=*/true>);
  315. BENCHMARK(BM_ValidIdentifiers<80, 80, /*Uniform=*/true>);
  316. // Benchmark to stress the lexing of horizontal whitespace. This sets up what is
  317. // nearly a worst-case scenario of short-but-expensive-to-lex tokens with runs
  318. // of horizontal whitespace between them.
  319. void BM_HorizontalWhitespace(benchmark::State& state) {
  320. int num_spaces = state.range(0);
  321. std::string separator(num_spaces, ' ');
  322. std::string source = RandomIdentifierSeq(3, 5, /*uniform=*/true, separator);
  323. LexerBenchHelper helper(source);
  324. for (auto _ : state) {
  325. TokenizedBuffer buffer = helper.Lex();
  326. // Ensure that lexing actually occurs for benchmarking and that it doesn't
  327. // hit errors that would skew the benchmark results.
  328. CARBON_CHECK(!buffer.has_errors(), "{0}", helper.DiagnoseErrors());
  329. }
  330. state.SetBytesProcessed(state.iterations() * source.size());
  331. state.counters["tokens_per_second"] = benchmark::Counter(
  332. NumTokens, benchmark::Counter::kIsIterationInvariantRate);
  333. }
  334. BENCHMARK(BM_HorizontalWhitespace)->RangeMultiplier(4)->Range(1, 128);
  335. void BM_RandomSource(benchmark::State& state) {
  336. std::string source = RandomSource(DefaultSourceDist);
  337. LexerBenchHelper helper(source);
  338. for (auto _ : state) {
  339. TokenizedBuffer buffer = helper.Lex();
  340. // Ensure that lexing actually occurs for benchmarking and that it doesn't
  341. // hit errors that would skew the benchmark results.
  342. CARBON_CHECK(!buffer.has_errors(), "{0}", helper.DiagnoseErrors());
  343. }
  344. state.SetBytesProcessed(state.iterations() * source.size());
  345. state.counters["tokens_per_second"] = benchmark::Counter(
  346. NumTokens, benchmark::Counter::kIsIterationInvariantRate);
  347. state.counters["lines_per_second"] =
  348. benchmark::Counter(llvm::StringRef(source).count('\n'),
  349. benchmark::Counter::kIsIterationInvariantRate);
  350. }
  351. // The distributions between symbols, keywords, and identifiers here are
  352. // guesses. Eventually, we should collect more data to help tune these, but
  353. // hopefully the performance isn't too sensitive and we can just cover a wide
  354. // range here.
  355. BENCHMARK(BM_RandomSource);
  356. // Benchmark to stress opening and closing grouped symbols.
  357. void BM_GroupingSymbols(benchmark::State& state) {
  358. int curly_brace_depth = state.range(0);
  359. int paren_depth = state.range(1);
  360. int square_bracket_depth = state.range(2);
  361. // TODO: It might be interesting to have some random pattern of nesting, but
  362. // the obvious ways to do that result it really unstable total size of input
  363. // or unbalanced groups. For now, just use a simple strict nesting approach.
  364. // It should still let us look for specific pain points. We do include some
  365. // whitespace and keywords to make sure *some* other parts of the benchmark
  366. // are also active and have some reasonable icache pressure.
  367. llvm::SmallVector<llvm::StringRef> ids =
  368. Testing::SourceGen::Global().GetShuffledIdentifiers(NumTokens);
  369. RawStringOstream os;
  370. int num_tokens_per_nest =
  371. curly_brace_depth * 2 + paren_depth * 2 + square_bracket_depth * 2 + 2;
  372. int num_nests = NumTokens / num_tokens_per_nest;
  373. for (int i : llvm::seq(num_nests)) {
  374. for (int j : llvm::seq(curly_brace_depth)) {
  375. os.indent(j * 2) << "{\n";
  376. }
  377. os.indent(curly_brace_depth * 2);
  378. for ([[maybe_unused]] int j : llvm::seq(paren_depth)) {
  379. os << "(";
  380. }
  381. for ([[maybe_unused]] int j : llvm::seq(square_bracket_depth)) {
  382. os << "[";
  383. }
  384. os << ids[(i * 2) % NumTokens];
  385. for ([[maybe_unused]] int j : llvm::seq(square_bracket_depth)) {
  386. os << "]";
  387. }
  388. for ([[maybe_unused]] int j : llvm::seq(paren_depth)) {
  389. os << ")";
  390. }
  391. for (int j : llvm::reverse(llvm::seq(curly_brace_depth))) {
  392. os << "\n";
  393. os.indent(j * 2) << "}";
  394. }
  395. os << ids[(i * 2 + 1) % NumTokens] << "\n";
  396. }
  397. std::string source = os.TakeStr();
  398. LexerBenchHelper helper(source);
  399. for (auto _ : state) {
  400. TokenizedBuffer buffer = helper.Lex();
  401. // Ensure that lexing actually occurs for benchmarking and that it doesn't
  402. // hit errors that would skew the benchmark results.
  403. CARBON_CHECK(!buffer.has_errors(), "{0}", helper.DiagnoseErrors());
  404. }
  405. state.SetBytesProcessed(state.iterations() * source.size());
  406. state.counters["tokens_per_second"] = benchmark::Counter(
  407. NumTokens, benchmark::Counter::kIsIterationInvariantRate);
  408. state.counters["lines_per_second"] =
  409. benchmark::Counter(llvm::StringRef(source).count('\n'),
  410. benchmark::Counter::kIsIterationInvariantRate);
  411. }
  412. BENCHMARK(BM_GroupingSymbols)
  413. ->ArgsProduct({
  414. {1, 2, 3, 4, 8, 16, 32},
  415. {0},
  416. {0},
  417. })
  418. ->ArgsProduct({
  419. {0},
  420. {1, 2, 3, 4, 8, 16, 32},
  421. {0},
  422. })
  423. ->ArgsProduct({
  424. {0},
  425. {0},
  426. {1, 2, 3, 4, 8, 16, 32},
  427. })
  428. ->ArgsProduct({
  429. {32},
  430. {1, 2, 3, 4, 8, 16, 32},
  431. {0},
  432. })
  433. ->ArgsProduct({
  434. {32},
  435. {32},
  436. {1, 2, 3, 4, 8, 16, 32},
  437. });
  438. // Benchmark to stress the lexing of blank lines. This uses a simple, easy to
  439. // lex token, but separates each one by varying numbers of blank lines.
  440. void BM_BlankLines(benchmark::State& state) {
  441. int num_blank_lines = state.range(0);
  442. std::string separator(num_blank_lines, '\n');
  443. std::string source = RandomIdentifierSeq(3, 5, /*uniform=*/true, separator);
  444. LexerBenchHelper helper(source);
  445. for (auto _ : state) {
  446. TokenizedBuffer buffer = helper.Lex();
  447. // Ensure that lexing actually occurs for benchmarking and that it doesn't
  448. // hit errors that would skew the benchmark results.
  449. CARBON_CHECK(!buffer.has_errors(), "{0}", helper.DiagnoseErrors());
  450. }
  451. state.SetBytesProcessed(state.iterations() * source.size());
  452. state.counters["tokens_per_second"] = benchmark::Counter(
  453. NumTokens, benchmark::Counter::kIsIterationInvariantRate);
  454. state.counters["lines_per_second"] =
  455. benchmark::Counter(llvm::StringRef(source).count('\n'),
  456. benchmark::Counter::kIsIterationInvariantRate);
  457. }
  458. BENCHMARK(BM_BlankLines)->RangeMultiplier(4)->Range(1, 128);
  459. // Benchmark to stress the lexing of comment lines. This uses a simple, easy to
  460. // lex token, but separates each one by varying numbers of comment lines, with
  461. // varying comment line length and indentation.
  462. void BM_CommentLines(benchmark::State& state) {
  463. int num_comment_lines = state.range(0);
  464. int comment_length = state.range(1);
  465. int comment_indent = state.range(2);
  466. RawStringOstream os;
  467. os << "\n";
  468. for (int i : llvm::seq(num_comment_lines)) {
  469. static_cast<void>(i);
  470. os << std::string(comment_indent, ' ') << "//"
  471. << std::string(comment_length, ' ') << "\n";
  472. }
  473. std::string source =
  474. RandomIdentifierSeq(3, 5, /*uniform=*/true, os.TakeStr());
  475. LexerBenchHelper helper(source);
  476. for (auto _ : state) {
  477. TokenizedBuffer buffer = helper.Lex();
  478. // Ensure that lexing actually occurs for benchmarking and that it doesn't
  479. // hit errors that would skew the benchmark results.
  480. CARBON_CHECK(!buffer.has_errors(), "{0}", helper.DiagnoseErrors());
  481. }
  482. state.SetBytesProcessed(state.iterations() * source.size());
  483. state.counters["tokens_per_second"] = benchmark::Counter(
  484. NumTokens, benchmark::Counter::kIsIterationInvariantRate);
  485. state.counters["lines_per_second"] =
  486. benchmark::Counter(llvm::StringRef(source).count('\n'),
  487. benchmark::Counter::kIsIterationInvariantRate);
  488. }
  489. BENCHMARK(BM_CommentLines)
  490. ->ArgsProduct({
  491. // How many lines of comment. Focused on a couple of small and checking
  492. // how it scales up to large blocks.
  493. {1, 4, 128},
  494. // Comment lengths: the two extremes and a middling length.
  495. {0, 30, 70},
  496. // Comment indentations.
  497. {0, 2, 8},
  498. });
  499. // This is a speed-of-light benchmark that should reflect memory bandwidth
  500. // (ideally) of simply reading all the source code. For speed-of-light we use
  501. // `strcpy` -- this both examines ever byte of the input looking for a null to
  502. // end the copy, and also writes to a data structure of roughly the same size as
  503. // the input. This routine is one we expect to be *very* well optimized and give
  504. // a good approximation of the fastest possible lexer given the physical
  505. // constraints of the machine. Note that which particular source we use as input
  506. // here isn't especially interesting, so we just pick one and should update it
  507. // to reflect whatever distribution is most realistic long-term. The
  508. // bytes/second throughput is the important output of this routine.
  509. auto BM_SpeedOfLightStrCpy(benchmark::State& state) -> void {
  510. std::string source = RandomSource(DefaultSourceDist);
  511. // A buffer to write the null-terminated contents of `source` into.
  512. llvm::OwningArrayRef<char> buffer(source.size() + 1);
  513. for (auto _ : state) {
  514. const char* text = source.data();
  515. benchmark::DoNotOptimize(text);
  516. strcpy(buffer.data(), text);
  517. benchmark::DoNotOptimize(buffer.data());
  518. }
  519. state.SetBytesProcessed(state.iterations() * source.size());
  520. state.counters["tokens_per_second"] = benchmark::Counter(
  521. NumTokens, benchmark::Counter::kIsIterationInvariantRate);
  522. state.counters["lines_per_second"] =
  523. benchmark::Counter(llvm::StringRef(source).count('\n'),
  524. benchmark::Counter::kIsIterationInvariantRate);
  525. }
  526. BENCHMARK(BM_SpeedOfLightStrCpy);
  527. // This is a speed-of-light benchmark that builds up a best-case byte-wise table
  528. // dispatch using guaranteed tail recursion. The goal is both to ensure the
  529. // general technique can reasonably hit the level of performance we need and to
  530. // establish how far from this speed of light the actual lexer currently sits.
  531. //
  532. // A major impact on the observed performance of this technique is how many
  533. // different functions are reached in this dispatch loop. This benchmark
  534. // infrastructure tries to bracket the range of performance this technique
  535. // affords with different numbers of dispatch target functions.
  536. using DispatchPtrT = auto (*)(ssize_t& index, const char* text, char* buffer)
  537. -> void;
  538. using DispatchTableT = std::array<DispatchPtrT, 256>;
  539. template <const DispatchTableT& Table>
  540. auto BasicDispatch(ssize_t& index, const char* text, char* buffer) -> void {
  541. *buffer = text[index];
  542. ++index;
  543. // NOLINTNEXTLINE(readability-avoid-return-with-void-value): For musttail.
  544. [[clang::musttail]] return Table[static_cast<unsigned char>(text[index])](
  545. index, text, buffer);
  546. }
  547. template <const DispatchTableT& Table, char C>
  548. auto SpecializedDispatch(ssize_t& index, const char* text, char* buffer)
  549. -> void {
  550. CARBON_CHECK(C == text[index]);
  551. *buffer = C;
  552. ++index;
  553. // NOLINTNEXTLINE(readability-avoid-return-with-void-value): For musttail.
  554. [[clang::musttail]] return Table[static_cast<unsigned char>(text[index])](
  555. index, text, buffer);
  556. }
  557. // A sample of the symbol characters used in Carbon code. Doesn't need to be
  558. // perfect, as we just need to have a reasonably large # of distinct dispatch
  559. // functions.
  560. constexpr char DispatchSpecializableSymbols[] = {
  561. '!', '%', '(', ')', '*', '+', ',', '-', '.', ':',
  562. ';', '<', '=', '>', '?', '[', ']', '{', '}', '~',
  563. };
  564. // Create an array of all the characters we can specialize dispatch over --
  565. // [0-9A-Za-z] and the symbols above. Similar to the above symbols, doesn't need
  566. // to be exhaustive.
  567. constexpr std::array<char, 26 * 2 + 10 + sizeof(DispatchSpecializableSymbols)>
  568. DispatchSpecializableChars = []() {
  569. constexpr int Size = sizeof(DispatchSpecializableChars);
  570. std::array<char, Size> chars = {};
  571. int i = 0;
  572. for (char c = '0'; c <= '9'; ++c) {
  573. chars[i] = c;
  574. ++i;
  575. }
  576. for (char c = 'A'; c <= 'Z'; ++c) {
  577. chars[i] = c;
  578. ++i;
  579. }
  580. for (char c = 'a'; c <= 'z'; ++c) {
  581. chars[i] = c;
  582. ++i;
  583. }
  584. for (char c : DispatchSpecializableSymbols) {
  585. chars[i] = c;
  586. ++i;
  587. }
  588. CARBON_CHECK(i == Size);
  589. return chars;
  590. }();
  591. // Instantiate a number of specialized dispatch functions for characters in the
  592. // array above, and assign those function addresses to the character's entry in
  593. // the provided table. The provided `tmp_table` is a temporary that will
  594. // eventually initialize the provided `Table` constant, so the constant is what
  595. // we propagate to the instantiated function and the temporary is the one we
  596. // initialize.
  597. template <const DispatchTableT& Table, size_t... Indices>
  598. constexpr auto SpecializeDispatchTable(
  599. DispatchTableT& tmp_table, std::index_sequence<Indices...> /*indices*/)
  600. -> void {
  601. static_assert(sizeof...(Indices) <= sizeof(DispatchSpecializableChars));
  602. ((tmp_table[static_cast<unsigned char>(DispatchSpecializableChars[Indices])] =
  603. &SpecializedDispatch<Table, DispatchSpecializableChars[Indices]>),
  604. ...);
  605. }
  606. // The maximum number of dispatch targets is the size of the array + 1 (for the
  607. // base case target).
  608. constexpr int MaxDispatchTargets = sizeof(DispatchSpecializableChars) + 1;
  609. // Dispatch tables with a provided number of distinct dispatch targets. There
  610. // will always be one additional target for the null byte to end the loop.
  611. template <int NumDispatchTargets>
  612. constexpr DispatchTableT DispatchTable = []() {
  613. static_assert(NumDispatchTargets > 0, "Need at least one dispatch target.");
  614. static_assert(NumDispatchTargets <= MaxDispatchTargets,
  615. "Limited number of dispatch targets available.");
  616. DispatchTableT tmp_table = {};
  617. // Start with the basic dispatch target.
  618. for (int i = 0; i < 256; ++i) {
  619. tmp_table[i] = &BasicDispatch<DispatchTable<NumDispatchTargets>>;
  620. }
  621. // NOLINTNEXTLINE(readability-braces-around-statements): False positive.
  622. if constexpr (NumDispatchTargets > 1) {
  623. // Add additional dispatch targets from our specializable array.
  624. SpecializeDispatchTable<DispatchTable<NumDispatchTargets>>(
  625. tmp_table, std::make_index_sequence<NumDispatchTargets - 1>());
  626. }
  627. // Special case the null byte index to end the tail-dispatch.
  628. tmp_table[0] =
  629. +[](ssize_t& index, const char* text, char* /*buffer*/) -> void {
  630. CARBON_CHECK(text[index] == '\0');
  631. return;
  632. };
  633. return tmp_table;
  634. }();
  635. template <int NumDispatchTargets>
  636. auto BM_SpeedOfLightDispatch(benchmark::State& state) -> void {
  637. std::string source = RandomSource(DefaultSourceDist);
  638. // A buffer to write to, simulating some minimal write traffic.
  639. llvm::OwningArrayRef<char> buffer(source.size());
  640. for (auto _ : state) {
  641. const char* text = source.data();
  642. benchmark::DoNotOptimize(text);
  643. // Use `ssize_t` to minimize indexing overhead.
  644. ssize_t i = 0;
  645. // The dispatch table tail-recurses through the entire string.
  646. DispatchTable<NumDispatchTargets>[static_cast<unsigned char>(text[i])](
  647. i, text, buffer.data());
  648. CARBON_CHECK(i == static_cast<ssize_t>(source.size()));
  649. benchmark::DoNotOptimize(buffer.data());
  650. }
  651. state.SetBytesProcessed(state.iterations() * source.size());
  652. state.counters["tokens_per_second"] = benchmark::Counter(
  653. NumTokens, benchmark::Counter::kIsIterationInvariantRate);
  654. state.counters["lines_per_second"] =
  655. benchmark::Counter(llvm::StringRef(source).count('\n'),
  656. benchmark::Counter::kIsIterationInvariantRate);
  657. }
  658. BENCHMARK(BM_SpeedOfLightDispatch<1>);
  659. BENCHMARK(BM_SpeedOfLightDispatch<2>);
  660. BENCHMARK(BM_SpeedOfLightDispatch<4>);
  661. BENCHMARK(BM_SpeedOfLightDispatch<8>);
  662. BENCHMARK(BM_SpeedOfLightDispatch<16>);
  663. BENCHMARK(BM_SpeedOfLightDispatch<32>);
  664. BENCHMARK(BM_SpeedOfLightDispatch<MaxDispatchTargets>);
  665. } // namespace
  666. } // namespace Carbon::Lex