Files
carbon-lang/toolchain/parse/tree_and_subtrees.cpp
T
4845f40dff Switch CARBON_CHECK to a format string API (#4285)
This switches `DCHECK` and `FATAL` as well.

The goal is to reduce the code size impact of these assertions so that
we can keep more of them enabled. Currently, the largest cost I see from
`CHECK` is not the actual check or the cold code itself, but actually
the failure to inline trivial functions due to the presence of the cold
code. This means that our goal isn't to reduce apparent code size in the
final binary but the LLVM IR cost assessed for these routines in the
inliner, which closely correlates with code size but is a bit different.

As discussed in #4283, experimentation shows that a single function call
with a minimal number of arguments is the lowest cost model for these.
This is easily achieved with a format-string API that internally uses
`llvm::formatv`. This PR is essentially the `CHECK` version of #4283.

However, the check macros are substantially harder to make work with
both format strings and streaming because they also take a condition.
Also, unexpectedly, I was very successful at devising a regular
expression based automated rewrite from the streaming to the format
string form with only low 10s of manual fixes. This includes compacting
strings broken up across lines, etc. Given how well that went, I've
prepared this PR which just directly switches to the format string API
and migrate everything to use it.

One nice side-effect is that the format string approach ends up greatly
simplifying the implementation here as well.

This is ... *shockingly* effective. Parsing speeds up by more than 3%
with just this change. And checking speeds up by **8%** with this change
alone:
```
BM_CompileAPIFileDenseDecls<Phase::Parse>/256      86.3µs ± 1%  82.9µs ± 1%  -3.94%  (p=0.000 n=17+19)
BM_CompileAPIFileDenseDecls<Phase::Parse>/1024      431µs ± 1%   415µs ± 1%  -3.76%  (p=0.000 n=18+19)
BM_CompileAPIFileDenseDecls<Phase::Parse>/4096     1.77ms ± 1%  1.71ms ± 1%  -3.18%  (p=0.000 n=18+19)
BM_CompileAPIFileDenseDecls<Phase::Parse>/16384    7.44ms ± 1%  7.17ms ± 2%  -3.56%  (p=0.000 n=18+20)
BM_CompileAPIFileDenseDecls<Phase::Parse>/65536    30.7ms ± 1%  29.7ms ± 1%  -3.15%  (p=0.000 n=18+20)
BM_CompileAPIFileDenseDecls<Phase::Parse>/262144    131ms ± 1%   127ms ± 1%  -2.81%  (p=0.000 n=18+18)
BM_CompileAPIFileDenseDecls<Phase::Check>/256       878µs ± 2%   800µs ± 1%  -8.91%  (p=0.000 n=19+20)
BM_CompileAPIFileDenseDecls<Phase::Check>/1024     1.88ms ± 2%  1.72ms ± 1%  -8.56%  (p=0.000 n=19+20)
BM_CompileAPIFileDenseDecls<Phase::Check>/4096     5.78ms ± 2%  5.28ms ± 1%  -8.70%  (p=0.000 n=20+18)
BM_CompileAPIFileDenseDecls<Phase::Check>/16384    21.9ms ± 1%  20.1ms ± 1%  -8.02%  (p=0.000 n=18+20)
BM_CompileAPIFileDenseDecls<Phase::Check>/65536    90.4ms ± 2%  83.1ms ± 1%  -8.04%  (p=0.000 n=19+20)
BM_CompileAPIFileDenseDecls<Phase::Check>/262144    381ms ± 2%   352ms ± 1%  -7.79%  (p=0.000 n=19+19)
```

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
Co-authored-by: josh11b <15258583+josh11b@users.noreply.github.com>
2024-09-12 16:42:08 +00:00

247 lines
8.5 KiB
C++

// Part of the Carbon Language project, under the Apache License v2.0 with LLVM
// Exceptions. See /LICENSE for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#include "toolchain/parse/tree_and_subtrees.h"
namespace Carbon::Parse {
TreeAndSubtrees::TreeAndSubtrees(const Lex::TokenizedBuffer& tokens,
const Tree& tree)
: tokens_(&tokens), tree_(&tree) {
subtree_sizes_.reserve(tree_->size());
// A stack of nodes which haven't yet been used as children.
llvm::SmallVector<NodeId> size_stack;
for (auto n : tree.postorder()) {
// Nodes always include themselves.
int32_t size = 1;
auto kind = tree.node_kind(n);
if (kind.has_child_count()) {
// When the child count is set, remove the specific number from the stack.
CARBON_CHECK(
static_cast<int32_t>(size_stack.size()) >= kind.child_count(),
"Need {0} children for {1}, have {2} available", kind.child_count(),
kind, size_stack.size());
for (auto i : llvm::seq(kind.child_count())) {
auto child = size_stack.pop_back_val();
CARBON_CHECK((size_t)child.index < subtree_sizes_.size());
size += subtree_sizes_[child.index];
if (kind.has_bracket() && i == kind.child_count() - 1) {
CARBON_CHECK(kind.bracket() == tree.node_kind(child),
"Node {0} with child count {1} needs bracket {2}, found "
"wrong bracket {3}",
kind, kind.child_count(), kind.bracket(),
tree.node_kind(child));
}
}
} else {
while (true) {
CARBON_CHECK(!size_stack.empty(), "Node {0} is missing bracket {1}",
kind, kind.bracket());
auto child = size_stack.pop_back_val();
size += subtree_sizes_[child.index];
if (kind.bracket() == tree.node_kind(child)) {
break;
}
}
}
size_stack.push_back(n);
subtree_sizes_.push_back(size);
}
CARBON_CHECK(static_cast<int>(subtree_sizes_.size()) == tree_->size());
// Remaining nodes should all be roots in the tree; make sure they line up.
CARBON_CHECK(
size_stack.back().index == static_cast<int32_t>(tree_->size()) - 1,
"{0} {1}", size_stack.back(), tree_->size() - 1);
int prev_index = -1;
for (const auto& n : size_stack) {
CARBON_CHECK(n.index - subtree_sizes_[n.index] == prev_index,
"NodeId {0} is a root {1} with subtree_size {2}, but previous "
"root was at {3}.",
n, tree_->node_kind(n), subtree_sizes_[n.index], prev_index);
prev_index = n.index;
}
}
auto TreeAndSubtrees::VerifyExtract(NodeId node_id, NodeKind kind,
ErrorBuilder* trace) const -> bool {
switch (kind) {
#define CARBON_PARSE_NODE_KIND(Name) \
case NodeKind::Name: \
return VerifyExtractAs<Name>(node_id, trace).has_value();
#include "toolchain/parse/node_kind.def"
}
}
auto TreeAndSubtrees::Verify() const -> ErrorOr<Success> {
// Validate that each node extracts successfully when not marked as having an
// error.
//
// Without this code, a 10 mloc test case of lex & parse takes 4.129 s ± 0.041
// s. With this additional verification, it takes 5.768 s ± 0.036 s.
for (NodeId n : tree_->postorder()) {
if (tree_->node_has_error(n)) {
continue;
}
auto node_kind = tree_->node_kind(n);
if (!VerifyExtract(n, node_kind, nullptr)) {
ErrorBuilder trace;
trace << llvm::formatv(
"NodeId #{0} couldn't be extracted as a {1}. Trace:\n", n, node_kind);
VerifyExtract(n, node_kind, &trace);
return trace;
}
}
// Validate the roots. Also ensures Tree::ExtractFile() doesn't error.
if (!TryExtractNodeFromChildren<File>(NodeId::Invalid, roots(), nullptr)) {
ErrorBuilder trace;
trace << "Roots of tree couldn't be extracted as a `File`. Trace:\n";
TryExtractNodeFromChildren<File>(NodeId::Invalid, roots(), &trace);
return trace;
}
return Success();
}
auto TreeAndSubtrees::postorder(NodeId n) const
-> llvm::iterator_range<Tree::PostorderIterator> {
// The postorder ends after this node, the root, and begins at the start of
// its subtree.
int start_index = n.index - subtree_sizes_[n.index] + 1;
return Tree::PostorderIterator::MakeRange(NodeId(start_index), n);
}
auto TreeAndSubtrees::children(NodeId n) const
-> llvm::iterator_range<SiblingIterator> {
CARBON_CHECK(n.is_valid());
int end_index = n.index - subtree_sizes_[n.index];
return llvm::iterator_range<SiblingIterator>(
SiblingIterator(*this, NodeId(n.index - 1)),
SiblingIterator(*this, NodeId(end_index)));
}
auto TreeAndSubtrees::roots() const -> llvm::iterator_range<SiblingIterator> {
return llvm::iterator_range<SiblingIterator>(
SiblingIterator(*this,
NodeId(static_cast<int>(subtree_sizes_.size()) - 1)),
SiblingIterator(*this, NodeId(-1)));
}
auto TreeAndSubtrees::PrintNode(llvm::raw_ostream& output, NodeId n, int depth,
bool preorder) const -> bool {
output.indent(2 * (depth + 2));
output << "{";
// If children are being added, include node_index in order to disambiguate
// nodes.
if (preorder) {
output << "node_index: " << n << ", ";
}
output << "kind: '" << tree_->node_kind(n) << "', text: '"
<< tokens_->GetTokenText(tree_->node_token(n)) << "'";
if (tree_->node_has_error(n)) {
output << ", has_error: yes";
}
if (subtree_sizes_[n.index] > 1) {
output << ", subtree_size: " << subtree_sizes_[n.index];
if (preorder) {
output << ", children: [\n";
return true;
}
}
output << "}";
return false;
}
auto TreeAndSubtrees::Print(llvm::raw_ostream& output) const -> void {
output << "- filename: " << tokens_->source().filename() << "\n"
<< " parse_tree: [\n";
// Walk the tree just to calculate depths for each node.
llvm::SmallVector<int> indents;
indents.resize(subtree_sizes_.size(), 0);
llvm::SmallVector<std::pair<NodeId, int>, 16> node_stack;
for (NodeId n : roots()) {
node_stack.push_back({n, 0});
}
while (!node_stack.empty()) {
NodeId n = NodeId::Invalid;
int depth;
std::tie(n, depth) = node_stack.pop_back_val();
for (NodeId sibling_n : children(n)) {
indents[sibling_n.index] = depth + 1;
node_stack.push_back({sibling_n, depth + 1});
}
}
for (NodeId n : tree_->postorder()) {
PrintNode(output, n, indents[n.index], /*preorder=*/false);
output << ",\n";
}
output << " ]\n";
}
auto TreeAndSubtrees::PrintPreorder(llvm::raw_ostream& output) const -> void {
output << "- filename: " << tokens_->source().filename() << "\n"
<< " parse_tree: [\n";
// The parse tree is stored in postorder. The preorder can be constructed
// by reversing the order of each level of siblings within an RPO. The
// sibling iterators are directly built around RPO and so can be used with a
// stack to produce preorder.
// The roots, like siblings, are in RPO (so reversed), but we add them in
// order here because we'll pop off the stack effectively reversing then.
llvm::SmallVector<std::pair<NodeId, int>, 16> node_stack;
for (NodeId n : roots()) {
node_stack.push_back({n, 0});
}
while (!node_stack.empty()) {
NodeId n = NodeId::Invalid;
int depth;
std::tie(n, depth) = node_stack.pop_back_val();
if (PrintNode(output, n, depth, /*preorder=*/true)) {
// Has children, so we descend. We append the children in order here as
// well because they will get reversed when popped off the stack.
for (NodeId sibling_n : children(n)) {
node_stack.push_back({sibling_n, depth + 1});
}
continue;
}
int next_depth = node_stack.empty() ? 0 : node_stack.back().second;
CARBON_CHECK(next_depth <= depth, "Cannot have the next depth increase!");
for (int close_children_count : llvm::seq(0, depth - next_depth)) {
(void)close_children_count;
output << "]}";
}
// We always end with a comma and a new line as we'll move to the next
// node at whatever the current level ends up being.
output << " ,\n";
}
output << " ]\n";
}
auto TreeAndSubtrees::CollectMemUsage(MemUsage& mem_usage,
llvm::StringRef label) const -> void {
mem_usage.Add(MemUsage::ConcatLabel(label, "subtree_sizes_"), subtree_sizes_);
}
auto TreeAndSubtrees::SiblingIterator::Print(llvm::raw_ostream& output) const
-> void {
output << node_;
}
} // namespace Carbon::Parse