tokenized_buffer_benchmark.cpp 29 KB

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