tokenized_buffer_benchmark.cpp 33 KB

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