tokenized_buffer_benchmark.cpp 29 KB

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