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