tokenized_buffer_benchmark.cpp 29 KB

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