LLVM 23.0.0git
Error.h
Go to the documentation of this file.
1//===- llvm/Support/Error.h - Recoverable error handling --------*- C++ -*-===//
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//
9// This file defines an API used to report recoverable errors.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_SUPPORT_ERROR_H
14#define LLVM_SUPPORT_ERROR_H
15
16#include "llvm-c/Error.h"
17#include "llvm/ADT/Twine.h"
18#include "llvm/Config/abi-breaking.h"
20#include "llvm/Support/Debug.h"
23#include "llvm/Support/Format.h"
25#include <cassert>
26#include <cstdint>
27#include <cstdlib>
28#include <functional>
29#include <memory>
30#include <new>
31#include <optional>
32#include <string>
33#include <system_error>
34#include <type_traits>
35#include <utility>
36#include <vector>
37
38namespace llvm {
39
40class ErrorSuccess;
41
42/// Base class for error info classes. Do not extend this directly: Extend
43/// the ErrorInfo template subclass instead.
45public:
46 virtual ~ErrorInfoBase() = default;
47
48 /// Print an error message to an output stream.
49 virtual void log(raw_ostream &OS) const = 0;
50
51 /// Return the error message as a string.
52 virtual std::string message() const {
53 std::string Msg;
54 raw_string_ostream OS(Msg);
55 log(OS);
56 return Msg;
57 }
58
59 /// Convert this error to a std::error_code.
60 ///
61 /// This is a temporary crutch to enable interaction with code still
62 /// using std::error_code. It will be removed in the future.
63 virtual std::error_code convertToErrorCode() const = 0;
64
65 // Returns the class ID for this type.
66 static const void *classID() { return &ID; }
67
68 // Returns the class ID for the dynamic type of this ErrorInfoBase instance.
69 virtual const void *dynamicClassID() const = 0;
70
71 // Check whether this instance is a subclass of the class identified by
72 // ClassID.
73 virtual bool isA(const void *const ClassID) const {
74 return ClassID == classID();
75 }
76
77 // Check whether this instance is a subclass of ErrorInfoT.
78 template <typename ErrorInfoT> bool isA() const {
79 return isA(ErrorInfoT::classID());
80 }
81
82private:
83 virtual void anchor();
84
85 static char ID;
86};
87
88/// Lightweight error class with error context and mandatory checking.
89///
90/// Instances of this class wrap a ErrorInfoBase pointer. Failure states
91/// are represented by setting the pointer to a ErrorInfoBase subclass
92/// instance containing information describing the failure. Success is
93/// represented by a null pointer value.
94///
95/// Instances of Error also contains a 'Checked' flag, which must be set
96/// before the destructor is called, otherwise the destructor will trigger a
97/// runtime error. This enforces at runtime the requirement that all Error
98/// instances be checked or returned to the caller.
99///
100/// There are two ways to set the checked flag, depending on what state the
101/// Error instance is in. For Error instances indicating success, it
102/// is sufficient to invoke the boolean conversion operator. E.g.:
103///
104/// @code{.cpp}
105/// Error foo(<...>);
106///
107/// if (auto E = foo(<...>))
108/// return E; // <- Return E if it is in the error state.
109/// // We have verified that E was in the success state. It can now be safely
110/// // destroyed.
111/// @endcode
112///
113/// A success value *can not* be dropped. For example, just calling 'foo(<...>)'
114/// without testing the return value will raise a runtime error, even if foo
115/// returns success.
116///
117/// For Error instances representing failure, you must use either the
118/// handleErrors or handleAllErrors function with a typed handler. E.g.:
119///
120/// @code{.cpp}
121/// class MyErrorInfo : public ErrorInfo<MyErrorInfo> {
122/// // Custom error info.
123/// };
124///
125/// Error foo(<...>) { return make_error<MyErrorInfo>(...); }
126///
127/// auto E = foo(<...>); // <- foo returns failure with MyErrorInfo.
128/// auto NewE =
129/// handleErrors(std::move(E),
130/// [](const MyErrorInfo &M) {
131/// // Deal with the error.
132/// },
133/// [](std::unique_ptr<OtherError> M) -> Error {
134/// if (canHandle(*M)) {
135/// // handle error.
136/// return Error::success();
137/// }
138/// // Couldn't handle this error instance. Pass it up the stack.
139/// return Error(std::move(M));
140/// });
141/// // Note - The error passed to handleErrors will be marked as checked. If
142/// // there is no matched handler, a new error with the same payload is
143/// // created and returned.
144/// // The handlers take the error checked by handleErrors as an argument,
145/// // which can be used to retrieve more information. If a new error is
146/// // created by a handler, it will be passed back to the caller of
147/// // handleErrors and needs to be checked or return up to the stack.
148/// // Otherwise, the passed-in error is considered consumed.
149/// @endcode
150///
151/// The handleAllErrors function is identical to handleErrors, except
152/// that it has a void return type, and requires all errors to be handled and
153/// no new errors be returned. It prevents errors (assuming they can all be
154/// handled) from having to be bubbled all the way to the top-level.
155///
156/// *All* Error instances must be checked before destruction, even if
157/// they're moved-assigned or constructed from Success values that have already
158/// been checked. This enforces checking through all levels of the call stack.
159class [[nodiscard]] Error {
160 // ErrorList needs to be able to yank ErrorInfoBase pointers out of Errors
161 // to add to the error list. It can't rely on handleErrors for this, since
162 // handleErrors does not support ErrorList handlers.
163 friend class ErrorList;
164
165 // handleErrors needs to be able to set the Checked flag.
166 template <typename... HandlerTs>
167 friend Error handleErrors(Error E, HandlerTs &&... Handlers);
168 // visitErrors needs direct access to the payload.
169 template <typename HandlerT>
170 friend void visitErrors(const Error &E, HandlerT H);
171
172 // Expected<T> needs to be able to steal the payload when constructed from an
173 // error.
174 template <typename T> friend class Expected;
175
176 // wrap needs to be able to steal the payload.
177 friend LLVMErrorRef wrap(Error);
178
179protected:
180 /// Create a success value. Prefer using 'Error::success()' for readability
182 setPtr(nullptr);
183 setChecked(false);
184 }
185
186public:
187 /// Create a success value.
188 static ErrorSuccess success();
189
190 // Errors are not copy-constructable.
191 Error(const Error &Other) = delete;
192
193 /// Move-construct an error value. The newly constructed error is considered
194 /// unchecked, even if the source error had been checked. The original error
195 /// becomes a checked Success value, regardless of its original state.
197 setChecked(true);
198 *this = std::move(Other);
199 }
200
201 /// Create an error value. Prefer using the 'make_error' function, but
202 /// this constructor can be useful when "re-throwing" errors from handlers.
203 Error(std::unique_ptr<ErrorInfoBase> Payload) {
204 setPtr(Payload.release());
205 setChecked(false);
206 }
207
208 // Errors are not copy-assignable.
209 Error &operator=(const Error &Other) = delete;
210
211 /// Move-assign an error value. The current error must represent success, you
212 /// you cannot overwrite an unhandled error. The current error is then
213 /// considered unchecked. The source error becomes a checked success value,
214 /// regardless of its original state.
216 // Don't allow overwriting of unchecked values.
217 assertIsChecked();
218 setPtr(Other.getPtr());
219
220 // This Error is unchecked, even if the source error was checked.
221 setChecked(false);
222
223 // Null out Other's payload and set its checked bit.
224 Other.setPtr(nullptr);
225 Other.setChecked(true);
226
227 return *this;
228 }
229
230 /// Destroy a Error. Fails with a call to abort() if the error is
231 /// unchecked.
233 assertIsChecked();
234 delete getPtr();
235 }
236
237 /// Bool conversion. Returns true if this Error is in a failure state,
238 /// and false if it is in an accept state. If the error is in a Success state
239 /// it will be considered checked.
240 explicit operator bool() {
241 setChecked(getPtr() == nullptr);
242 return getPtr() != nullptr;
243 }
244
245 /// Check whether one error is a subclass of another.
246 template <typename ErrT> bool isA() const {
247 return getPtr() && getPtr()->isA(ErrT::classID());
248 }
249
250 /// Returns the dynamic class id of this error, or null if this is a success
251 /// value.
252 const void* dynamicClassID() const {
253 if (!getPtr())
254 return nullptr;
255 return getPtr()->dynamicClassID();
256 }
257
258private:
259#if LLVM_ENABLE_ABI_BREAKING_CHECKS
260 // assertIsChecked() happens very frequently, but under normal circumstances
261 // is supposed to be a no-op. So we want it to be inlined, but having a bunch
262 // of debug prints can cause the function to be too large for inlining. So
263 // it's important that we define this function out of line so that it can't be
264 // inlined.
265 [[noreturn]] LLVM_ABI void fatalUncheckedError() const;
266#endif
267
268 void assertIsChecked() {
269#if LLVM_ENABLE_ABI_BREAKING_CHECKS
270 if (LLVM_UNLIKELY(!getChecked() || getPtr()))
271 fatalUncheckedError();
272#endif
273 }
274
275 ErrorInfoBase *getPtr() const {
276#if LLVM_ENABLE_ABI_BREAKING_CHECKS
277 return reinterpret_cast<ErrorInfoBase*>(
278 reinterpret_cast<uintptr_t>(Payload) &
279 ~static_cast<uintptr_t>(0x1));
280#else
281 return Payload;
282#endif
283 }
284
285 void setPtr(ErrorInfoBase *EI) {
286#if LLVM_ENABLE_ABI_BREAKING_CHECKS
287 Payload = reinterpret_cast<ErrorInfoBase*>(
288 (reinterpret_cast<uintptr_t>(EI) &
289 ~static_cast<uintptr_t>(0x1)) |
290 (reinterpret_cast<uintptr_t>(Payload) & 0x1));
291#else
292 Payload = EI;
293#endif
294 }
295
296 bool getChecked() const {
297#if LLVM_ENABLE_ABI_BREAKING_CHECKS
298 return (reinterpret_cast<uintptr_t>(Payload) & 0x1) == 0;
299#else
300 return true;
301#endif
302 }
303
304 void setChecked(bool V) {
305#if LLVM_ENABLE_ABI_BREAKING_CHECKS
306 Payload = reinterpret_cast<ErrorInfoBase*>(
307 (reinterpret_cast<uintptr_t>(Payload) &
308 ~static_cast<uintptr_t>(0x1)) |
309 (V ? 0 : 1));
310#endif
311 }
312
313 std::unique_ptr<ErrorInfoBase> takePayload() {
314 std::unique_ptr<ErrorInfoBase> Tmp(getPtr());
315 setPtr(nullptr);
316 setChecked(true);
317 return Tmp;
318 }
319
320 friend raw_ostream &operator<<(raw_ostream &OS, const Error &E) {
321 if (auto *P = E.getPtr())
322 P->log(OS);
323 else
324 OS << "success";
325 return OS;
326 }
327
328 ErrorInfoBase *Payload = nullptr;
329};
330
331/// Subclass of Error for the sole purpose of identifying the success path in
332/// the type system. This allows to catch invalid conversion to Expected<T> at
333/// compile time.
334class ErrorSuccess final : public Error {};
335
337
338/// Make a Error instance representing failure using the given error info
339/// type.
340template <typename ErrT, typename... ArgTs> Error make_error(ArgTs &&... Args) {
341 return Error(std::make_unique<ErrT>(std::forward<ArgTs>(Args)...));
342}
343
344/// Base class for user error types. Users should declare their error types
345/// like:
346///
347/// class MyError : public ErrorInfo<MyError> {
348/// ....
349/// };
350///
351/// This class provides an implementation of the ErrorInfoBase::kind
352/// method, which is used by the Error RTTI system.
353template <typename ThisErrT, typename ParentErrT = ErrorInfoBase>
354class ErrorInfo : public ParentErrT {
355public:
356 using ParentErrT::ParentErrT; // inherit constructors
357
358 static const void *classID() { return &ThisErrT::ID; }
359
360 const void *dynamicClassID() const override { return &ThisErrT::ID; }
361
362 bool isA(const void *const ClassID) const override {
363 return ClassID == classID() || ParentErrT::isA(ClassID);
364 }
365};
366
367/// Special ErrorInfo subclass representing a list of ErrorInfos.
368/// Instances of this class are constructed by joinError.
369class LLVM_ABI ErrorList final : public ErrorInfo<ErrorList> {
370 // handleErrors needs to be able to iterate the payload list of an
371 // ErrorList.
372 template <typename... HandlerTs>
373 friend Error handleErrors(Error E, HandlerTs &&... Handlers);
374 // visitErrors needs to be able to iterate the payload list of an
375 // ErrorList.
376 template <typename HandlerT>
377 friend void visitErrors(const Error &E, HandlerT H);
378
379 // joinErrors is implemented in terms of join.
380 friend Error joinErrors(Error, Error);
381
382public:
383 void log(raw_ostream &OS) const override {
384 OS << "Multiple errors:\n";
385 for (const auto &ErrPayload : Payloads) {
386 ErrPayload->log(OS);
387 OS << "\n";
388 }
389 }
390
391 std::error_code convertToErrorCode() const override;
392
393 // Used by ErrorInfo::classID.
394 static char ID;
395
396private:
397 ErrorList(std::unique_ptr<ErrorInfoBase> Payload1,
398 std::unique_ptr<ErrorInfoBase> Payload2) {
399 assert(!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() &&
400 "ErrorList constructor payloads should be singleton errors");
401 Payloads.push_back(std::move(Payload1));
402 Payloads.push_back(std::move(Payload2));
403 }
404
405 // Explicitly non-copyable.
406 ErrorList(ErrorList const &) = delete;
407 ErrorList &operator=(ErrorList const &) = delete;
408
409 static Error join(Error E1, Error E2) {
410 if (!E1)
411 return E2;
412 if (!E2)
413 return E1;
414 if (E1.isA<ErrorList>()) {
415 auto &E1List = static_cast<ErrorList &>(*E1.getPtr());
416 if (E2.isA<ErrorList>()) {
417 auto E2Payload = E2.takePayload();
418 auto &E2List = static_cast<ErrorList &>(*E2Payload);
419 for (auto &Payload : E2List.Payloads)
420 E1List.Payloads.push_back(std::move(Payload));
421 } else {
422 E1List.Payloads.push_back(E2.takePayload());
423 }
424
425 return E1;
426 }
427 if (E2.isA<ErrorList>()) {
428 auto &E2List = static_cast<ErrorList &>(*E2.getPtr());
429 E2List.Payloads.insert(E2List.Payloads.begin(), E1.takePayload());
430 return E2;
431 }
432 return Error(std::unique_ptr<ErrorList>(
433 new ErrorList(E1.takePayload(), E2.takePayload())));
434 }
435
436 std::vector<std::unique_ptr<ErrorInfoBase>> Payloads;
437};
438
439/// Concatenate errors. The resulting Error is unchecked, and contains the
440/// ErrorInfo(s), if any, contained in E1, followed by the
441/// ErrorInfo(s), if any, contained in E2.
442inline Error joinErrors(Error E1, Error E2) {
443 return ErrorList::join(std::move(E1), std::move(E2));
444}
445
446/// Tagged union holding either a T or a Error.
447///
448/// This class parallels ErrorOr, but replaces error_code with Error. Since
449/// Error cannot be copied, this class replaces getError() with
450/// takeError(). It also adds an bool errorIsA<ErrT>() method for testing the
451/// error class type.
452///
453/// Example usage of 'Expected<T>' as a function return type:
454///
455/// @code{.cpp}
456/// Expected<int> myDivide(int A, int B) {
457/// if (B == 0) {
458/// // return an Error
459/// return createStringError(inconvertibleErrorCode(),
460/// "B must not be zero!");
461/// }
462/// // return an integer
463/// return A / B;
464/// }
465/// @endcode
466///
467/// Checking the results of to a function returning 'Expected<T>':
468/// @code{.cpp}
469/// if (auto E = Result.takeError()) {
470/// // We must consume the error. Typically one of:
471/// // - return the error to our caller
472/// // - toString(), when logging
473/// // - consumeError(), to silently swallow the error
474/// // - handleErrors(), to distinguish error types
475/// errs() << "Problem with division " << toString(std::move(E)) << "\n";
476/// return;
477/// }
478/// // use the result
479/// outs() << "The answer is " << *Result << "\n";
480/// @endcode
481///
482/// For unit-testing a function returning an 'Expected<T>', see the
483/// 'EXPECT_THAT_EXPECTED' macros in llvm/Testing/Support/Error.h
484
485template <class T> class [[nodiscard]] Expected {
486 template <class T1> friend class ExpectedAsOutParameter;
487 template <class OtherT> friend class Expected;
488
489 static constexpr bool isRef = std::is_reference_v<T>;
490
491 using wrap = std::reference_wrapper<std::remove_reference_t<T>>;
492
493 using error_type = std::unique_ptr<ErrorInfoBase>;
494
495public:
496 using storage_type = std::conditional_t<isRef, wrap, T>;
497 using value_type = T;
498
499private:
500 using reference = std::remove_reference_t<T> &;
501 using const_reference = const std::remove_reference_t<T> &;
502 using pointer = std::remove_reference_t<T> *;
503 using const_pointer = const std::remove_reference_t<T> *;
504
505public:
506 /// Create an Expected<T> error value from the given Error.
508 : HasError(true)
509#if LLVM_ENABLE_ABI_BREAKING_CHECKS
510 // Expected is unchecked upon construction in Debug builds.
511 , Unchecked(true)
512#endif
513 {
514 assert(Err && "Cannot create Expected<T> from Error success value.");
515 new (getErrorStorage()) error_type(Err.takePayload());
516 }
517
518 /// Forbid to convert from Error::success() implicitly, this avoids having
519 /// Expected<T> foo() { return Error::success(); } which compiles otherwise
520 /// but triggers the assertion above.
522
523 /// Create an Expected<T> success value from the given OtherT value, which
524 /// must be convertible to T.
525 template <typename OtherT>
526 Expected(OtherT &&Val,
527 std::enable_if_t<std::is_convertible_v<OtherT, T>> * = nullptr)
528 : HasError(false)
529#if LLVM_ENABLE_ABI_BREAKING_CHECKS
530 // Expected is unchecked upon construction in Debug builds.
531 ,
533#endif
534 {
535 new (getStorage()) storage_type(std::forward<OtherT>(Val));
536 }
537
538 /// Move construct an Expected<T> value.
539 Expected(Expected &&Other) { moveConstruct(std::move(Other)); }
540
541 /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT
542 /// must be convertible to T.
543 template <class OtherT>
545 std::enable_if_t<std::is_convertible_v<OtherT, T>> * = nullptr) {
546 moveConstruct(std::move(Other));
547 }
548
549 /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT
550 /// isn't convertible to T.
551 template <class OtherT>
552 explicit Expected(
554 std::enable_if_t<!std::is_convertible_v<OtherT, T>> * = nullptr) {
555 moveConstruct(std::move(Other));
556 }
557
558 /// Move-assign from another Expected<T>.
560 moveAssign(std::move(Other));
561 return *this;
562 }
563
564 /// Destroy an Expected<T>.
566 assertIsChecked();
567 if (!HasError)
568 getStorage()->~storage_type();
569 else
570 getErrorStorage()->~error_type();
571 }
572
573 /// Return false if there is an error.
574 explicit operator bool() {
575#if LLVM_ENABLE_ABI_BREAKING_CHECKS
576 Unchecked = HasError;
577#endif
578 return !HasError;
579 }
580
581 /// Returns a reference to the stored T value.
582 reference get() {
583 assertIsChecked();
584 return *getStorage();
585 }
586
587 /// Returns a const reference to the stored T value.
588 const_reference get() const {
589 assertIsChecked();
590 return const_cast<Expected<T> *>(this)->get();
591 }
592
593 /// Returns \a takeError() after moving the held T (if any) into \p V.
594 template <class OtherT>
596 OtherT &Value,
597 std::enable_if_t<std::is_assignable_v<OtherT &, T &&>> * = nullptr) && {
598 if (*this)
599 Value = std::move(get());
600 return takeError();
601 }
602
603 /// Check that this Expected<T> is an error of type ErrT.
604 template <typename ErrT> bool errorIsA() const {
605 return HasError && (*getErrorStorage())->template isA<ErrT>();
606 }
607
608 /// Take ownership of the stored error.
609 /// After calling this the Expected<T> is in an indeterminate state that can
610 /// only be safely destructed. No further calls (beside the destructor) should
611 /// be made on the Expected<T> value.
613#if LLVM_ENABLE_ABI_BREAKING_CHECKS
614 Unchecked = false;
615#endif
616 return HasError ? Error(std::move(*getErrorStorage())) : Error::success();
617 }
618
619 /// Returns a pointer to the stored T value.
620 pointer operator->() {
621 assertIsChecked();
622 return toPointer(getStorage());
623 }
624
625 /// Returns a const pointer to the stored T value.
626 const_pointer operator->() const {
627 assertIsChecked();
628 return toPointer(getStorage());
629 }
630
631 /// Returns a reference to the stored T value.
632 reference operator*() {
633 assertIsChecked();
634 return *getStorage();
635 }
636
637 /// Returns a const reference to the stored T value.
638 const_reference operator*() const {
639 assertIsChecked();
640 return *getStorage();
641 }
642
643private:
644 template <class T1>
645 static bool compareThisIfSameType(const T1 &a, const T1 &b) {
646 return &a == &b;
647 }
648
649 template <class T1, class T2>
650 static bool compareThisIfSameType(const T1 &, const T2 &) {
651 return false;
652 }
653
654 template <class OtherT> void moveConstruct(Expected<OtherT> &&Other) {
655 HasError = Other.HasError;
656#if LLVM_ENABLE_ABI_BREAKING_CHECKS
657 Unchecked = true;
658 Other.Unchecked = false;
659#endif
660
661 if (!HasError)
662 new (getStorage()) storage_type(std::move(*Other.getStorage()));
663 else
664 new (getErrorStorage()) error_type(std::move(*Other.getErrorStorage()));
665 }
666
667 template <class OtherT> void moveAssign(Expected<OtherT> &&Other) {
668 assertIsChecked();
669
670 if (compareThisIfSameType(*this, Other))
671 return;
672
673 this->~Expected();
674 new (this) Expected(std::move(Other));
675 }
676
677 pointer toPointer(pointer Val) { return Val; }
678
679 const_pointer toPointer(const_pointer Val) const { return Val; }
680
681 pointer toPointer(wrap *Val) { return &Val->get(); }
682
683 const_pointer toPointer(const wrap *Val) const { return &Val->get(); }
684
685 storage_type *getStorage() {
686 assert(!HasError && "Cannot get value when an error exists!");
687 return &TStorage;
688 }
689
690 const storage_type *getStorage() const {
691 assert(!HasError && "Cannot get value when an error exists!");
692 return &TStorage;
693 }
694
695 error_type *getErrorStorage() {
696 assert(HasError && "Cannot get error when a value exists!");
697 return &ErrorStorage;
698 }
699
700 const error_type *getErrorStorage() const {
701 assert(HasError && "Cannot get error when a value exists!");
702 return &ErrorStorage;
703 }
704
705 // Used by ExpectedAsOutParameter to reset the checked flag.
706 void setUnchecked() {
707#if LLVM_ENABLE_ABI_BREAKING_CHECKS
708 Unchecked = true;
709#endif
710 }
711
712#if LLVM_ENABLE_ABI_BREAKING_CHECKS
713 [[noreturn]] LLVM_ATTRIBUTE_NOINLINE void fatalUncheckedExpected() const {
714 dbgs() << "Expected<T> must be checked before access or destruction.\n";
715 if (HasError) {
716 dbgs() << "Unchecked Expected<T> contained error:\n";
717 (*getErrorStorage())->log(dbgs());
718 } else {
719 dbgs() << "Expected<T> value was in success state. (Note: Expected<T> "
720 "values in success mode must still be checked prior to being "
721 "destroyed).\n";
722 }
723 abort();
724 }
725#endif
726
727 void assertIsChecked() const {
728#if LLVM_ENABLE_ABI_BREAKING_CHECKS
730 fatalUncheckedExpected();
731#endif
732 }
733
734 union {
736 error_type ErrorStorage;
737 };
738 bool HasError : 1;
739#if LLVM_ENABLE_ABI_BREAKING_CHECKS
740 bool Unchecked : 1;
741#endif
742};
743
744/// @deprecated Use reportFatalInternalError() or reportFatalUsageError()
745/// instead.
746[[noreturn]] LLVM_ABI void report_fatal_error(Error Err,
747 bool gen_crash_diag = true);
748
749/// Report a fatal error that indicates a bug in LLVM.
750/// See ErrorHandling.h for details.
751[[noreturn]] LLVM_ABI void reportFatalInternalError(Error Err);
752/// Report a fatal error that does not indicate a bug in LLVM.
753/// See ErrorHandling.h for details.
754[[noreturn]] LLVM_ABI void reportFatalUsageError(Error Err);
755
756/// Report a fatal error if Err is a failure value.
757///
758/// This function can be used to wrap calls to fallible functions ONLY when it
759/// is known that the Error will always be a success value. E.g.
760///
761/// @code{.cpp}
762/// // foo only attempts the fallible operation if DoFallibleOperation is
763/// // true. If DoFallibleOperation is false then foo always returns
764/// // Error::success().
765/// Error foo(bool DoFallibleOperation);
766///
767/// cantFail(foo(false));
768/// @endcode
769inline void cantFail(Error Err, const char *Msg = nullptr) {
770 if (Err) {
771 if (!Msg)
772 Msg = "Failure value returned from cantFail wrapped call";
773#ifndef NDEBUG
774 std::string Str;
775 raw_string_ostream OS(Str);
776 OS << Msg << "\n" << Err;
777 Msg = Str.c_str();
778#endif
779 llvm_unreachable(Msg);
780 }
781}
782
783/// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and
784/// returns the contained value.
785///
786/// This function can be used to wrap calls to fallible functions ONLY when it
787/// is known that the Error will always be a success value. E.g.
788///
789/// @code{.cpp}
790/// // foo only attempts the fallible operation if DoFallibleOperation is
791/// // true. If DoFallibleOperation is false then foo always returns an int.
792/// Expected<int> foo(bool DoFallibleOperation);
793///
794/// int X = cantFail(foo(false));
795/// @endcode
796template <typename T>
797T cantFail(Expected<T> ValOrErr, const char *Msg = nullptr) {
798 if (ValOrErr)
799 return std::move(*ValOrErr);
800 else {
801 if (!Msg)
802 Msg = "Failure value returned from cantFail wrapped call";
803#ifndef NDEBUG
804 std::string Str;
805 raw_string_ostream OS(Str);
806 auto E = ValOrErr.takeError();
807 OS << Msg << "\n" << E;
808 Msg = Str.c_str();
809#endif
810 llvm_unreachable(Msg);
811 }
812}
813
814namespace detail {
815
816template <typename T>
817using compare_nullptr_t = decltype(std::declval<T &>() == nullptr);
818
819template <typename T>
821
822} // namespace detail
823
824/// Calls llvm_unreachable if Pointer is null, otherwise returns the
825/// pointer as is.
826template <typename T,
827 typename = std::enable_if_t<detail::is_nullptr_comparable<T>::value>>
828[[nodiscard]] decltype(auto) checkNotNull(
829 T &&Pointer,
830 const char *Msg = "Expected a non-null pointer but got a null pointer") {
831 assert(Msg);
832 if (Pointer != nullptr)
833 return std::forward<T>(Pointer);
834 llvm_unreachable(Msg);
835}
836
837/// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and
838/// returns the contained reference.
839///
840/// This function can be used to wrap calls to fallible functions ONLY when it
841/// is known that the Error will always be a success value. E.g.
842///
843/// @code{.cpp}
844/// // foo only attempts the fallible operation if DoFallibleOperation is
845/// // true. If DoFallibleOperation is false then foo always returns a Bar&.
846/// Expected<Bar&> foo(bool DoFallibleOperation);
847///
848/// Bar &X = cantFail(foo(false));
849/// @endcode
850template <typename T>
851T& cantFail(Expected<T&> ValOrErr, const char *Msg = nullptr) {
852 if (ValOrErr)
853 return *ValOrErr;
854 else {
855 if (!Msg)
856 Msg = "Failure value returned from cantFail wrapped call";
857#ifndef NDEBUG
858 std::string Str;
859 raw_string_ostream OS(Str);
860 auto E = ValOrErr.takeError();
861 OS << Msg << "\n" << E;
862 Msg = Str.c_str();
863#endif
864 llvm_unreachable(Msg);
865 }
866}
867
868/// Helper for testing applicability of, and applying, handlers for
869/// ErrorInfo types.
870template <typename HandlerT>
872 : public ErrorHandlerTraits<
873 decltype(&std::remove_reference_t<HandlerT>::operator())> {};
874
875// Specialization functions of the form 'Error (const ErrT&)'.
876template <typename ErrT> class ErrorHandlerTraits<Error (&)(ErrT &)> {
877public:
878 static bool appliesTo(const ErrorInfoBase &E) {
879 return E.template isA<ErrT>();
880 }
881
882 template <typename HandlerT>
883 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
884 assert(appliesTo(*E) && "Applying incorrect handler");
885 return H(static_cast<ErrT &>(*E));
886 }
887};
888
889// Specialization functions of the form 'void (const ErrT&)'.
890template <typename ErrT> class ErrorHandlerTraits<void (&)(ErrT &)> {
891public:
892 static bool appliesTo(const ErrorInfoBase &E) {
893 return E.template isA<ErrT>();
894 }
895
896 template <typename HandlerT>
897 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
898 assert(appliesTo(*E) && "Applying incorrect handler");
899 H(static_cast<ErrT &>(*E));
900 return Error::success();
901 }
902};
903
904/// Specialization for functions of the form 'Error (std::unique_ptr<ErrT>)'.
905template <typename ErrT>
906class ErrorHandlerTraits<Error (&)(std::unique_ptr<ErrT>)> {
907public:
908 static bool appliesTo(const ErrorInfoBase &E) {
909 return E.template isA<ErrT>();
910 }
911
912 template <typename HandlerT>
913 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
914 assert(appliesTo(*E) && "Applying incorrect handler");
915 std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release()));
916 return H(std::move(SubE));
917 }
918};
919
920/// Specialization for functions of the form 'void (std::unique_ptr<ErrT>)'.
921template <typename ErrT>
922class ErrorHandlerTraits<void (&)(std::unique_ptr<ErrT>)> {
923public:
924 static bool appliesTo(const ErrorInfoBase &E) {
925 return E.template isA<ErrT>();
926 }
927
928 template <typename HandlerT>
929 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
930 assert(appliesTo(*E) && "Applying incorrect handler");
931 std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release()));
932 H(std::move(SubE));
933 return Error::success();
934 }
935};
936
937// Specialization for member functions of the form 'RetT (const ErrT&)'.
938template <typename C, typename RetT, typename ErrT>
939class ErrorHandlerTraits<RetT (C::*)(ErrT &)>
940 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
941
942// Specialization for member functions of the form 'RetT (const ErrT&) const'.
943template <typename C, typename RetT, typename ErrT>
944class ErrorHandlerTraits<RetT (C::*)(ErrT &) const>
945 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
946
947// Specialization for member functions of the form 'RetT (const ErrT&)'.
948template <typename C, typename RetT, typename ErrT>
949class ErrorHandlerTraits<RetT (C::*)(const ErrT &)>
950 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
951
952// Specialization for member functions of the form 'RetT (const ErrT&) const'.
953template <typename C, typename RetT, typename ErrT>
954class ErrorHandlerTraits<RetT (C::*)(const ErrT &) const>
955 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
956
957/// Specialization for member functions of the form
958/// 'RetT (std::unique_ptr<ErrT>)'.
959template <typename C, typename RetT, typename ErrT>
960class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>)>
961 : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {};
962
963/// Specialization for member functions of the form
964/// 'RetT (std::unique_ptr<ErrT>) const'.
965template <typename C, typename RetT, typename ErrT>
966class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>) const>
967 : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {};
968
969inline Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload) {
970 return Error(std::move(Payload));
971}
972
973template <typename HandlerT, typename... HandlerTs>
974Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload,
975 HandlerT &&Handler, HandlerTs &&... Handlers) {
977 return ErrorHandlerTraits<HandlerT>::apply(std::forward<HandlerT>(Handler),
978 std::move(Payload));
979 return handleErrorImpl(std::move(Payload),
980 std::forward<HandlerTs>(Handlers)...);
981}
982
983/// Pass the ErrorInfo(s) contained in E to their respective handlers. Any
984/// unhandled errors (or Errors returned by handlers) are re-concatenated and
985/// returned.
986/// Because this function returns an error, its result must also be checked
987/// or returned. If you intend to handle all errors use handleAllErrors
988/// (which returns void, and will abort() on unhandled errors) instead.
989template <typename... HandlerTs>
990Error handleErrors(Error E, HandlerTs &&... Hs) {
991 if (!E)
992 return Error::success();
993
994 std::unique_ptr<ErrorInfoBase> Payload = E.takePayload();
995
996 if (Payload->isA<ErrorList>()) {
997 ErrorList &List = static_cast<ErrorList &>(*Payload);
998 Error R;
999 for (auto &P : List.Payloads)
1000 R = ErrorList::join(
1001 std::move(R),
1002 handleErrorImpl(std::move(P), std::forward<HandlerTs>(Hs)...));
1003 return R;
1004 }
1005
1006 return handleErrorImpl(std::move(Payload), std::forward<HandlerTs>(Hs)...);
1007}
1008
1009/// Behaves the same as handleErrors, except that by contract all errors
1010/// *must* be handled by the given handlers (i.e. there must be no remaining
1011/// errors after running the handlers, or llvm_unreachable is called).
1012template <typename... HandlerTs>
1013void handleAllErrors(Error E, HandlerTs &&... Handlers) {
1014 cantFail(handleErrors(std::move(E), std::forward<HandlerTs>(Handlers)...));
1015}
1016
1017/// Check that E is a non-error, then drop it.
1018/// If E is an error, llvm_unreachable will be called.
1020 cantFail(std::move(E));
1021}
1022
1023/// Visit all the ErrorInfo(s) contained in E by passing them to the respective
1024/// handler, without consuming the error.
1025template <typename HandlerT> void visitErrors(const Error &E, HandlerT H) {
1026 const ErrorInfoBase *Payload = E.getPtr();
1027 if (!Payload)
1028 return;
1029
1030 if (Payload->isA<ErrorList>()) {
1031 const ErrorList &List = static_cast<const ErrorList &>(*Payload);
1032 for (const auto &P : List.Payloads)
1033 H(*P);
1034 return;
1035 }
1036
1037 return H(*Payload);
1038}
1039
1040/// Handle any errors (if present) in an Expected<T>, then try a recovery path.
1041///
1042/// If the incoming value is a success value it is returned unmodified. If it
1043/// is a failure value then it the contained error is passed to handleErrors.
1044/// If handleErrors is able to handle the error then the RecoveryPath functor
1045/// is called to supply the final result. If handleErrors is not able to
1046/// handle all errors then the unhandled errors are returned.
1047///
1048/// This utility enables the follow pattern:
1049///
1050/// @code{.cpp}
1051/// enum FooStrategy { Aggressive, Conservative };
1052/// Expected<Foo> foo(FooStrategy S);
1053///
1054/// auto ResultOrErr =
1055/// handleExpected(
1056/// foo(Aggressive),
1057/// []() { return foo(Conservative); },
1058/// [](AggressiveStrategyError&) {
1059/// // Implicitly conusme this - we'll recover by using a conservative
1060/// // strategy.
1061/// });
1062///
1063/// @endcode
1064template <typename T, typename RecoveryFtor, typename... HandlerTs>
1065Expected<T> handleExpected(Expected<T> ValOrErr, RecoveryFtor &&RecoveryPath,
1066 HandlerTs &&... Handlers) {
1067 if (ValOrErr)
1068 return ValOrErr;
1069
1070 if (auto Err = handleErrors(ValOrErr.takeError(),
1071 std::forward<HandlerTs>(Handlers)...))
1072 return std::move(Err);
1073
1074 return RecoveryPath();
1075}
1076
1077/// Log all errors (if any) in E to OS. If there are any errors, ErrorBanner
1078/// will be printed before the first one is logged. A newline will be printed
1079/// after each error.
1080///
1081/// This function is compatible with the helpers from Support/WithColor.h. You
1082/// can pass any of them as the OS. Please consider using them instead of
1083/// including 'error: ' in the ErrorBanner.
1084///
1085/// This is useful in the base level of your program to allow clean termination
1086/// (allowing clean deallocation of resources, etc.), while reporting error
1087/// information to the user.
1088LLVM_ABI void logAllUnhandledErrors(Error E, raw_ostream &OS,
1089 Twine ErrorBanner = {});
1090
1091/// Write all error messages (if any) in E to a string. The newline character
1092/// is used to separate error messages.
1093LLVM_ABI std::string toString(Error E);
1094
1095/// Like toString(), but does not consume the error. This can be used to print
1096/// a warning while retaining the original error object.
1097LLVM_ABI std::string toStringWithoutConsuming(const Error &E);
1098
1099/// Consume a Error without doing anything. This method should be used
1100/// only where an error can be considered a reasonable and expected return
1101/// value.
1102///
1103/// Uses of this method are potentially indicative of design problems: If it's
1104/// legitimate to do nothing while processing an "error", the error-producer
1105/// might be more clearly refactored to return an std::optional<T>.
1106inline void consumeError(Error Err) {
1107 handleAllErrors(std::move(Err), [](const ErrorInfoBase &) {});
1108}
1109
1110/// Convert an Expected to an Optional without doing anything. This method
1111/// should be used only where an error can be considered a reasonable and
1112/// expected return value.
1113///
1114/// Uses of this method are potentially indicative of problems: perhaps the
1115/// error should be propagated further, or the error-producer should just
1116/// return an Optional in the first place.
1117template <typename T> std::optional<T> expectedToOptional(Expected<T> &&E) {
1118 if (E)
1119 return std::move(*E);
1120 consumeError(E.takeError());
1121 return std::nullopt;
1122}
1123
1124template <typename T> std::optional<T> expectedToStdOptional(Expected<T> &&E) {
1125 if (E)
1126 return std::move(*E);
1127 consumeError(E.takeError());
1128 return std::nullopt;
1129}
1130
1131/// Helper for converting an Error to a bool.
1132///
1133/// This method returns true if Err is in an error state, or false if it is
1134/// in a success state. Puts Err in a checked state in both cases (unlike
1135/// Error::operator bool(), which only does this for success states).
1136inline bool errorToBool(Error Err) {
1137 bool IsError = static_cast<bool>(Err);
1138 if (IsError)
1139 consumeError(std::move(Err));
1140 return IsError;
1141}
1142
1143/// Helper for Errors used as out-parameters.
1144///
1145/// This helper is for use with the Error-as-out-parameter idiom, where an error
1146/// is passed to a function or method by reference, rather than being returned.
1147/// In such cases it is helpful to set the checked bit on entry to the function
1148/// so that the error can be written to (unchecked Errors abort on assignment)
1149/// and clear the checked bit on exit so that clients cannot accidentally forget
1150/// to check the result. This helper performs these actions automatically using
1151/// RAII:
1152///
1153/// @code{.cpp}
1154/// Result foo(Error &Err) {
1155/// ErrorAsOutParameter ErrAsOutParam(&Err); // 'Checked' flag set
1156/// // <body of foo>
1157/// // <- 'Checked' flag auto-cleared when ErrAsOutParam is destructed.
1158/// }
1159/// @endcode
1160///
1161/// ErrorAsOutParameter takes an Error* rather than Error& so that it can be
1162/// used with optional Errors (Error pointers that are allowed to be null). If
1163/// ErrorAsOutParameter took an Error reference, an instance would have to be
1164/// created inside every condition that verified that Error was non-null. By
1165/// taking an Error pointer we can just create one instance at the top of the
1166/// function.
1168public:
1169
1170 ErrorAsOutParameter(Error *Err) : Err(Err) {
1171 // Raise the checked bit if Err is success.
1172 if (Err)
1173 (void)!!*Err;
1174 }
1175
1176 ErrorAsOutParameter(Error &Err) : Err(&Err) {
1177 (void)!!Err;
1178 }
1179
1181 // Clear the checked bit.
1182 if (Err && !*Err)
1183 *Err = Error::success();
1184 }
1185
1186private:
1187 Error *Err;
1188};
1189
1190/// Helper for Expected<T>s used as out-parameters.
1191///
1192/// See ErrorAsOutParameter.
1193template <typename T>
1195public:
1197 : ValOrErr(ValOrErr) {
1198 if (ValOrErr)
1199 (void)!!*ValOrErr;
1200 }
1201
1203 if (ValOrErr)
1204 ValOrErr->setUnchecked();
1205 }
1206
1207private:
1208 Expected<T> *ValOrErr;
1209};
1210
1211/// This class wraps a std::error_code in a Error.
1212///
1213/// This is useful if you're writing an interface that returns a Error
1214/// (or Expected) and you want to call code that still returns
1215/// std::error_codes.
1216class LLVM_ABI ECError : public ErrorInfo<ECError> {
1217 LLVM_ABI friend Error errorCodeToError(std::error_code);
1218
1219 void anchor() override;
1220
1221public:
1222 void setErrorCode(std::error_code EC) { this->EC = EC; }
1223 std::error_code convertToErrorCode() const override { return EC; }
1224 void log(raw_ostream &OS) const override { OS << EC.message(); }
1225
1226 // Used by ErrorInfo::classID.
1227 static char ID;
1228
1229protected:
1230 ECError() = default;
1231 ECError(std::error_code EC) : EC(EC) {}
1232
1233 std::error_code EC;
1234};
1235
1236/// The value returned by this function can be returned from convertToErrorCode
1237/// for Error values where no sensible translation to std::error_code exists.
1238/// It should only be used in this situation, and should never be used where a
1239/// sensible conversion to std::error_code is available, as attempts to convert
1240/// to/from this error will result in a fatal error. (i.e. it is a programmatic
1241/// error to try to convert such a value).
1242LLVM_ABI std::error_code inconvertibleErrorCode();
1243
1244/// Helper for converting an std::error_code to a Error.
1245LLVM_ABI Error errorCodeToError(std::error_code EC);
1246
1247/// Helper for converting an ECError to a std::error_code.
1248///
1249/// This method requires that Err be Error() or an ECError, otherwise it
1250/// will trigger a call to abort().
1251LLVM_ABI std::error_code errorToErrorCode(Error Err);
1252
1253/// Helper to get errno as an std::error_code.
1254///
1255/// errno should always be represented using the generic category as that's what
1256/// both libc++ and libstdc++ do. On POSIX systems you can also represent them
1257/// using the system category, however this makes them compare differently for
1258/// values outside of those used by `std::errc` if one is generic and the other
1259/// is system.
1260///
1261/// See the libc++ and libstdc++ implementations of `default_error_condition` on
1262/// the system category for more details on what the difference is.
1263inline std::error_code errnoAsErrorCode() {
1264 return std::error_code(errno, std::generic_category());
1265}
1266
1267/// Convert an ErrorOr<T> to an Expected<T>.
1268template <typename T> Expected<T> errorOrToExpected(ErrorOr<T> &&EO) {
1269 if (auto EC = EO.getError())
1270 return errorCodeToError(EC);
1271 return std::move(*EO);
1272}
1273
1274/// Convert an Expected<T> to an ErrorOr<T>.
1275template <typename T> ErrorOr<T> expectedToErrorOr(Expected<T> &&E) {
1276 if (auto Err = E.takeError())
1277 return errorToErrorCode(std::move(Err));
1278 return std::move(*E);
1279}
1280
1281/// This class wraps a string in an Error.
1282///
1283/// StringError is useful in cases where the client is not expected to be able
1284/// to consume the specific error message programmatically (for example, if the
1285/// error message is to be presented to the user).
1286///
1287/// StringError can also be used when additional information is to be printed
1288/// along with a error_code message. Depending on the constructor called, this
1289/// class can either display:
1290/// 1. the error_code message (ECError behavior)
1291/// 2. a string
1292/// 3. the error_code message and a string
1293///
1294/// These behaviors are useful when subtyping is required; for example, when a
1295/// specific library needs an explicit error type. In the example below,
1296/// PDBError is derived from StringError:
1297///
1298/// @code{.cpp}
1299/// Expected<int> foo() {
1300/// return llvm::make_error<PDBError>(pdb_error_code::dia_failed_loading,
1301/// "Additional information");
1302/// }
1303/// @endcode
1304///
1305class LLVM_ABI StringError : public ErrorInfo<StringError> {
1306public:
1307 static char ID;
1308
1309 StringError(std::string &&S, std::error_code EC, bool PrintMsgOnly);
1310 /// Prints EC + S and converts to EC.
1311 StringError(std::error_code EC, const Twine &S = Twine());
1312 /// Prints S and converts to EC.
1313 StringError(const Twine &S, std::error_code EC);
1314
1315 void log(raw_ostream &OS) const override;
1316 std::error_code convertToErrorCode() const override;
1317
1318 const std::string &getMessage() const { return Msg; }
1319
1320private:
1321 std::string Msg;
1322 std::error_code EC;
1323 const bool PrintMsgOnly = false;
1324};
1325
1326/// Create formatted StringError object.
1327template <typename... Ts>
1328inline Error createStringError(std::error_code EC, char const *Fmt,
1329 const Ts &... Vals) {
1330 std::string Buffer;
1331 raw_string_ostream(Buffer) << format(Fmt, Vals...);
1332 return make_error<StringError>(std::move(Buffer), EC, true);
1333}
1334
1335LLVM_ABI Error createStringError(std::string &&Msg, std::error_code EC);
1336
1337inline Error createStringError(std::error_code EC, const char *S) {
1338 return createStringError(std::string(S), EC);
1339}
1340
1341inline Error createStringError(std::error_code EC, const Twine &S) {
1342 return createStringError(S.str(), EC);
1343}
1344
1345/// Create a StringError with an inconvertible error code.
1349
1350template <typename... Ts>
1351inline Error createStringError(char const *Fmt, const Ts &...Vals) {
1352 return createStringError(llvm::inconvertibleErrorCode(), Fmt, Vals...);
1353}
1354
1355template <typename... Ts>
1356inline Error createStringError(std::errc EC, char const *Fmt,
1357 const Ts &... Vals) {
1358 return createStringError(std::make_error_code(EC), Fmt, Vals...);
1359}
1360
1361/// This class wraps a filename and another Error.
1362///
1363/// In some cases, an error needs to live along a 'source' name, in order to
1364/// show more detailed information to the user.
1365class LLVM_ABI FileError final : public ErrorInfo<FileError> {
1366
1367 friend Error createFileError(const Twine &, Error);
1368 friend Error createFileError(const Twine &, size_t, Error);
1369
1370public:
1371 void log(raw_ostream &OS) const override {
1372 assert(Err && "Trying to log after takeError().");
1373 OS << "'" << FileName << "': ";
1374 if (Line)
1375 OS << "line " << *Line << ": ";
1376 Err->log(OS);
1377 }
1378
1379 std::string messageWithoutFileInfo() const {
1380 std::string Msg;
1381 raw_string_ostream OS(Msg);
1382 Err->log(OS);
1383 return Msg;
1384 }
1385
1386 StringRef getFileName() const { return FileName; }
1387
1388 Error takeError() { return Error(std::move(Err)); }
1389
1390 std::error_code convertToErrorCode() const override;
1391
1392 // Used by ErrorInfo::classID.
1393 static char ID;
1394
1395private:
1396 FileError(const Twine &F, std::optional<size_t> LineNum,
1397 std::unique_ptr<ErrorInfoBase> E) {
1398 assert(E && "Cannot create FileError from Error success value.");
1399 FileName = F.str();
1400 Err = std::move(E);
1401 Line = std::move(LineNum);
1402 }
1403
1404 static Error build(const Twine &F, std::optional<size_t> Line, Error E) {
1405 std::unique_ptr<ErrorInfoBase> Payload;
1406 handleAllErrors(std::move(E),
1407 [&](std::unique_ptr<ErrorInfoBase> EIB) -> Error {
1408 Payload = std::move(EIB);
1409 return Error::success();
1410 });
1411 return Error(
1412 std::unique_ptr<FileError>(new FileError(F, Line, std::move(Payload))));
1413 }
1414
1415 std::string FileName;
1416 std::optional<size_t> Line;
1417 std::unique_ptr<ErrorInfoBase> Err;
1418};
1419
1420/// Concatenate a source file path and/or name with an Error. The resulting
1421/// Error is unchecked.
1423 return FileError::build(F, std::optional<size_t>(), std::move(E));
1424}
1425
1426/// Concatenate a source file path and/or name with line number and an Error.
1427/// The resulting Error is unchecked.
1428inline Error createFileError(const Twine &F, size_t Line, Error E) {
1429 return FileError::build(F, std::optional<size_t>(Line), std::move(E));
1430}
1431
1432/// Concatenate a source file path and/or name with a std::error_code
1433/// to form an Error object.
1434inline Error createFileError(const Twine &F, std::error_code EC) {
1435 return createFileError(F, errorCodeToError(EC));
1436}
1437
1438/// Concatenate a source file path and/or name with line number and
1439/// std::error_code to form an Error object.
1440inline Error createFileError(const Twine &F, size_t Line, std::error_code EC) {
1441 return createFileError(F, Line, errorCodeToError(EC));
1442}
1443
1444/// Create a StringError with the specified error code and prepend the file path
1445/// to it.
1446inline Error createFileError(const Twine &F, std::error_code EC,
1447 const Twine &S) {
1448 Error E = createStringError(EC, S);
1449 return createFileError(F, std::move(E));
1450}
1451
1452/// Create a StringError with the specified error code and prepend the file path
1453/// to it.
1454template <typename... Ts>
1455inline Error createFileError(const Twine &F, std::error_code EC,
1456 char const *Fmt, const Ts &...Vals) {
1457 Error E = createStringError(EC, Fmt, Vals...);
1458 return createFileError(F, std::move(E));
1459}
1460
1462
1463/// Helper for check-and-exit error handling.
1464///
1465/// For tool use only. NOT FOR USE IN LIBRARY CODE.
1466///
1468public:
1469 /// Create an error on exit helper.
1470 ExitOnError(std::string Banner = "", int DefaultErrorExitCode = 1)
1471 : Banner(std::move(Banner)),
1472 GetExitCode([=](const Error &) { return DefaultErrorExitCode; }) {}
1473
1474 /// Set the banner string for any errors caught by operator().
1475 void setBanner(std::string Banner) { this->Banner = std::move(Banner); }
1476
1477 /// Set the exit-code mapper function.
1478 void setExitCodeMapper(std::function<int(const Error &)> GetExitCode) {
1479 this->GetExitCode = std::move(GetExitCode);
1480 }
1481
1482 /// Check Err. If it's in a failure state log the error(s) and exit.
1483 void operator()(Error Err) const { checkError(std::move(Err)); }
1484
1485 /// Check E. If it's in a success state then return the contained value. If
1486 /// it's in a failure state log the error(s) and exit.
1487 template <typename T> T operator()(Expected<T> &&E) const {
1488 checkError(E.takeError());
1489 return std::move(*E);
1490 }
1491
1492 /// Check E. If it's in a success state then return the contained reference. If
1493 /// it's in a failure state log the error(s) and exit.
1494 template <typename T> T& operator()(Expected<T&> &&E) const {
1495 checkError(E.takeError());
1496 return *E;
1497 }
1498
1499private:
1500 void checkError(Error Err) const {
1501 if (Err) {
1502 int ExitCode = GetExitCode(Err);
1503 logAllUnhandledErrors(std::move(Err), errs(), Banner);
1504 exit(ExitCode);
1505 }
1506 }
1507
1508 std::string Banner;
1509 std::function<int(const Error &)> GetExitCode;
1510};
1511
1512/// Conversion from Error to LLVMErrorRef for C error bindings.
1514 return reinterpret_cast<LLVMErrorRef>(Err.takePayload().release());
1515}
1516
1517/// Conversion from LLVMErrorRef to Error for C error bindings.
1518inline Error unwrap(LLVMErrorRef ErrRef) {
1519 return Error(std::unique_ptr<ErrorInfoBase>(
1520 reinterpret_cast<ErrorInfoBase *>(ErrRef)));
1521}
1522
1523} // end namespace llvm
1524
1525#endif // LLVM_SUPPORT_ERROR_H
@ Unchecked
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_UNLIKELY(EXPR)
Definition Compiler.h:336
#define LLVM_ABI
Definition Compiler.h:213
#define LLVM_ATTRIBUTE_NOINLINE
LLVM_ATTRIBUTE_NOINLINE - On compilers where we have a directive to do so, mark a method "not for inl...
Definition Compiler.h:346
Provides ErrorOr<T> smart pointer.
static LLVMTargetMachineRef wrap(const TargetMachine *P)
#define F(x, y, z)
Definition MD5.cpp:54
#define H(x, y, z)
Definition MD5.cpp:56
static const char * getPtr(const MachOObjectFile &O, size_t Offset, size_t MachOFilesetEntryOffset=0)
#define T
#define T1
#define P(N)
if(PassOpts->AAPipeline)
ECError()=default
std::error_code EC
Definition Error.h:1233
LLVM_ABI friend Error errorCodeToError(std::error_code)
Helper for converting an std::error_code to a Error.
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition Error.h:1223
ECError(std::error_code EC)
Definition Error.h:1231
static char ID
Definition Error.h:1227
void setErrorCode(std::error_code EC)
Definition Error.h:1222
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition Error.h:1224
ErrorAsOutParameter(Error *Err)
Definition Error.h:1170
ErrorAsOutParameter(Error &Err)
Definition Error.h:1176
static bool appliesTo(const ErrorInfoBase &E)
Definition Error.h:878
static Error apply(HandlerT &&H, std::unique_ptr< ErrorInfoBase > E)
Definition Error.h:883
static Error apply(HandlerT &&H, std::unique_ptr< ErrorInfoBase > E)
Definition Error.h:913
static bool appliesTo(const ErrorInfoBase &E)
Definition Error.h:908
static bool appliesTo(const ErrorInfoBase &E)
Definition Error.h:892
static Error apply(HandlerT &&H, std::unique_ptr< ErrorInfoBase > E)
Definition Error.h:897
static bool appliesTo(const ErrorInfoBase &E)
Definition Error.h:924
static Error apply(HandlerT &&H, std::unique_ptr< ErrorInfoBase > E)
Definition Error.h:929
Helper for testing applicability of, and applying, handlers for ErrorInfo types.
Definition Error.h:873
Base class for error info classes.
Definition Error.h:44
virtual ~ErrorInfoBase()=default
virtual std::string message() const
Return the error message as a string.
Definition Error.h:52
static const void * classID()
Definition Error.h:66
bool isA() const
Definition Error.h:78
virtual const void * dynamicClassID() const =0
virtual bool isA(const void *const ClassID) const
Definition Error.h:73
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.
Base class for user error types.
Definition Error.h:354
bool isA(const void *const ClassID) const override
Definition Error.h:362
const void * dynamicClassID() const override
Definition Error.h:360
static const void * classID()
Definition Error.h:358
Special ErrorInfo subclass representing a list of ErrorInfos.
Definition Error.h:369
friend Error handleErrors(Error E, HandlerTs &&... Handlers)
Pass the ErrorInfo(s) contained in E to their respective handlers.
Definition Error.h:990
static char ID
Definition Error.h:394
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition Error.h:383
friend Error joinErrors(Error, Error)
Concatenate errors.
Definition Error.h:442
friend 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:1025
Represents either an error or a value T.
Definition ErrorOr.h:56
Subclass of Error for the sole purpose of identifying the success path in the type system.
Definition Error.h:334
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
Error(Error &&Other)
Move-construct an error value.
Definition Error.h:196
friend Error handleErrors(Error E, HandlerTs &&... Handlers)
Pass the ErrorInfo(s) contained in E to their respective handlers.
Definition Error.h:990
~Error()
Destroy a Error.
Definition Error.h:232
const void * dynamicClassID() const
Returns the dynamic class id of this error, or null if this is a success value.
Definition Error.h:252
friend raw_ostream & operator<<(raw_ostream &OS, const Error &E)
Definition Error.h:320
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Error(std::unique_ptr< ErrorInfoBase > Payload)
Create an error value.
Definition Error.h:203
Error & operator=(const Error &Other)=delete
Error()
Create a success value. Prefer using 'Error::success()' for readability.
Definition Error.h:181
friend class Expected
Definition Error.h:174
Error(const Error &Other)=delete
friend 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:1025
Error & operator=(Error &&Other)
Move-assign an error value.
Definition Error.h:215
friend class ErrorList
Definition Error.h:163
bool isA() const
Check whether one error is a subclass of another.
Definition Error.h:246
void setBanner(std::string Banner)
Set the banner string for any errors caught by operator().
Definition Error.h:1475
ExitOnError(std::string Banner="", int DefaultErrorExitCode=1)
Create an error on exit helper.
Definition Error.h:1470
T operator()(Expected< T > &&E) const
Check E.
Definition Error.h:1487
T & operator()(Expected< T & > &&E) const
Check E.
Definition Error.h:1494
void operator()(Error Err) const
Check Err. If it's in a failure state log the error(s) and exit.
Definition Error.h:1483
void setExitCodeMapper(std::function< int(const Error &)> GetExitCode)
Set the exit-code mapper function.
Definition Error.h:1478
ExpectedAsOutParameter(Expected< T > *ValOrErr)
Definition Error.h:1196
Tagged union holding either a T or a Error.
Definition Error.h:485
const_reference operator*() const
Returns a const reference to the stored T value.
Definition Error.h:638
Expected(Expected< OtherT > &&Other, std::enable_if_t<!std::is_convertible_v< OtherT, T > > *=nullptr)
Move construct an Expected<T> value from an Expected<OtherT>, where OtherT isn't convertible to T.
Definition Error.h:552
Error moveInto(OtherT &Value, std::enable_if_t< std::is_assignable_v< OtherT &, T && > > *=nullptr) &&
Returns takeError() after moving the held T (if any) into V.
Definition Error.h:595
pointer operator->()
Returns a pointer to the stored T value.
Definition Error.h:620
reference operator*()
Returns a reference to the stored T value.
Definition Error.h:632
Expected(OtherT &&Val, std::enable_if_t< std::is_convertible_v< OtherT, T > > *=nullptr)
Create an Expected<T> success value from the given OtherT value, which must be convertible to T.
Definition Error.h:526
~Expected()
Destroy an Expected<T>.
Definition Error.h:565
const_reference get() const
Returns a const reference to the stored T value.
Definition Error.h:588
bool errorIsA() const
Check that this Expected<T> is an error of type ErrT.
Definition Error.h:604
Expected(ErrorSuccess)=delete
Forbid to convert from Error::success() implicitly, this avoids having Expected<T> foo() { return Err...
friend class Expected
Definition Error.h:487
Expected(Error &&Err)
Create an Expected<T> error value from the given Error.
Definition Error.h:507
const_pointer operator->() const
Returns a const pointer to the stored T value.
Definition Error.h:626
Expected & operator=(Expected &&Other)
Move-assign from another Expected<T>.
Definition Error.h:559
reference get()
Returns a reference to the stored T value.
Definition Error.h:582
std::conditional_t< isRef, wrap, std::unique_ptr< InFlightAlloc > > storage_type
Definition Error.h:496
Expected(Expected &&Other)
Move construct an Expected<T> value.
Definition Error.h:539
std::unique_ptr< InFlightAlloc > value_type
Definition Error.h:497
Expected(Expected< OtherT > &&Other, std::enable_if_t< std::is_convertible_v< OtherT, T > > *=nullptr)
Move construct an Expected<T> value from an Expected<OtherT>, where OtherT must be convertible to T.
Definition Error.h:544
Error takeError()
Definition Error.h:1388
std::string messageWithoutFileInfo() const
Definition Error.h:1379
StringRef getFileName() const
Definition Error.h:1386
static char ID
Definition Error.h:1393
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition Error.h:1371
friend Error createFileError(const Twine &, Error)
Concatenate a source file path and/or name with an Error.
Definition Error.h:1422
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition Error.cpp:155
static char ID
Definition Error.h:1307
const std::string & getMessage() const
Definition Error.h:1318
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition Error.cpp:145
StringError(std::string &&S, std::error_code EC, bool PrintMsgOnly)
Definition Error.cpp:142
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
LLVM_ABI std::string str() const
Return the twine contents as a std::string.
Definition Twine.cpp:17
LLVM Value Representation.
Definition Value.h:75
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
A raw_ostream that writes to an std::string.
struct LLVMOpaqueError * LLVMErrorRef
Opaque reference to an error instance.
Definition Error.h:34
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
llvm::is_detected< compare_nullptr_t, T > is_nullptr_comparable
Definition Error.h:820
decltype(std::declval< T & >()==nullptr) compare_nullptr_t
Definition Error.h:817
This is an optimization pass for GlobalISel generic memory operations.
bool errorToBool(Error Err)
Helper for converting an Error to a bool.
Definition Error.h:1136
LLVM_ABI void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner={})
Log all errors (if any) in E to OS.
Definition Error.cpp:61
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:1025
Error createFileError(const Twine &F, Error E)
Concatenate a source file path and/or name with an Error.
Definition Error.h:1422
std::optional< T > expectedToStdOptional(Expected< T > &&E)
Definition Error.h:1124
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:1013
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition Error.cpp:94
Error handleErrors(Error E, HandlerTs &&... Hs)
Pass the ErrorInfo(s) contained in E to their respective handlers.
Definition Error.h:990
decltype(auto) checkNotNull(T &&Pointer, const char *Msg="Expected a non-null pointer but got a null pointer")
Calls llvm_unreachable if Pointer is null, otherwise returns the pointer as is.
Definition Error.h:828
ErrorOr< T > expectedToErrorOr(Expected< T > &&E)
Convert an Expected<T> to an ErrorOr<T>.
Definition Error.h:1275
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition Error.h:1328
LLVM_ABI void reportFatalInternalError(Error Err)
Report a fatal error that indicates a bug in LLVM.
Definition Error.cpp:173
std::optional< T > expectedToOptional(Expected< T > &&E)
Convert an Expected to an Optional without doing anything.
Definition Error.h:1117
LLVM_ABI std::string toStringWithoutConsuming(const Error &E)
Like toString(), but does not consume the error.
Definition Error.cpp:81
Error joinErrors(Error E1, Error E2)
Concatenate errors.
Definition Error.h:442
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
Expected< T > handleExpected(Expected< T > ValOrErr, RecoveryFtor &&RecoveryPath, HandlerTs &&... Handlers)
Handle any errors (if present) in an Expected<T>, then try a recovery path.
Definition Error.h:1065
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition Format.h:129
Error handleErrorImpl(std::unique_ptr< ErrorInfoBase > Payload)
Definition Error.h:969
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ Other
Any other memory.
Definition ModRef.h:68
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
Definition Error.h:769
std::string join(IteratorT Begin, IteratorT End, StringRef Separator)
Joins the strings in the range [Begin, End), adding Separator between the elements.
Attribute unwrap(LLVMAttributeRef Attr)
Definition Attributes.h:397
Expected< T > errorOrToExpected(ErrorOr< T > &&EO)
Convert an ErrorOr<T> to an Expected<T>.
Definition Error.h:1268
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
typename detail::detector< void, Op, Args... >::value_t is_detected
Detects if a given trait holds for some set of arguments 'Args'.
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1917
LLVMAttributeRef wrap(Attribute Attr)
Definition Attributes.h:392
LLVM_ABI Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition Error.cpp:107
std::error_code errnoAsErrorCode()
Helper to get errno as an std::error_code.
Definition Error.h:1263
LogicalResult success(bool IsSuccess=true)
Utility function to generate a LogicalResult.
LLVM_ABI std::error_code errorToErrorCode(Error Err)
Helper for converting an ECError to a std::error_code.
Definition Error.cpp:113
void consumeError(Error Err)
Consume a Error without doing anything.
Definition Error.h:1106
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:870