LLVM 20.0.0git
Error.cpp
Go to the documentation of this file.
1//===----- lib/Support/Error.cpp - Error and associated utilities ---------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
12#include "llvm/ADT/Twine.h"
14#include <system_error>
15
16using namespace llvm;
17
18namespace {
19
20 enum class ErrorErrorCode : int {
21 MultipleErrors = 1,
23 InconvertibleError
24 };
25
26 // FIXME: This class is only here to support the transition to llvm::Error. It
27 // will be removed once this transition is complete. Clients should prefer to
28 // deal with the Error value directly, rather than converting to error_code.
29 class ErrorErrorCategory : public std::error_category {
30 public:
31 const char *name() const noexcept override { return "Error"; }
32
33 std::string message(int condition) const override {
34 switch (static_cast<ErrorErrorCode>(condition)) {
35 case ErrorErrorCode::MultipleErrors:
36 return "Multiple errors";
37 case ErrorErrorCode::InconvertibleError:
38 return "Inconvertible error value. An error has occurred that could "
39 "not be converted to a known std::error_code. Please file a "
40 "bug.";
41 case ErrorErrorCode::FileError:
42 return "A file error occurred.";
43 }
44 llvm_unreachable("Unhandled error code");
45 }
46 };
47
48}
49
50ErrorErrorCategory &getErrorErrorCat() {
51 static ErrorErrorCategory ErrorErrorCat;
52 return ErrorErrorCat;
53}
54
55namespace llvm {
56
57void ErrorInfoBase::anchor() {}
58char ErrorInfoBase::ID = 0;
59char ErrorList::ID = 0;
60void ECError::anchor() {}
61char ECError::ID = 0;
62char StringError::ID = 0;
63char FileError::ID = 0;
64
65void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner) {
66 if (!E)
67 return;
68 OS << ErrorBanner;
69 handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
70 EI.log(OS);
71 OS << "\n";
72 });
73}
74
75/// Write all error messages (if any) in E to a string. The newline character
76/// is used to separate error messages.
77std::string toString(Error E) {
79 handleAllErrors(std::move(E), [&Errors](const ErrorInfoBase &EI) {
80 Errors.push_back(EI.message());
81 });
82 return join(Errors.begin(), Errors.end(), "\n");
83}
84
85std::string toStringWithoutConsuming(const Error &E) {
87 visitErrors(E, [&Errors](const ErrorInfoBase &EI) {
88 Errors.push_back(EI.message());
89 });
90 return join(Errors.begin(), Errors.end(), "\n");
91}
92
93std::error_code ErrorList::convertToErrorCode() const {
94 return std::error_code(static_cast<int>(ErrorErrorCode::MultipleErrors),
96}
97
98std::error_code inconvertibleErrorCode() {
99 return std::error_code(static_cast<int>(ErrorErrorCode::InconvertibleError),
101}
102
103std::error_code FileError::convertToErrorCode() const {
104 std::error_code NestedEC = Err->convertToErrorCode();
105 if (NestedEC == inconvertibleErrorCode())
106 return std::error_code(static_cast<int>(ErrorErrorCode::FileError),
108 return NestedEC;
109}
110
111Error errorCodeToError(std::error_code EC) {
112 if (!EC)
113 return Error::success();
114 return Error(std::make_unique<ECError>(ECError(EC)));
115}
116
117std::error_code errorToErrorCode(Error Err) {
118 std::error_code EC;
119 handleAllErrors(std::move(Err), [&](const ErrorInfoBase &EI) {
120 EC = EI.convertToErrorCode();
121 });
122 if (EC == inconvertibleErrorCode())
123 report_fatal_error(Twine(EC.message()));
124 return EC;
125}
126
127#if LLVM_ENABLE_ABI_BREAKING_CHECKS
128void Error::fatalUncheckedError() const {
129 dbgs() << "Program aborted due to an unhandled Error:\n";
130 if (getPtr()) {
131 getPtr()->log(dbgs());
132 dbgs() << "\n";
133 }else
134 dbgs() << "Error value was Success. (Note: Success values must still be "
135 "checked prior to being destroyed).\n";
136 abort();
137}
138#endif
139
140StringError::StringError(std::error_code EC, const Twine &S)
141 : Msg(S.str()), EC(EC) {}
142
143StringError::StringError(const Twine &S, std::error_code EC)
144 : Msg(S.str()), EC(EC), PrintMsgOnly(true) {}
145
146StringError::StringError(std::string &&S, std::error_code EC, bool PrintMsgOnly)
147 : Msg(S), EC(EC), PrintMsgOnly(PrintMsgOnly) {}
148
149void StringError::log(raw_ostream &OS) const {
150 if (PrintMsgOnly) {
151 OS << Msg;
152 } else {
153 OS << EC.message();
154 if (!Msg.empty())
155 OS << (" " + Msg);
156 }
157}
158
159std::error_code StringError::convertToErrorCode() const {
160 return EC;
161}
162
163Error createStringError(std::string &&Msg, std::error_code EC) {
164 return make_error<StringError>(Msg, EC);
165}
166
167void report_fatal_error(Error Err, bool GenCrashDiag) {
168 assert(Err && "report_fatal_error called with success value");
169 std::string ErrMsg;
170 {
171 raw_string_ostream ErrStream(ErrMsg);
172 logAllUnhandledErrors(std::move(Err), ErrStream);
173 }
174 report_fatal_error(Twine(ErrMsg), GenCrashDiag);
175}
176
177} // end namespace llvm
178
180 return reinterpret_cast<ErrorInfoBase *>(Err)->dynamicClassID();
181}
182
184
185
186
187void LLVMCantFail(LLVMErrorRef Err) {
188 cantFail(unwrap(Err));
189}
190
192 std::string Tmp = toString(unwrap(Err));
193 char *ErrMsg = new char[Tmp.size() + 1];
194 memcpy(ErrMsg, Tmp.data(), Tmp.size());
195 ErrMsg[Tmp.size()] = '\0';
196 return ErrMsg;
197}
198
199void LLVMDisposeErrorMessage(char *ErrMsg) { delete[] ErrMsg; }
200
202 return reinterpret_cast<void *>(&StringError::ID);
203}
204
205LLVMErrorRef LLVMCreateStringError(const char *ErrMsg) {
206 return wrap(make_error<StringError>(ErrMsg, inconvertibleErrorCode()));
207}
aarch64 promote const
basic Basic Alias true
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static LLVMTargetMachineRef wrap(const TargetMachine *P)
static const char * toString(MIToken::TokenKind TokenKind)
Definition: MIParser.cpp:616
SymbolStringPoolEntryUnsafe unwrap(LLVMOrcSymbolStringPoolEntryRef E)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static const char * name
Definition: SMEABIPass.cpp:50
raw_pwrite_stream & OS
This file defines the SmallVector class.
This file contains some functions that are useful when dealing with strings.
ErrorErrorCategory & getErrorErrorCat()
Definition: Error.cpp:50
This class wraps a std::error_code in a Error.
Definition: Error.h:1174
static char ID
Definition: Error.h:1185
Base class for error info classes.
Definition: Error.h:45
virtual std::string message() const
Return the error message as a string.
Definition: Error.h:53
virtual std::error_code convertToErrorCode() const =0
Convert this error to a std::error_code.
virtual void log(raw_ostream &OS) const =0
Print an error message to an output stream.
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition: Error.cpp:93
static char ID
Definition: Error.h:395
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
static ErrorSuccess success()
Create a success value.
Definition: Error.h:337
This class wraps a filename and another Error.
Definition: Error.h:1323
static char ID
Definition: Error.h:1351
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition: Error.cpp:103
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
StringError(std::string &&S, std::error_code EC, bool PrintMsgOnly)
Definition: Error.cpp:146
static char ID
Definition: Error.h:1265
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:661
char * LLVMGetErrorMessage(LLVMErrorRef Err)
Returns the given string's error message.
Definition: Error.cpp:191
LLVMErrorTypeId LLVMGetErrorTypeId(LLVMErrorRef Err)
Returns the type id for the given error instance, which must be a failure value (i....
Definition: Error.cpp:179
LLVMErrorTypeId LLVMGetStringErrorTypeId(void)
Returns the type id for llvm StringError.
Definition: Error.cpp:201
void LLVMDisposeErrorMessage(char *ErrMsg)
Dispose of the given error message.
Definition: Error.cpp:199
void LLVMCantFail(LLVMErrorRef Err)
Report a fatal error if Err is a failure value.
Definition: Error.cpp:187
const void * LLVMErrorTypeId
Error type identifier.
Definition: Error.h:38
struct LLVMOpaqueError * LLVMErrorRef
Opaque reference to an error instance.
Definition: Error.h:33
LLVMErrorRef LLVMCreateStringError(const char *ErrMsg)
Create a StringError.
Definition: Error.cpp:205
void LLVMConsumeError(LLVMErrorRef Err)
Dispose of the given error without handling it.
Definition: Error.cpp:183
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
std::optional< const char * > toString(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract a string value from it.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner={})
Log all errors (if any) in E to OS.
Definition: Error.cpp:65
void visitErrors(const Error &E, HandlerT H)
Visit all the ErrorInfo(s) contained in E by passing them to the respective handler,...
Definition: Error.h:989
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
Definition: Error.h:977
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition: Error.cpp:98
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition: Error.h:1286
std::string toStringWithoutConsuming(const Error &E)
Like toString(), but does not consume the error.
Definition: Error.cpp:85
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:167
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
Definition: Error.h:756
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition: Error.cpp:111
std::error_code errorToErrorCode(Error Err)
Helper for converting an ECError to a std::error_code.
Definition: Error.cpp:117
void consumeError(Error Err)
Consume a Error without doing anything.
Definition: Error.h:1069