Files
carbon-lang/common/error.h
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

205 lines
6.2 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
#ifndef CARBON_COMMON_ERROR_H_
#define CARBON_COMMON_ERROR_H_
#include <string>
#include <variant>
#include "common/check.h"
#include "common/ostream.h"
#include "llvm/ADT/Twine.h"
namespace Carbon {
// Success values should be represented as the presence of a value in ErrorOr,
// using `ErrorOr<Success>` and `return Success();` if no value needs to be
// returned.
struct Success {};
// Tracks an error message.
//
// This is nodiscard to enforce error handling prior to destruction.
class [[nodiscard]] Error : public Printable<Error> {
public:
// Represents an error state.
explicit Error(llvm::Twine location, llvm::Twine message)
: location_(location.str()), message_(message.str()) {
CARBON_CHECK(!message_.empty(), "Errors must have a message.");
}
// Represents an error with no associated location.
// TODO: Consider using two different types.
explicit Error(llvm::Twine message) : Error("", message) {}
Error(Error&& other) noexcept
: location_(std::move(other.location_)),
message_(std::move(other.message_)) {}
auto operator=(Error&& other) noexcept -> Error& {
location_ = std::move(other.location_);
message_ = std::move(other.message_);
return *this;
}
// Prints the error string.
void Print(llvm::raw_ostream& out) const {
if (!location().empty()) {
out << location() << ": ";
}
out << message();
}
// Returns a string describing the location of the error, such as
// "file.cc:123".
auto location() const -> const std::string& { return location_; }
// Returns the error message.
auto message() const -> const std::string& { return message_; }
private:
// The location associated with the error.
std::string location_;
// The error message.
std::string message_;
};
// Holds a value of type `T`, or an Error explaining why the value is
// unavailable.
//
// This is nodiscard to enforce error handling prior to destruction.
template <typename T>
class [[nodiscard]] ErrorOr {
public:
// Constructs with an error; the error must not be Error::Success().
// Implicit for easy construction on returns.
// NOLINTNEXTLINE(google-explicit-constructor)
ErrorOr(Error err) : val_(std::move(err)) {}
// Constructs with a value.
// Implicit for easy construction on returns.
// NOLINTNEXTLINE(google-explicit-constructor)
ErrorOr(T val) : val_(std::move(val)) {}
// Returns true for success.
auto ok() const -> bool { return std::holds_alternative<T>(val_); }
// Returns the contained error.
// REQUIRES: `ok()` is false.
auto error() const& -> const Error& {
CARBON_CHECK(!ok());
return std::get<Error>(val_);
}
auto error() && -> Error {
CARBON_CHECK(!ok());
return std::get<Error>(std::move(val_));
}
// Returns the contained value.
// REQUIRES: `ok()` is true.
auto operator*() -> T& {
CARBON_CHECK(ok());
return std::get<T>(val_);
}
// Returns the contained value.
// REQUIRES: `ok()` is true.
auto operator*() const -> const T& {
CARBON_CHECK(ok());
return std::get<T>(val_);
}
// Returns the contained value.
// REQUIRES: `ok()` is true.
auto operator->() -> T* {
CARBON_CHECK(ok());
return &std::get<T>(val_);
}
// Returns the contained value.
// REQUIRES: `ok()` is true.
auto operator->() const -> const T* {
CARBON_CHECK(ok());
return &std::get<T>(val_);
}
private:
// Either an error message or a value.
std::variant<Error, T> val_;
};
// A helper class for accumulating error message and converting to
// `Error` and `ErrorOr<T>`.
class ErrorBuilder {
public:
explicit ErrorBuilder(std::string location = "")
: location_(std::move(location)),
out_(std::make_unique<llvm::raw_string_ostream>(message_)) {}
// Accumulates string message to a temporary `ErrorBuilder`. After streaming,
// the builder must be converted to an `Error` or `ErrorOr`.
template <typename T>
auto operator<<(T&& message) && -> ErrorBuilder&& {
*out_ << message;
return std::move(*this);
}
// Accumulates string message for an lvalue error builder.
template <typename T>
auto operator<<(T&& message) & -> ErrorBuilder& {
*out_ << message;
return *this;
}
// NOLINTNEXTLINE(google-explicit-constructor): Implicit cast for returns.
operator Error() { return Error(location_, message_); }
template <typename T>
// NOLINTNEXTLINE(google-explicit-constructor): Implicit cast for returns.
operator ErrorOr<T>() {
return Error(location_, message_);
}
private:
std::string location_;
std::string message_;
// Use a pointer to allow move construction.
std::unique_ptr<llvm::raw_string_ostream> out_;
};
} // namespace Carbon
// Macro hackery to get a unique variable name.
#define CARBON_MAKE_UNIQUE_NAME_IMPL(a, b, c) a##b##c
#define CARBON_MAKE_UNIQUE_NAME(a, b, c) CARBON_MAKE_UNIQUE_NAME_IMPL(a, b, c)
// Macro to prevent a top-level comma from being interpreted as a macro
// argument separator.
#define CARBON_PROTECT_COMMAS(...) __VA_ARGS__
#define CARBON_RETURN_IF_ERROR_IMPL(unique_name, expr) \
if (auto unique_name = (expr); !(unique_name).ok()) { \
return std::move(unique_name).error(); \
}
#define CARBON_RETURN_IF_ERROR(expr) \
CARBON_RETURN_IF_ERROR_IMPL( \
CARBON_MAKE_UNIQUE_NAME(_llvm_error_line, __LINE__, __COUNTER__), \
CARBON_PROTECT_COMMAS(expr))
#define CARBON_ASSIGN_OR_RETURN_IMPL(unique_name, var, expr) \
auto unique_name = (expr); \
if (!(unique_name).ok()) { \
return std::move(unique_name).error(); \
} \
var = std::move(*(unique_name));
#define CARBON_ASSIGN_OR_RETURN(var, expr) \
CARBON_ASSIGN_OR_RETURN_IMPL( \
CARBON_MAKE_UNIQUE_NAME(_llvm_expected_line, __LINE__, __COUNTER__), \
CARBON_PROTECT_COMMAS(var), CARBON_PROTECT_COMMAS(expr))
#endif // CARBON_COMMON_ERROR_H_