tokenized_buffer_benchmark.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751
  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. auto buffer = Lex::Lex(value_stores_, source_, consumer);
  198. consumer.Flush();
  199. CARBON_CHECK(buffer.has_errors(),
  200. "Asked to diagnose errors but none found!");
  201. return result.TakeStr();
  202. }
  203. auto source_text() -> llvm::StringRef { return source_.text(); }
  204. private:
  205. auto MakeSourceBuffer(llvm::StringRef text) -> SourceBuffer {
  206. CARBON_CHECK(fs_.addFile(filename_, /*ModificationTime=*/0,
  207. llvm::MemoryBuffer::getMemBuffer(text)));
  208. return std::move(*SourceBuffer::MakeFromFile(fs_, filename_,
  209. ConsoleDiagnosticConsumer()));
  210. }
  211. SharedValueStores value_stores_;
  212. llvm::vfs::InMemoryFileSystem fs_;
  213. std::string filename_ = "test.carbon";
  214. SourceBuffer source_;
  215. };
  216. void BM_ValidKeywords(benchmark::State& state) {
  217. absl::BitGen gen;
  218. std::array<llvm::StringRef, NumTokens> tokens;
  219. for (int i : llvm::seq(NumTokens)) {
  220. tokens[i] = TokenKind::KeywordTokens[i % TokenKind::KeywordTokens.size()]
  221. .fixed_spelling();
  222. }
  223. std::shuffle(tokens.begin(), tokens.end(), gen);
  224. std::string source = llvm::join(tokens, " ");
  225. LexerBenchHelper helper(source);
  226. for (auto _ : state) {
  227. TokenizedBuffer buffer = helper.Lex();
  228. CARBON_CHECK(!buffer.has_errors());
  229. }
  230. state.SetBytesProcessed(state.iterations() * source.size());
  231. state.counters["tokens_per_second"] = benchmark::Counter(
  232. NumTokens, benchmark::Counter::kIsIterationInvariantRate);
  233. }
  234. BENCHMARK(BM_ValidKeywords);
  235. void BM_ValidKeywordsAsRawIdentifiers(benchmark::State& state) {
  236. absl::BitGen gen;
  237. std::array<llvm::StringRef, NumTokens> tokens;
  238. for (int i : llvm::seq(NumTokens)) {
  239. tokens[i] = TokenKind::KeywordTokens[i % TokenKind::KeywordTokens.size()]
  240. .fixed_spelling();
  241. }
  242. std::shuffle(tokens.begin(), tokens.end(), gen);
  243. std::string source("r#");
  244. source.append(llvm::join(tokens, " r#"));
  245. LexerBenchHelper helper(source);
  246. for (auto _ : state) {
  247. TokenizedBuffer buffer = helper.Lex();
  248. CARBON_CHECK(!buffer.has_errors());
  249. }
  250. state.SetBytesProcessed(state.iterations() * source.size());
  251. state.counters["tokens_per_second"] = benchmark::Counter(
  252. NumTokens, benchmark::Counter::kIsIterationInvariantRate);
  253. }
  254. BENCHMARK(BM_ValidKeywordsAsRawIdentifiers);
  255. // This benchmark does a 50-50 split of r-prefixed and r#-prefixed identifiers
  256. // to directly compare raw and non-raw performance.
  257. void BM_RawIdentifierFocus(benchmark::State& state) {
  258. llvm::SmallVector<llvm::StringRef> ids =
  259. Testing::SourceGen::Global().GetIdentifiers(NumTokens / 2);
  260. llvm::SmallVector<std::string> modified_ids;
  261. // As we resize, start with the in-use prefix. Note that `r#` uses the first
  262. // character of the original identifier.
  263. modified_ids.resize(NumTokens / 2, "r#");
  264. modified_ids.resize(NumTokens, "r");
  265. for (int i : llvm::seq(NumTokens / 2)) {
  266. // Use the same identifier both ways.
  267. modified_ids[i].append(ids[i]);
  268. modified_ids[i + NumTokens / 2].append(
  269. llvm::StringRef(ids[i]).drop_front());
  270. }
  271. absl::BitGen gen;
  272. std::array<llvm::StringRef, NumTokens> tokens;
  273. for (int i : llvm::seq(NumTokens)) {
  274. tokens[i] = modified_ids[i];
  275. }
  276. std::shuffle(tokens.begin(), tokens.end(), gen);
  277. std::string source = llvm::join(tokens, " ");
  278. LexerBenchHelper helper(source);
  279. for (auto _ : state) {
  280. TokenizedBuffer buffer = helper.Lex();
  281. CARBON_CHECK(!buffer.has_errors());
  282. }
  283. state.SetBytesProcessed(state.iterations() * source.size());
  284. state.counters["tokens_per_second"] = benchmark::Counter(
  285. NumTokens, benchmark::Counter::kIsIterationInvariantRate);
  286. }
  287. BENCHMARK(BM_RawIdentifierFocus);
  288. template <int MinLength, int MaxLength, bool Uniform>
  289. void BM_ValidIdentifiers(benchmark::State& state) {
  290. std::string source = RandomIdentifierSeq(MinLength, MaxLength, Uniform);
  291. LexerBenchHelper helper(source);
  292. for (auto _ : state) {
  293. TokenizedBuffer buffer = helper.Lex();
  294. CARBON_CHECK(!buffer.has_errors(), "{0}", helper.DiagnoseErrors());
  295. }
  296. state.SetBytesProcessed(state.iterations() * source.size());
  297. state.counters["tokens_per_second"] = benchmark::Counter(
  298. NumTokens, benchmark::Counter::kIsIterationInvariantRate);
  299. }
  300. // Benchmark the non-uniform distribution we observe in C++ code.
  301. BENCHMARK(BM_ValidIdentifiers<1, 64, /*Uniform=*/false>);
  302. // Also benchmark a few uniform distribution ranges of identifier widths to
  303. // cover different patterns that emerge with small, medium, and longer
  304. // identifiers.
  305. BENCHMARK(BM_ValidIdentifiers<1, 1, /*Uniform=*/true>);
  306. BENCHMARK(BM_ValidIdentifiers<3, 5, /*Uniform=*/true>);
  307. BENCHMARK(BM_ValidIdentifiers<3, 16, /*Uniform=*/true>);
  308. BENCHMARK(BM_ValidIdentifiers<12, 64, /*Uniform=*/true>);
  309. BENCHMARK(BM_ValidIdentifiers<16, 16, /*Uniform=*/true>);
  310. BENCHMARK(BM_ValidIdentifiers<24, 24, /*Uniform=*/true>);
  311. BENCHMARK(BM_ValidIdentifiers<32, 32, /*Uniform=*/true>);
  312. BENCHMARK(BM_ValidIdentifiers<48, 48, /*Uniform=*/true>);
  313. BENCHMARK(BM_ValidIdentifiers<64, 64, /*Uniform=*/true>);
  314. BENCHMARK(BM_ValidIdentifiers<80, 80, /*Uniform=*/true>);
  315. // Benchmark to stress the lexing of horizontal whitespace. This sets up what is
  316. // nearly a worst-case scenario of short-but-expensive-to-lex tokens with runs
  317. // of horizontal whitespace between them.
  318. void BM_HorizontalWhitespace(benchmark::State& state) {
  319. int num_spaces = state.range(0);
  320. std::string separator(num_spaces, ' ');
  321. std::string source = RandomIdentifierSeq(3, 5, /*uniform=*/true, separator);
  322. LexerBenchHelper helper(source);
  323. for (auto _ : state) {
  324. TokenizedBuffer buffer = helper.Lex();
  325. // Ensure that lexing actually occurs for benchmarking and that it doesn't
  326. // hit errors that would skew the benchmark results.
  327. CARBON_CHECK(!buffer.has_errors(), "{0}", helper.DiagnoseErrors());
  328. }
  329. state.SetBytesProcessed(state.iterations() * source.size());
  330. state.counters["tokens_per_second"] = benchmark::Counter(
  331. NumTokens, benchmark::Counter::kIsIterationInvariantRate);
  332. }
  333. BENCHMARK(BM_HorizontalWhitespace)->RangeMultiplier(4)->Range(1, 128);
  334. void BM_RandomSource(benchmark::State& state) {
  335. std::string source = RandomSource(DefaultSourceDist);
  336. LexerBenchHelper helper(source);
  337. for (auto _ : state) {
  338. TokenizedBuffer buffer = helper.Lex();
  339. // Ensure that lexing actually occurs for benchmarking and that it doesn't
  340. // hit errors that would skew the benchmark results.
  341. CARBON_CHECK(!buffer.has_errors(), "{0}", helper.DiagnoseErrors());
  342. }
  343. state.SetBytesProcessed(state.iterations() * source.size());
  344. state.counters["tokens_per_second"] = benchmark::Counter(
  345. NumTokens, benchmark::Counter::kIsIterationInvariantRate);
  346. state.counters["lines_per_second"] =
  347. benchmark::Counter(llvm::StringRef(source).count('\n'),
  348. benchmark::Counter::kIsIterationInvariantRate);
  349. }
  350. // The distributions between symbols, keywords, and identifiers here are
  351. // guesses. Eventually, we should collect more data to help tune these, but
  352. // hopefully the performance isn't too sensitive and we can just cover a wide
  353. // range here.
  354. BENCHMARK(BM_RandomSource);
  355. // Benchmark to stress opening and closing grouped symbols.
  356. void BM_GroupingSymbols(benchmark::State& state) {
  357. int curly_brace_depth = state.range(0);
  358. int paren_depth = state.range(1);
  359. int square_bracket_depth = state.range(2);
  360. // TODO: It might be interesting to have some random pattern of nesting, but
  361. // the obvious ways to do that result it really unstable total size of input
  362. // or unbalanced groups. For now, just use a simple strict nesting approach.
  363. // It should still let us look for specific pain points. We do include some
  364. // whitespace and keywords to make sure *some* other parts of the benchmark
  365. // are also active and have some reasonable icache pressure.
  366. llvm::SmallVector<llvm::StringRef> ids =
  367. Testing::SourceGen::Global().GetShuffledIdentifiers(NumTokens);
  368. RawStringOstream os;
  369. int num_tokens_per_nest =
  370. curly_brace_depth * 2 + paren_depth * 2 + square_bracket_depth * 2 + 2;
  371. int num_nests = NumTokens / num_tokens_per_nest;
  372. for (int i : llvm::seq(num_nests)) {
  373. for (int j : llvm::seq(curly_brace_depth)) {
  374. os.indent(j * 2) << "{\n";
  375. }
  376. os.indent(curly_brace_depth * 2);
  377. for ([[maybe_unused]] int j : llvm::seq(paren_depth)) {
  378. os << "(";
  379. }
  380. for ([[maybe_unused]] int j : llvm::seq(square_bracket_depth)) {
  381. os << "[";
  382. }
  383. os << ids[(i * 2) % NumTokens];
  384. for ([[maybe_unused]] int j : llvm::seq(square_bracket_depth)) {
  385. os << "]";
  386. }
  387. for ([[maybe_unused]] int j : llvm::seq(paren_depth)) {
  388. os << ")";
  389. }
  390. for (int j : llvm::reverse(llvm::seq(curly_brace_depth))) {
  391. os << "\n";
  392. os.indent(j * 2) << "}";
  393. }
  394. os << ids[(i * 2 + 1) % NumTokens] << "\n";
  395. }
  396. std::string source = os.TakeStr();
  397. LexerBenchHelper helper(source);
  398. for (auto _ : state) {
  399. TokenizedBuffer buffer = helper.Lex();
  400. // Ensure that lexing actually occurs for benchmarking and that it doesn't
  401. // hit errors that would skew the benchmark results.
  402. CARBON_CHECK(!buffer.has_errors(), "{0}", helper.DiagnoseErrors());
  403. }
  404. state.SetBytesProcessed(state.iterations() * source.size());
  405. state.counters["tokens_per_second"] = benchmark::Counter(
  406. NumTokens, benchmark::Counter::kIsIterationInvariantRate);
  407. state.counters["lines_per_second"] =
  408. benchmark::Counter(llvm::StringRef(source).count('\n'),
  409. benchmark::Counter::kIsIterationInvariantRate);
  410. }
  411. BENCHMARK(BM_GroupingSymbols)
  412. ->ArgsProduct({
  413. {1, 2, 3, 4, 8, 16, 32},
  414. {0},
  415. {0},
  416. })
  417. ->ArgsProduct({
  418. {0},
  419. {1, 2, 3, 4, 8, 16, 32},
  420. {0},
  421. })
  422. ->ArgsProduct({
  423. {0},
  424. {0},
  425. {1, 2, 3, 4, 8, 16, 32},
  426. })
  427. ->ArgsProduct({
  428. {32},
  429. {1, 2, 3, 4, 8, 16, 32},
  430. {0},
  431. })
  432. ->ArgsProduct({
  433. {32},
  434. {32},
  435. {1, 2, 3, 4, 8, 16, 32},
  436. });
  437. // Benchmark to stress the lexing of blank lines. This uses a simple, easy to
  438. // lex token, but separates each one by varying numbers of blank lines.
  439. void BM_BlankLines(benchmark::State& state) {
  440. int num_blank_lines = state.range(0);
  441. std::string separator(num_blank_lines, '\n');
  442. std::string source = RandomIdentifierSeq(3, 5, /*uniform=*/true, separator);
  443. LexerBenchHelper helper(source);
  444. for (auto _ : state) {
  445. TokenizedBuffer buffer = helper.Lex();
  446. // Ensure that lexing actually occurs for benchmarking and that it doesn't
  447. // hit errors that would skew the benchmark results.
  448. CARBON_CHECK(!buffer.has_errors(), "{0}", helper.DiagnoseErrors());
  449. }
  450. state.SetBytesProcessed(state.iterations() * source.size());
  451. state.counters["tokens_per_second"] = benchmark::Counter(
  452. NumTokens, benchmark::Counter::kIsIterationInvariantRate);
  453. state.counters["lines_per_second"] =
  454. benchmark::Counter(llvm::StringRef(source).count('\n'),
  455. benchmark::Counter::kIsIterationInvariantRate);
  456. }
  457. BENCHMARK(BM_BlankLines)->RangeMultiplier(4)->Range(1, 128);
  458. // Benchmark to stress the lexing of comment lines. This uses a simple, easy to
  459. // lex token, but separates each one by varying numbers of comment lines, with
  460. // varying comment line length and indentation.
  461. void BM_CommentLines(benchmark::State& state) {
  462. int num_comment_lines = state.range(0);
  463. int comment_length = state.range(1);
  464. int comment_indent = state.range(2);
  465. RawStringOstream os;
  466. os << "\n";
  467. for (int i : llvm::seq(num_comment_lines)) {
  468. static_cast<void>(i);
  469. os << std::string(comment_indent, ' ') << "//"
  470. << std::string(comment_length, ' ') << "\n";
  471. }
  472. std::string source =
  473. RandomIdentifierSeq(3, 5, /*uniform=*/true, os.TakeStr());
  474. LexerBenchHelper helper(source);
  475. for (auto _ : state) {
  476. TokenizedBuffer buffer = helper.Lex();
  477. // Ensure that lexing actually occurs for benchmarking and that it doesn't
  478. // hit errors that would skew the benchmark results.
  479. CARBON_CHECK(!buffer.has_errors(), "{0}", helper.DiagnoseErrors());
  480. }
  481. state.SetBytesProcessed(state.iterations() * source.size());
  482. state.counters["tokens_per_second"] = benchmark::Counter(
  483. NumTokens, benchmark::Counter::kIsIterationInvariantRate);
  484. state.counters["lines_per_second"] =
  485. benchmark::Counter(llvm::StringRef(source).count('\n'),
  486. benchmark::Counter::kIsIterationInvariantRate);
  487. }
  488. BENCHMARK(BM_CommentLines)
  489. ->ArgsProduct({
  490. // How many lines of comment. Focused on a couple of small and checking
  491. // how it scales up to large blocks.
  492. {1, 4, 128},
  493. // Comment lengths: the two extremes and a middling length.
  494. {0, 30, 70},
  495. // Comment indentations.
  496. {0, 2, 8},
  497. });
  498. // This is a speed-of-light benchmark that should reflect memory bandwidth
  499. // (ideally) of simply reading all the source code. For speed-of-light we use
  500. // `strcpy` -- this both examines ever byte of the input looking for a null to
  501. // end the copy, and also writes to a data structure of roughly the same size as
  502. // the input. This routine is one we expect to be *very* well optimized and give
  503. // a good approximation of the fastest possible lexer given the physical
  504. // constraints of the machine. Note that which particular source we use as input
  505. // here isn't especially interesting, so we just pick one and should update it
  506. // to reflect whatever distribution is most realistic long-term. The
  507. // bytes/second throughput is the important output of this routine.
  508. auto BM_SpeedOfLightStrCpy(benchmark::State& state) -> void {
  509. std::string source = RandomSource(DefaultSourceDist);
  510. // A buffer to write the null-terminated contents of `source` into.
  511. llvm::OwningArrayRef<char> buffer(source.size() + 1);
  512. for (auto _ : state) {
  513. const char* text = source.data();
  514. benchmark::DoNotOptimize(text);
  515. strcpy(buffer.data(), text);
  516. benchmark::DoNotOptimize(buffer.data());
  517. }
  518. state.SetBytesProcessed(state.iterations() * source.size());
  519. state.counters["tokens_per_second"] = benchmark::Counter(
  520. NumTokens, benchmark::Counter::kIsIterationInvariantRate);
  521. state.counters["lines_per_second"] =
  522. benchmark::Counter(llvm::StringRef(source).count('\n'),
  523. benchmark::Counter::kIsIterationInvariantRate);
  524. }
  525. BENCHMARK(BM_SpeedOfLightStrCpy);
  526. // This is a speed-of-light benchmark that builds up a best-case byte-wise table
  527. // dispatch using guaranteed tail recursion. The goal is both to ensure the
  528. // general technique can reasonably hit the level of performance we need and to
  529. // establish how far from this speed of light the actual lexer currently sits.
  530. //
  531. // A major impact on the observed performance of this technique is how many
  532. // different functions are reached in this dispatch loop. This benchmark
  533. // infrastructure tries to bracket the range of performance this technique
  534. // affords with different numbers of dispatch target functions.
  535. using DispatchPtrT = auto (*)(ssize_t& index, const char* text, char* buffer)
  536. -> void;
  537. using DispatchTableT = std::array<DispatchPtrT, 256>;
  538. template <const DispatchTableT& Table>
  539. auto BasicDispatch(ssize_t& index, const char* text, char* buffer) -> void {
  540. *buffer = text[index];
  541. ++index;
  542. // NOLINTNEXTLINE(readability-avoid-return-with-void-value): For musttail.
  543. [[clang::musttail]] return Table[static_cast<unsigned char>(text[index])](
  544. index, text, buffer);
  545. }
  546. template <const DispatchTableT& Table, char C>
  547. auto SpecializedDispatch(ssize_t& index, const char* text, char* buffer)
  548. -> void {
  549. CARBON_CHECK(C == text[index]);
  550. *buffer = C;
  551. ++index;
  552. // NOLINTNEXTLINE(readability-avoid-return-with-void-value): For musttail.
  553. [[clang::musttail]] return Table[static_cast<unsigned char>(text[index])](
  554. index, text, buffer);
  555. }
  556. // A sample of the symbol characters used in Carbon code. Doesn't need to be
  557. // perfect, as we just need to have a reasonably large # of distinct dispatch
  558. // functions.
  559. constexpr char DispatchSpecializableSymbols[] = {
  560. '!', '%', '(', ')', '*', '+', ',', '-', '.', ':',
  561. ';', '<', '=', '>', '?', '[', ']', '{', '}', '~',
  562. };
  563. // Create an array of all the characters we can specialize dispatch over --
  564. // [0-9A-Za-z] and the symbols above. Similar to the above symbols, doesn't need
  565. // to be exhaustive.
  566. constexpr std::array<char, 26 * 2 + 10 + sizeof(DispatchSpecializableSymbols)>
  567. DispatchSpecializableChars = []() {
  568. constexpr int Size = sizeof(DispatchSpecializableChars);
  569. std::array<char, Size> chars = {};
  570. int i = 0;
  571. for (char c = '0'; c <= '9'; ++c) {
  572. chars[i] = c;
  573. ++i;
  574. }
  575. for (char c = 'A'; c <= 'Z'; ++c) {
  576. chars[i] = c;
  577. ++i;
  578. }
  579. for (char c = 'a'; c <= 'z'; ++c) {
  580. chars[i] = c;
  581. ++i;
  582. }
  583. for (char c : DispatchSpecializableSymbols) {
  584. chars[i] = c;
  585. ++i;
  586. }
  587. CARBON_CHECK(i == Size);
  588. return chars;
  589. }();
  590. // Instantiate a number of specialized dispatch functions for characters in the
  591. // array above, and assign those function addresses to the character's entry in
  592. // the provided table. The provided `tmp_table` is a temporary that will
  593. // eventually initialize the provided `Table` constant, so the constant is what
  594. // we propagate to the instantiated function and the temporary is the one we
  595. // initialize.
  596. template <const DispatchTableT& Table, size_t... Indices>
  597. constexpr auto SpecializeDispatchTable(
  598. DispatchTableT& tmp_table, std::index_sequence<Indices...> /*indices*/)
  599. -> void {
  600. static_assert(sizeof...(Indices) <= sizeof(DispatchSpecializableChars));
  601. ((tmp_table[static_cast<unsigned char>(DispatchSpecializableChars[Indices])] =
  602. &SpecializedDispatch<Table, DispatchSpecializableChars[Indices]>),
  603. ...);
  604. }
  605. // The maximum number of dispatch targets is the size of the array + 1 (for the
  606. // base case target).
  607. constexpr int MaxDispatchTargets = sizeof(DispatchSpecializableChars) + 1;
  608. // Dispatch tables with a provided number of distinct dispatch targets. There
  609. // will always be one additional target for the null byte to end the loop.
  610. template <int NumDispatchTargets>
  611. constexpr DispatchTableT DispatchTable = []() {
  612. static_assert(NumDispatchTargets > 0, "Need at least one dispatch target.");
  613. static_assert(NumDispatchTargets <= MaxDispatchTargets,
  614. "Limited number of dispatch targets available.");
  615. DispatchTableT tmp_table = {};
  616. // Start with the basic dispatch target.
  617. for (int i = 0; i < 256; ++i) {
  618. tmp_table[i] = &BasicDispatch<DispatchTable<NumDispatchTargets>>;
  619. }
  620. // NOLINTNEXTLINE(readability-braces-around-statements): False positive.
  621. if constexpr (NumDispatchTargets > 1) {
  622. // Add additional dispatch targets from our specializable array.
  623. SpecializeDispatchTable<DispatchTable<NumDispatchTargets>>(
  624. tmp_table, std::make_index_sequence<NumDispatchTargets - 1>());
  625. }
  626. // Special case the null byte index to end the tail-dispatch.
  627. tmp_table[0] =
  628. +[](ssize_t& index, const char* text, char* /*buffer*/) -> void {
  629. CARBON_CHECK(text[index] == '\0');
  630. return;
  631. };
  632. return tmp_table;
  633. }();
  634. template <int NumDispatchTargets>
  635. auto BM_SpeedOfLightDispatch(benchmark::State& state) -> void {
  636. std::string source = RandomSource(DefaultSourceDist);
  637. // A buffer to write to, simulating some minimal write traffic.
  638. llvm::OwningArrayRef<char> buffer(source.size());
  639. for (auto _ : state) {
  640. const char* text = source.data();
  641. benchmark::DoNotOptimize(text);
  642. // Use `ssize_t` to minimize indexing overhead.
  643. ssize_t i = 0;
  644. // The dispatch table tail-recurses through the entire string.
  645. DispatchTable<NumDispatchTargets>[static_cast<unsigned char>(text[i])](
  646. i, text, buffer.data());
  647. CARBON_CHECK(i == static_cast<ssize_t>(source.size()));
  648. benchmark::DoNotOptimize(buffer.data());
  649. }
  650. state.SetBytesProcessed(state.iterations() * source.size());
  651. state.counters["tokens_per_second"] = benchmark::Counter(
  652. NumTokens, benchmark::Counter::kIsIterationInvariantRate);
  653. state.counters["lines_per_second"] =
  654. benchmark::Counter(llvm::StringRef(source).count('\n'),
  655. benchmark::Counter::kIsIterationInvariantRate);
  656. }
  657. BENCHMARK(BM_SpeedOfLightDispatch<1>);
  658. BENCHMARK(BM_SpeedOfLightDispatch<2>);
  659. BENCHMARK(BM_SpeedOfLightDispatch<4>);
  660. BENCHMARK(BM_SpeedOfLightDispatch<8>);
  661. BENCHMARK(BM_SpeedOfLightDispatch<16>);
  662. BENCHMARK(BM_SpeedOfLightDispatch<32>);
  663. BENCHMARK(BM_SpeedOfLightDispatch<MaxDispatchTargets>);
  664. } // namespace
  665. } // namespace Carbon::Lex