tokenized_buffer_benchmark.cpp 29 KB

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