Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:44:30

0001 //===- llvm/Support/Error.h - Recoverable error handling --------*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 //
0009 // This file defines an API used to report recoverable errors.
0010 //
0011 //===----------------------------------------------------------------------===//
0012 
0013 #ifndef LLVM_SUPPORT_ERROR_H
0014 #define LLVM_SUPPORT_ERROR_H
0015 
0016 #include "llvm-c/Error.h"
0017 #include "llvm/ADT/Twine.h"
0018 #include "llvm/Config/abi-breaking.h"
0019 #include "llvm/Support/AlignOf.h"
0020 #include "llvm/Support/Compiler.h"
0021 #include "llvm/Support/Debug.h"
0022 #include "llvm/Support/ErrorHandling.h"
0023 #include "llvm/Support/ErrorOr.h"
0024 #include "llvm/Support/Format.h"
0025 #include "llvm/Support/raw_ostream.h"
0026 #include <cassert>
0027 #include <cstdint>
0028 #include <cstdlib>
0029 #include <functional>
0030 #include <memory>
0031 #include <new>
0032 #include <optional>
0033 #include <string>
0034 #include <system_error>
0035 #include <type_traits>
0036 #include <utility>
0037 #include <vector>
0038 
0039 namespace llvm {
0040 
0041 class ErrorSuccess;
0042 
0043 /// Base class for error info classes. Do not extend this directly: Extend
0044 /// the ErrorInfo template subclass instead.
0045 class ErrorInfoBase {
0046 public:
0047   virtual ~ErrorInfoBase() = default;
0048 
0049   /// Print an error message to an output stream.
0050   virtual void log(raw_ostream &OS) const = 0;
0051 
0052   /// Return the error message as a string.
0053   virtual std::string message() const {
0054     std::string Msg;
0055     raw_string_ostream OS(Msg);
0056     log(OS);
0057     return Msg;
0058   }
0059 
0060   /// Convert this error to a std::error_code.
0061   ///
0062   /// This is a temporary crutch to enable interaction with code still
0063   /// using std::error_code. It will be removed in the future.
0064   virtual std::error_code convertToErrorCode() const = 0;
0065 
0066   // Returns the class ID for this type.
0067   static const void *classID() { return &ID; }
0068 
0069   // Returns the class ID for the dynamic type of this ErrorInfoBase instance.
0070   virtual const void *dynamicClassID() const = 0;
0071 
0072   // Check whether this instance is a subclass of the class identified by
0073   // ClassID.
0074   virtual bool isA(const void *const ClassID) const {
0075     return ClassID == classID();
0076   }
0077 
0078   // Check whether this instance is a subclass of ErrorInfoT.
0079   template <typename ErrorInfoT> bool isA() const {
0080     return isA(ErrorInfoT::classID());
0081   }
0082 
0083 private:
0084   virtual void anchor();
0085 
0086   static char ID;
0087 };
0088 
0089 /// Lightweight error class with error context and mandatory checking.
0090 ///
0091 /// Instances of this class wrap a ErrorInfoBase pointer. Failure states
0092 /// are represented by setting the pointer to a ErrorInfoBase subclass
0093 /// instance containing information describing the failure. Success is
0094 /// represented by a null pointer value.
0095 ///
0096 /// Instances of Error also contains a 'Checked' flag, which must be set
0097 /// before the destructor is called, otherwise the destructor will trigger a
0098 /// runtime error. This enforces at runtime the requirement that all Error
0099 /// instances be checked or returned to the caller.
0100 ///
0101 /// There are two ways to set the checked flag, depending on what state the
0102 /// Error instance is in. For Error instances indicating success, it
0103 /// is sufficient to invoke the boolean conversion operator. E.g.:
0104 ///
0105 ///   @code{.cpp}
0106 ///   Error foo(<...>);
0107 ///
0108 ///   if (auto E = foo(<...>))
0109 ///     return E; // <- Return E if it is in the error state.
0110 ///   // We have verified that E was in the success state. It can now be safely
0111 ///   // destroyed.
0112 ///   @endcode
0113 ///
0114 /// A success value *can not* be dropped. For example, just calling 'foo(<...>)'
0115 /// without testing the return value will raise a runtime error, even if foo
0116 /// returns success.
0117 ///
0118 /// For Error instances representing failure, you must use either the
0119 /// handleErrors or handleAllErrors function with a typed handler. E.g.:
0120 ///
0121 ///   @code{.cpp}
0122 ///   class MyErrorInfo : public ErrorInfo<MyErrorInfo> {
0123 ///     // Custom error info.
0124 ///   };
0125 ///
0126 ///   Error foo(<...>) { return make_error<MyErrorInfo>(...); }
0127 ///
0128 ///   auto E = foo(<...>); // <- foo returns failure with MyErrorInfo.
0129 ///   auto NewE =
0130 ///     handleErrors(std::move(E),
0131 ///       [](const MyErrorInfo &M) {
0132 ///         // Deal with the error.
0133 ///       },
0134 ///       [](std::unique_ptr<OtherError> M) -> Error {
0135 ///         if (canHandle(*M)) {
0136 ///           // handle error.
0137 ///           return Error::success();
0138 ///         }
0139 ///         // Couldn't handle this error instance. Pass it up the stack.
0140 ///         return Error(std::move(M));
0141 ///     });
0142 ///   // Note - The error passed to handleErrors will be marked as checked. If
0143 ///   // there is no matched handler, a new error with the same payload is
0144 ///   // created and returned.
0145 ///   // The handlers take the error checked by handleErrors as an argument,
0146 ///   // which can be used to retrieve more information. If a new error is
0147 ///   // created by a handler, it will be passed back to the caller of
0148 ///   // handleErrors and needs to be checked or return up to the stack.
0149 ///   // Otherwise, the passed-in error is considered consumed.
0150 ///   @endcode
0151 ///
0152 /// The handleAllErrors function is identical to handleErrors, except
0153 /// that it has a void return type, and requires all errors to be handled and
0154 /// no new errors be returned. It prevents errors (assuming they can all be
0155 /// handled) from having to be bubbled all the way to the top-level.
0156 ///
0157 /// *All* Error instances must be checked before destruction, even if
0158 /// they're moved-assigned or constructed from Success values that have already
0159 /// been checked. This enforces checking through all levels of the call stack.
0160 class [[nodiscard]] Error {
0161   // ErrorList needs to be able to yank ErrorInfoBase pointers out of Errors
0162   // to add to the error list. It can't rely on handleErrors for this, since
0163   // handleErrors does not support ErrorList handlers.
0164   friend class ErrorList;
0165 
0166   // handleErrors needs to be able to set the Checked flag.
0167   template <typename... HandlerTs>
0168   friend Error handleErrors(Error E, HandlerTs &&... Handlers);
0169   // visitErrors needs direct access to the payload.
0170   template <typename HandlerT>
0171   friend void visitErrors(const Error &E, HandlerT H);
0172 
0173   // Expected<T> needs to be able to steal the payload when constructed from an
0174   // error.
0175   template <typename T> friend class Expected;
0176 
0177   // wrap needs to be able to steal the payload.
0178   friend LLVMErrorRef wrap(Error);
0179 
0180 protected:
0181   /// Create a success value. Prefer using 'Error::success()' for readability
0182   Error() {
0183     setPtr(nullptr);
0184     setChecked(false);
0185   }
0186 
0187 public:
0188   /// Create a success value.
0189   static ErrorSuccess success();
0190 
0191   // Errors are not copy-constructable.
0192   Error(const Error &Other) = delete;
0193 
0194   /// Move-construct an error value. The newly constructed error is considered
0195   /// unchecked, even if the source error had been checked. The original error
0196   /// becomes a checked Success value, regardless of its original state.
0197   Error(Error &&Other) {
0198     setChecked(true);
0199     *this = std::move(Other);
0200   }
0201 
0202   /// Create an error value. Prefer using the 'make_error' function, but
0203   /// this constructor can be useful when "re-throwing" errors from handlers.
0204   Error(std::unique_ptr<ErrorInfoBase> Payload) {
0205     setPtr(Payload.release());
0206     setChecked(false);
0207   }
0208 
0209   // Errors are not copy-assignable.
0210   Error &operator=(const Error &Other) = delete;
0211 
0212   /// Move-assign an error value. The current error must represent success, you
0213   /// you cannot overwrite an unhandled error. The current error is then
0214   /// considered unchecked. The source error becomes a checked success value,
0215   /// regardless of its original state.
0216   Error &operator=(Error &&Other) {
0217     // Don't allow overwriting of unchecked values.
0218     assertIsChecked();
0219     setPtr(Other.getPtr());
0220 
0221     // This Error is unchecked, even if the source error was checked.
0222     setChecked(false);
0223 
0224     // Null out Other's payload and set its checked bit.
0225     Other.setPtr(nullptr);
0226     Other.setChecked(true);
0227 
0228     return *this;
0229   }
0230 
0231   /// Destroy a Error. Fails with a call to abort() if the error is
0232   /// unchecked.
0233   ~Error() {
0234     assertIsChecked();
0235     delete getPtr();
0236   }
0237 
0238   /// Bool conversion. Returns true if this Error is in a failure state,
0239   /// and false if it is in an accept state. If the error is in a Success state
0240   /// it will be considered checked.
0241   explicit operator bool() {
0242     setChecked(getPtr() == nullptr);
0243     return getPtr() != nullptr;
0244   }
0245 
0246   /// Check whether one error is a subclass of another.
0247   template <typename ErrT> bool isA() const {
0248     return getPtr() && getPtr()->isA(ErrT::classID());
0249   }
0250 
0251   /// Returns the dynamic class id of this error, or null if this is a success
0252   /// value.
0253   const void* dynamicClassID() const {
0254     if (!getPtr())
0255       return nullptr;
0256     return getPtr()->dynamicClassID();
0257   }
0258 
0259 private:
0260 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
0261   // assertIsChecked() happens very frequently, but under normal circumstances
0262   // is supposed to be a no-op.  So we want it to be inlined, but having a bunch
0263   // of debug prints can cause the function to be too large for inlining.  So
0264   // it's important that we define this function out of line so that it can't be
0265   // inlined.
0266   [[noreturn]] void fatalUncheckedError() const;
0267 #endif
0268 
0269   void assertIsChecked() {
0270 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
0271     if (LLVM_UNLIKELY(!getChecked() || getPtr()))
0272       fatalUncheckedError();
0273 #endif
0274   }
0275 
0276   ErrorInfoBase *getPtr() const {
0277 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
0278     return reinterpret_cast<ErrorInfoBase*>(
0279              reinterpret_cast<uintptr_t>(Payload) &
0280              ~static_cast<uintptr_t>(0x1));
0281 #else
0282     return Payload;
0283 #endif
0284   }
0285 
0286   void setPtr(ErrorInfoBase *EI) {
0287 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
0288     Payload = reinterpret_cast<ErrorInfoBase*>(
0289                 (reinterpret_cast<uintptr_t>(EI) &
0290                  ~static_cast<uintptr_t>(0x1)) |
0291                 (reinterpret_cast<uintptr_t>(Payload) & 0x1));
0292 #else
0293     Payload = EI;
0294 #endif
0295   }
0296 
0297   bool getChecked() const {
0298 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
0299     return (reinterpret_cast<uintptr_t>(Payload) & 0x1) == 0;
0300 #else
0301     return true;
0302 #endif
0303   }
0304 
0305   void setChecked(bool V) {
0306 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
0307     Payload = reinterpret_cast<ErrorInfoBase*>(
0308                 (reinterpret_cast<uintptr_t>(Payload) &
0309                   ~static_cast<uintptr_t>(0x1)) |
0310                   (V ? 0 : 1));
0311 #endif
0312   }
0313 
0314   std::unique_ptr<ErrorInfoBase> takePayload() {
0315     std::unique_ptr<ErrorInfoBase> Tmp(getPtr());
0316     setPtr(nullptr);
0317     setChecked(true);
0318     return Tmp;
0319   }
0320 
0321   friend raw_ostream &operator<<(raw_ostream &OS, const Error &E) {
0322     if (auto *P = E.getPtr())
0323       P->log(OS);
0324     else
0325       OS << "success";
0326     return OS;
0327   }
0328 
0329   ErrorInfoBase *Payload = nullptr;
0330 };
0331 
0332 /// Subclass of Error for the sole purpose of identifying the success path in
0333 /// the type system. This allows to catch invalid conversion to Expected<T> at
0334 /// compile time.
0335 class ErrorSuccess final : public Error {};
0336 
0337 inline ErrorSuccess Error::success() { return ErrorSuccess(); }
0338 
0339 /// Make a Error instance representing failure using the given error info
0340 /// type.
0341 template <typename ErrT, typename... ArgTs> Error make_error(ArgTs &&... Args) {
0342   return Error(std::make_unique<ErrT>(std::forward<ArgTs>(Args)...));
0343 }
0344 
0345 /// Base class for user error types. Users should declare their error types
0346 /// like:
0347 ///
0348 /// class MyError : public ErrorInfo<MyError> {
0349 ///   ....
0350 /// };
0351 ///
0352 /// This class provides an implementation of the ErrorInfoBase::kind
0353 /// method, which is used by the Error RTTI system.
0354 template <typename ThisErrT, typename ParentErrT = ErrorInfoBase>
0355 class ErrorInfo : public ParentErrT {
0356 public:
0357   using ParentErrT::ParentErrT; // inherit constructors
0358 
0359   static const void *classID() { return &ThisErrT::ID; }
0360 
0361   const void *dynamicClassID() const override { return &ThisErrT::ID; }
0362 
0363   bool isA(const void *const ClassID) const override {
0364     return ClassID == classID() || ParentErrT::isA(ClassID);
0365   }
0366 };
0367 
0368 /// Special ErrorInfo subclass representing a list of ErrorInfos.
0369 /// Instances of this class are constructed by joinError.
0370 class ErrorList final : public ErrorInfo<ErrorList> {
0371   // handleErrors needs to be able to iterate the payload list of an
0372   // ErrorList.
0373   template <typename... HandlerTs>
0374   friend Error handleErrors(Error E, HandlerTs &&... Handlers);
0375   // visitErrors needs to be able to iterate the payload list of an
0376   // ErrorList.
0377   template <typename HandlerT>
0378   friend void visitErrors(const Error &E, HandlerT H);
0379 
0380   // joinErrors is implemented in terms of join.
0381   friend Error joinErrors(Error, Error);
0382 
0383 public:
0384   void log(raw_ostream &OS) const override {
0385     OS << "Multiple errors:\n";
0386     for (const auto &ErrPayload : Payloads) {
0387       ErrPayload->log(OS);
0388       OS << "\n";
0389     }
0390   }
0391 
0392   std::error_code convertToErrorCode() const override;
0393 
0394   // Used by ErrorInfo::classID.
0395   static char ID;
0396 
0397 private:
0398   ErrorList(std::unique_ptr<ErrorInfoBase> Payload1,
0399             std::unique_ptr<ErrorInfoBase> Payload2) {
0400     assert(!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() &&
0401            "ErrorList constructor payloads should be singleton errors");
0402     Payloads.push_back(std::move(Payload1));
0403     Payloads.push_back(std::move(Payload2));
0404   }
0405 
0406   static Error join(Error E1, Error E2) {
0407     if (!E1)
0408       return E2;
0409     if (!E2)
0410       return E1;
0411     if (E1.isA<ErrorList>()) {
0412       auto &E1List = static_cast<ErrorList &>(*E1.getPtr());
0413       if (E2.isA<ErrorList>()) {
0414         auto E2Payload = E2.takePayload();
0415         auto &E2List = static_cast<ErrorList &>(*E2Payload);
0416         for (auto &Payload : E2List.Payloads)
0417           E1List.Payloads.push_back(std::move(Payload));
0418       } else
0419         E1List.Payloads.push_back(E2.takePayload());
0420 
0421       return E1;
0422     }
0423     if (E2.isA<ErrorList>()) {
0424       auto &E2List = static_cast<ErrorList &>(*E2.getPtr());
0425       E2List.Payloads.insert(E2List.Payloads.begin(), E1.takePayload());
0426       return E2;
0427     }
0428     return Error(std::unique_ptr<ErrorList>(
0429         new ErrorList(E1.takePayload(), E2.takePayload())));
0430   }
0431 
0432   std::vector<std::unique_ptr<ErrorInfoBase>> Payloads;
0433 };
0434 
0435 /// Concatenate errors. The resulting Error is unchecked, and contains the
0436 /// ErrorInfo(s), if any, contained in E1, followed by the
0437 /// ErrorInfo(s), if any, contained in E2.
0438 inline Error joinErrors(Error E1, Error E2) {
0439   return ErrorList::join(std::move(E1), std::move(E2));
0440 }
0441 
0442 /// Tagged union holding either a T or a Error.
0443 ///
0444 /// This class parallels ErrorOr, but replaces error_code with Error. Since
0445 /// Error cannot be copied, this class replaces getError() with
0446 /// takeError(). It also adds an bool errorIsA<ErrT>() method for testing the
0447 /// error class type.
0448 ///
0449 /// Example usage of 'Expected<T>' as a function return type:
0450 ///
0451 ///   @code{.cpp}
0452 ///     Expected<int> myDivide(int A, int B) {
0453 ///       if (B == 0) {
0454 ///         // return an Error
0455 ///         return createStringError(inconvertibleErrorCode(),
0456 ///                                  "B must not be zero!");
0457 ///       }
0458 ///       // return an integer
0459 ///       return A / B;
0460 ///     }
0461 ///   @endcode
0462 ///
0463 ///   Checking the results of to a function returning 'Expected<T>':
0464 ///   @code{.cpp}
0465 ///     if (auto E = Result.takeError()) {
0466 ///       // We must consume the error. Typically one of:
0467 ///       // - return the error to our caller
0468 ///       // - toString(), when logging
0469 ///       // - consumeError(), to silently swallow the error
0470 ///       // - handleErrors(), to distinguish error types
0471 ///       errs() << "Problem with division " << toString(std::move(E)) << "\n";
0472 ///       return;
0473 ///     }
0474 ///     // use the result
0475 ///     outs() << "The answer is " << *Result << "\n";
0476 ///   @endcode
0477 ///
0478 ///  For unit-testing a function returning an 'Expected<T>', see the
0479 ///  'EXPECT_THAT_EXPECTED' macros in llvm/Testing/Support/Error.h
0480 
0481 template <class T> class [[nodiscard]] Expected {
0482   template <class T1> friend class ExpectedAsOutParameter;
0483   template <class OtherT> friend class Expected;
0484 
0485   static constexpr bool isRef = std::is_reference_v<T>;
0486 
0487   using wrap = std::reference_wrapper<std::remove_reference_t<T>>;
0488 
0489   using error_type = std::unique_ptr<ErrorInfoBase>;
0490 
0491 public:
0492   using storage_type = std::conditional_t<isRef, wrap, T>;
0493   using value_type = T;
0494 
0495 private:
0496   using reference = std::remove_reference_t<T> &;
0497   using const_reference = const std::remove_reference_t<T> &;
0498   using pointer = std::remove_reference_t<T> *;
0499   using const_pointer = const std::remove_reference_t<T> *;
0500 
0501 public:
0502   /// Create an Expected<T> error value from the given Error.
0503   Expected(Error &&Err)
0504       : HasError(true)
0505 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
0506         // Expected is unchecked upon construction in Debug builds.
0507         , Unchecked(true)
0508 #endif
0509   {
0510     assert(Err && "Cannot create Expected<T> from Error success value.");
0511     new (getErrorStorage()) error_type(Err.takePayload());
0512   }
0513 
0514   /// Forbid to convert from Error::success() implicitly, this avoids having
0515   /// Expected<T> foo() { return Error::success(); } which compiles otherwise
0516   /// but triggers the assertion above.
0517   Expected(ErrorSuccess) = delete;
0518 
0519   /// Create an Expected<T> success value from the given OtherT value, which
0520   /// must be convertible to T.
0521   template <typename OtherT>
0522   Expected(OtherT &&Val,
0523            std::enable_if_t<std::is_convertible_v<OtherT, T>> * = nullptr)
0524       : HasError(false)
0525 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
0526         // Expected is unchecked upon construction in Debug builds.
0527         ,
0528         Unchecked(true)
0529 #endif
0530   {
0531     new (getStorage()) storage_type(std::forward<OtherT>(Val));
0532   }
0533 
0534   /// Move construct an Expected<T> value.
0535   Expected(Expected &&Other) { moveConstruct(std::move(Other)); }
0536 
0537   /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT
0538   /// must be convertible to T.
0539   template <class OtherT>
0540   Expected(Expected<OtherT> &&Other,
0541            std::enable_if_t<std::is_convertible_v<OtherT, T>> * = nullptr) {
0542     moveConstruct(std::move(Other));
0543   }
0544 
0545   /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT
0546   /// isn't convertible to T.
0547   template <class OtherT>
0548   explicit Expected(
0549       Expected<OtherT> &&Other,
0550       std::enable_if_t<!std::is_convertible_v<OtherT, T>> * = nullptr) {
0551     moveConstruct(std::move(Other));
0552   }
0553 
0554   /// Move-assign from another Expected<T>.
0555   Expected &operator=(Expected &&Other) {
0556     moveAssign(std::move(Other));
0557     return *this;
0558   }
0559 
0560   /// Destroy an Expected<T>.
0561   ~Expected() {
0562     assertIsChecked();
0563     if (!HasError)
0564       getStorage()->~storage_type();
0565     else
0566       getErrorStorage()->~error_type();
0567   }
0568 
0569   /// Return false if there is an error.
0570   explicit operator bool() {
0571 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
0572     Unchecked = HasError;
0573 #endif
0574     return !HasError;
0575   }
0576 
0577   /// Returns a reference to the stored T value.
0578   reference get() {
0579     assertIsChecked();
0580     return *getStorage();
0581   }
0582 
0583   /// Returns a const reference to the stored T value.
0584   const_reference get() const {
0585     assertIsChecked();
0586     return const_cast<Expected<T> *>(this)->get();
0587   }
0588 
0589   /// Returns \a takeError() after moving the held T (if any) into \p V.
0590   template <class OtherT>
0591   Error moveInto(
0592       OtherT &Value,
0593       std::enable_if_t<std::is_assignable_v<OtherT &, T &&>> * = nullptr) && {
0594     if (*this)
0595       Value = std::move(get());
0596     return takeError();
0597   }
0598 
0599   /// Check that this Expected<T> is an error of type ErrT.
0600   template <typename ErrT> bool errorIsA() const {
0601     return HasError && (*getErrorStorage())->template isA<ErrT>();
0602   }
0603 
0604   /// Take ownership of the stored error.
0605   /// After calling this the Expected<T> is in an indeterminate state that can
0606   /// only be safely destructed. No further calls (beside the destructor) should
0607   /// be made on the Expected<T> value.
0608   Error takeError() {
0609 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
0610     Unchecked = false;
0611 #endif
0612     return HasError ? Error(std::move(*getErrorStorage())) : Error::success();
0613   }
0614 
0615   /// Returns a pointer to the stored T value.
0616   pointer operator->() {
0617     assertIsChecked();
0618     return toPointer(getStorage());
0619   }
0620 
0621   /// Returns a const pointer to the stored T value.
0622   const_pointer operator->() const {
0623     assertIsChecked();
0624     return toPointer(getStorage());
0625   }
0626 
0627   /// Returns a reference to the stored T value.
0628   reference operator*() {
0629     assertIsChecked();
0630     return *getStorage();
0631   }
0632 
0633   /// Returns a const reference to the stored T value.
0634   const_reference operator*() const {
0635     assertIsChecked();
0636     return *getStorage();
0637   }
0638 
0639 private:
0640   template <class T1>
0641   static bool compareThisIfSameType(const T1 &a, const T1 &b) {
0642     return &a == &b;
0643   }
0644 
0645   template <class T1, class T2>
0646   static bool compareThisIfSameType(const T1 &, const T2 &) {
0647     return false;
0648   }
0649 
0650   template <class OtherT> void moveConstruct(Expected<OtherT> &&Other) {
0651     HasError = Other.HasError;
0652 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
0653     Unchecked = true;
0654     Other.Unchecked = false;
0655 #endif
0656 
0657     if (!HasError)
0658       new (getStorage()) storage_type(std::move(*Other.getStorage()));
0659     else
0660       new (getErrorStorage()) error_type(std::move(*Other.getErrorStorage()));
0661   }
0662 
0663   template <class OtherT> void moveAssign(Expected<OtherT> &&Other) {
0664     assertIsChecked();
0665 
0666     if (compareThisIfSameType(*this, Other))
0667       return;
0668 
0669     this->~Expected();
0670     new (this) Expected(std::move(Other));
0671   }
0672 
0673   pointer toPointer(pointer Val) { return Val; }
0674 
0675   const_pointer toPointer(const_pointer Val) const { return Val; }
0676 
0677   pointer toPointer(wrap *Val) { return &Val->get(); }
0678 
0679   const_pointer toPointer(const wrap *Val) const { return &Val->get(); }
0680 
0681   storage_type *getStorage() {
0682     assert(!HasError && "Cannot get value when an error exists!");
0683     return reinterpret_cast<storage_type *>(&TStorage);
0684   }
0685 
0686   const storage_type *getStorage() const {
0687     assert(!HasError && "Cannot get value when an error exists!");
0688     return reinterpret_cast<const storage_type *>(&TStorage);
0689   }
0690 
0691   error_type *getErrorStorage() {
0692     assert(HasError && "Cannot get error when a value exists!");
0693     return reinterpret_cast<error_type *>(&ErrorStorage);
0694   }
0695 
0696   const error_type *getErrorStorage() const {
0697     assert(HasError && "Cannot get error when a value exists!");
0698     return reinterpret_cast<const error_type *>(&ErrorStorage);
0699   }
0700 
0701   // Used by ExpectedAsOutParameter to reset the checked flag.
0702   void setUnchecked() {
0703 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
0704     Unchecked = true;
0705 #endif
0706   }
0707 
0708 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
0709   [[noreturn]] LLVM_ATTRIBUTE_NOINLINE void fatalUncheckedExpected() const {
0710     dbgs() << "Expected<T> must be checked before access or destruction.\n";
0711     if (HasError) {
0712       dbgs() << "Unchecked Expected<T> contained error:\n";
0713       (*getErrorStorage())->log(dbgs());
0714     } else
0715       dbgs() << "Expected<T> value was in success state. (Note: Expected<T> "
0716                 "values in success mode must still be checked prior to being "
0717                 "destroyed).\n";
0718     abort();
0719   }
0720 #endif
0721 
0722   void assertIsChecked() const {
0723 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
0724     if (LLVM_UNLIKELY(Unchecked))
0725       fatalUncheckedExpected();
0726 #endif
0727   }
0728 
0729   union {
0730     AlignedCharArrayUnion<storage_type> TStorage;
0731     AlignedCharArrayUnion<error_type> ErrorStorage;
0732   };
0733   bool HasError : 1;
0734 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
0735   bool Unchecked : 1;
0736 #endif
0737 };
0738 
0739 /// Report a serious error, calling any installed error handler. See
0740 /// ErrorHandling.h.
0741 [[noreturn]] void report_fatal_error(Error Err, bool gen_crash_diag = true);
0742 
0743 /// Report a fatal error if Err is a failure value.
0744 ///
0745 /// This function can be used to wrap calls to fallible functions ONLY when it
0746 /// is known that the Error will always be a success value. E.g.
0747 ///
0748 ///   @code{.cpp}
0749 ///   // foo only attempts the fallible operation if DoFallibleOperation is
0750 ///   // true. If DoFallibleOperation is false then foo always returns
0751 ///   // Error::success().
0752 ///   Error foo(bool DoFallibleOperation);
0753 ///
0754 ///   cantFail(foo(false));
0755 ///   @endcode
0756 inline void cantFail(Error Err, const char *Msg = nullptr) {
0757   if (Err) {
0758     if (!Msg)
0759       Msg = "Failure value returned from cantFail wrapped call";
0760 #ifndef NDEBUG
0761     std::string Str;
0762     raw_string_ostream OS(Str);
0763     OS << Msg << "\n" << Err;
0764     Msg = Str.c_str();
0765 #endif
0766     llvm_unreachable(Msg);
0767   }
0768 }
0769 
0770 /// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and
0771 /// returns the contained value.
0772 ///
0773 /// This function can be used to wrap calls to fallible functions ONLY when it
0774 /// is known that the Error will always be a success value. E.g.
0775 ///
0776 ///   @code{.cpp}
0777 ///   // foo only attempts the fallible operation if DoFallibleOperation is
0778 ///   // true. If DoFallibleOperation is false then foo always returns an int.
0779 ///   Expected<int> foo(bool DoFallibleOperation);
0780 ///
0781 ///   int X = cantFail(foo(false));
0782 ///   @endcode
0783 template <typename T>
0784 T cantFail(Expected<T> ValOrErr, const char *Msg = nullptr) {
0785   if (ValOrErr)
0786     return std::move(*ValOrErr);
0787   else {
0788     if (!Msg)
0789       Msg = "Failure value returned from cantFail wrapped call";
0790 #ifndef NDEBUG
0791     std::string Str;
0792     raw_string_ostream OS(Str);
0793     auto E = ValOrErr.takeError();
0794     OS << Msg << "\n" << E;
0795     Msg = Str.c_str();
0796 #endif
0797     llvm_unreachable(Msg);
0798   }
0799 }
0800 
0801 /// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and
0802 /// returns the contained reference.
0803 ///
0804 /// This function can be used to wrap calls to fallible functions ONLY when it
0805 /// is known that the Error will always be a success value. E.g.
0806 ///
0807 ///   @code{.cpp}
0808 ///   // foo only attempts the fallible operation if DoFallibleOperation is
0809 ///   // true. If DoFallibleOperation is false then foo always returns a Bar&.
0810 ///   Expected<Bar&> foo(bool DoFallibleOperation);
0811 ///
0812 ///   Bar &X = cantFail(foo(false));
0813 ///   @endcode
0814 template <typename T>
0815 T& cantFail(Expected<T&> ValOrErr, const char *Msg = nullptr) {
0816   if (ValOrErr)
0817     return *ValOrErr;
0818   else {
0819     if (!Msg)
0820       Msg = "Failure value returned from cantFail wrapped call";
0821 #ifndef NDEBUG
0822     std::string Str;
0823     raw_string_ostream OS(Str);
0824     auto E = ValOrErr.takeError();
0825     OS << Msg << "\n" << E;
0826     Msg = Str.c_str();
0827 #endif
0828     llvm_unreachable(Msg);
0829   }
0830 }
0831 
0832 /// Helper for testing applicability of, and applying, handlers for
0833 /// ErrorInfo types.
0834 template <typename HandlerT>
0835 class ErrorHandlerTraits
0836     : public ErrorHandlerTraits<
0837           decltype(&std::remove_reference_t<HandlerT>::operator())> {};
0838 
0839 // Specialization functions of the form 'Error (const ErrT&)'.
0840 template <typename ErrT> class ErrorHandlerTraits<Error (&)(ErrT &)> {
0841 public:
0842   static bool appliesTo(const ErrorInfoBase &E) {
0843     return E.template isA<ErrT>();
0844   }
0845 
0846   template <typename HandlerT>
0847   static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
0848     assert(appliesTo(*E) && "Applying incorrect handler");
0849     return H(static_cast<ErrT &>(*E));
0850   }
0851 };
0852 
0853 // Specialization functions of the form 'void (const ErrT&)'.
0854 template <typename ErrT> class ErrorHandlerTraits<void (&)(ErrT &)> {
0855 public:
0856   static bool appliesTo(const ErrorInfoBase &E) {
0857     return E.template isA<ErrT>();
0858   }
0859 
0860   template <typename HandlerT>
0861   static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
0862     assert(appliesTo(*E) && "Applying incorrect handler");
0863     H(static_cast<ErrT &>(*E));
0864     return Error::success();
0865   }
0866 };
0867 
0868 /// Specialization for functions of the form 'Error (std::unique_ptr<ErrT>)'.
0869 template <typename ErrT>
0870 class ErrorHandlerTraits<Error (&)(std::unique_ptr<ErrT>)> {
0871 public:
0872   static bool appliesTo(const ErrorInfoBase &E) {
0873     return E.template isA<ErrT>();
0874   }
0875 
0876   template <typename HandlerT>
0877   static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
0878     assert(appliesTo(*E) && "Applying incorrect handler");
0879     std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release()));
0880     return H(std::move(SubE));
0881   }
0882 };
0883 
0884 /// Specialization for functions of the form 'void (std::unique_ptr<ErrT>)'.
0885 template <typename ErrT>
0886 class ErrorHandlerTraits<void (&)(std::unique_ptr<ErrT>)> {
0887 public:
0888   static bool appliesTo(const ErrorInfoBase &E) {
0889     return E.template isA<ErrT>();
0890   }
0891 
0892   template <typename HandlerT>
0893   static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
0894     assert(appliesTo(*E) && "Applying incorrect handler");
0895     std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release()));
0896     H(std::move(SubE));
0897     return Error::success();
0898   }
0899 };
0900 
0901 // Specialization for member functions of the form 'RetT (const ErrT&)'.
0902 template <typename C, typename RetT, typename ErrT>
0903 class ErrorHandlerTraits<RetT (C::*)(ErrT &)>
0904     : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
0905 
0906 // Specialization for member functions of the form 'RetT (const ErrT&) const'.
0907 template <typename C, typename RetT, typename ErrT>
0908 class ErrorHandlerTraits<RetT (C::*)(ErrT &) const>
0909     : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
0910 
0911 // Specialization for member functions of the form 'RetT (const ErrT&)'.
0912 template <typename C, typename RetT, typename ErrT>
0913 class ErrorHandlerTraits<RetT (C::*)(const ErrT &)>
0914     : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
0915 
0916 // Specialization for member functions of the form 'RetT (const ErrT&) const'.
0917 template <typename C, typename RetT, typename ErrT>
0918 class ErrorHandlerTraits<RetT (C::*)(const ErrT &) const>
0919     : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
0920 
0921 /// Specialization for member functions of the form
0922 /// 'RetT (std::unique_ptr<ErrT>)'.
0923 template <typename C, typename RetT, typename ErrT>
0924 class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>)>
0925     : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {};
0926 
0927 /// Specialization for member functions of the form
0928 /// 'RetT (std::unique_ptr<ErrT>) const'.
0929 template <typename C, typename RetT, typename ErrT>
0930 class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>) const>
0931     : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {};
0932 
0933 inline Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload) {
0934   return Error(std::move(Payload));
0935 }
0936 
0937 template <typename HandlerT, typename... HandlerTs>
0938 Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload,
0939                       HandlerT &&Handler, HandlerTs &&... Handlers) {
0940   if (ErrorHandlerTraits<HandlerT>::appliesTo(*Payload))
0941     return ErrorHandlerTraits<HandlerT>::apply(std::forward<HandlerT>(Handler),
0942                                                std::move(Payload));
0943   return handleErrorImpl(std::move(Payload),
0944                          std::forward<HandlerTs>(Handlers)...);
0945 }
0946 
0947 /// Pass the ErrorInfo(s) contained in E to their respective handlers. Any
0948 /// unhandled errors (or Errors returned by handlers) are re-concatenated and
0949 /// returned.
0950 /// Because this function returns an error, its result must also be checked
0951 /// or returned. If you intend to handle all errors use handleAllErrors
0952 /// (which returns void, and will abort() on unhandled errors) instead.
0953 template <typename... HandlerTs>
0954 Error handleErrors(Error E, HandlerTs &&... Hs) {
0955   if (!E)
0956     return Error::success();
0957 
0958   std::unique_ptr<ErrorInfoBase> Payload = E.takePayload();
0959 
0960   if (Payload->isA<ErrorList>()) {
0961     ErrorList &List = static_cast<ErrorList &>(*Payload);
0962     Error R;
0963     for (auto &P : List.Payloads)
0964       R = ErrorList::join(
0965           std::move(R),
0966           handleErrorImpl(std::move(P), std::forward<HandlerTs>(Hs)...));
0967     return R;
0968   }
0969 
0970   return handleErrorImpl(std::move(Payload), std::forward<HandlerTs>(Hs)...);
0971 }
0972 
0973 /// Behaves the same as handleErrors, except that by contract all errors
0974 /// *must* be handled by the given handlers (i.e. there must be no remaining
0975 /// errors after running the handlers, or llvm_unreachable is called).
0976 template <typename... HandlerTs>
0977 void handleAllErrors(Error E, HandlerTs &&... Handlers) {
0978   cantFail(handleErrors(std::move(E), std::forward<HandlerTs>(Handlers)...));
0979 }
0980 
0981 /// Check that E is a non-error, then drop it.
0982 /// If E is an error, llvm_unreachable will be called.
0983 inline void handleAllErrors(Error E) {
0984   cantFail(std::move(E));
0985 }
0986 
0987 /// Visit all the ErrorInfo(s) contained in E by passing them to the respective
0988 /// handler, without consuming the error.
0989 template <typename HandlerT> void visitErrors(const Error &E, HandlerT H) {
0990   const ErrorInfoBase *Payload = E.getPtr();
0991   if (!Payload)
0992     return;
0993 
0994   if (Payload->isA<ErrorList>()) {
0995     const ErrorList &List = static_cast<const ErrorList &>(*Payload);
0996     for (const auto &P : List.Payloads)
0997       H(*P);
0998     return;
0999   }
1000 
1001   return H(*Payload);
1002 }
1003 
1004 /// Handle any errors (if present) in an Expected<T>, then try a recovery path.
1005 ///
1006 /// If the incoming value is a success value it is returned unmodified. If it
1007 /// is a failure value then it the contained error is passed to handleErrors.
1008 /// If handleErrors is able to handle the error then the RecoveryPath functor
1009 /// is called to supply the final result. If handleErrors is not able to
1010 /// handle all errors then the unhandled errors are returned.
1011 ///
1012 /// This utility enables the follow pattern:
1013 ///
1014 ///   @code{.cpp}
1015 ///   enum FooStrategy { Aggressive, Conservative };
1016 ///   Expected<Foo> foo(FooStrategy S);
1017 ///
1018 ///   auto ResultOrErr =
1019 ///     handleExpected(
1020 ///       foo(Aggressive),
1021 ///       []() { return foo(Conservative); },
1022 ///       [](AggressiveStrategyError&) {
1023 ///         // Implicitly conusme this - we'll recover by using a conservative
1024 ///         // strategy.
1025 ///       });
1026 ///
1027 ///   @endcode
1028 template <typename T, typename RecoveryFtor, typename... HandlerTs>
1029 Expected<T> handleExpected(Expected<T> ValOrErr, RecoveryFtor &&RecoveryPath,
1030                            HandlerTs &&... Handlers) {
1031   if (ValOrErr)
1032     return ValOrErr;
1033 
1034   if (auto Err = handleErrors(ValOrErr.takeError(),
1035                               std::forward<HandlerTs>(Handlers)...))
1036     return std::move(Err);
1037 
1038   return RecoveryPath();
1039 }
1040 
1041 /// Log all errors (if any) in E to OS. If there are any errors, ErrorBanner
1042 /// will be printed before the first one is logged. A newline will be printed
1043 /// after each error.
1044 ///
1045 /// This function is compatible with the helpers from Support/WithColor.h. You
1046 /// can pass any of them as the OS. Please consider using them instead of
1047 /// including 'error: ' in the ErrorBanner.
1048 ///
1049 /// This is useful in the base level of your program to allow clean termination
1050 /// (allowing clean deallocation of resources, etc.), while reporting error
1051 /// information to the user.
1052 void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner = {});
1053 
1054 /// Write all error messages (if any) in E to a string. The newline character
1055 /// is used to separate error messages.
1056 std::string toString(Error E);
1057 
1058 /// Like toString(), but does not consume the error. This can be used to print
1059 /// a warning while retaining the original error object.
1060 std::string toStringWithoutConsuming(const Error &E);
1061 
1062 /// Consume a Error without doing anything. This method should be used
1063 /// only where an error can be considered a reasonable and expected return
1064 /// value.
1065 ///
1066 /// Uses of this method are potentially indicative of design problems: If it's
1067 /// legitimate to do nothing while processing an "error", the error-producer
1068 /// might be more clearly refactored to return an std::optional<T>.
1069 inline void consumeError(Error Err) {
1070   handleAllErrors(std::move(Err), [](const ErrorInfoBase &) {});
1071 }
1072 
1073 /// Convert an Expected to an Optional without doing anything. This method
1074 /// should be used only where an error can be considered a reasonable and
1075 /// expected return value.
1076 ///
1077 /// Uses of this method are potentially indicative of problems: perhaps the
1078 /// error should be propagated further, or the error-producer should just
1079 /// return an Optional in the first place.
1080 template <typename T> std::optional<T> expectedToOptional(Expected<T> &&E) {
1081   if (E)
1082     return std::move(*E);
1083   consumeError(E.takeError());
1084   return std::nullopt;
1085 }
1086 
1087 template <typename T> std::optional<T> expectedToStdOptional(Expected<T> &&E) {
1088   if (E)
1089     return std::move(*E);
1090   consumeError(E.takeError());
1091   return std::nullopt;
1092 }
1093 
1094 /// Helper for converting an Error to a bool.
1095 ///
1096 /// This method returns true if Err is in an error state, or false if it is
1097 /// in a success state.  Puts Err in a checked state in both cases (unlike
1098 /// Error::operator bool(), which only does this for success states).
1099 inline bool errorToBool(Error Err) {
1100   bool IsError = static_cast<bool>(Err);
1101   if (IsError)
1102     consumeError(std::move(Err));
1103   return IsError;
1104 }
1105 
1106 /// Helper for Errors used as out-parameters.
1107 ///
1108 /// This helper is for use with the Error-as-out-parameter idiom, where an error
1109 /// is passed to a function or method by reference, rather than being returned.
1110 /// In such cases it is helpful to set the checked bit on entry to the function
1111 /// so that the error can be written to (unchecked Errors abort on assignment)
1112 /// and clear the checked bit on exit so that clients cannot accidentally forget
1113 /// to check the result. This helper performs these actions automatically using
1114 /// RAII:
1115 ///
1116 ///   @code{.cpp}
1117 ///   Result foo(Error &Err) {
1118 ///     ErrorAsOutParameter ErrAsOutParam(&Err); // 'Checked' flag set
1119 ///     // <body of foo>
1120 ///     // <- 'Checked' flag auto-cleared when ErrAsOutParam is destructed.
1121 ///   }
1122 ///   @endcode
1123 ///
1124 /// ErrorAsOutParameter takes an Error* rather than Error& so that it can be
1125 /// used with optional Errors (Error pointers that are allowed to be null). If
1126 /// ErrorAsOutParameter took an Error reference, an instance would have to be
1127 /// created inside every condition that verified that Error was non-null. By
1128 /// taking an Error pointer we can just create one instance at the top of the
1129 /// function.
1130 class ErrorAsOutParameter {
1131 public:
1132 
1133   ErrorAsOutParameter(Error *Err) : Err(Err) {
1134     // Raise the checked bit if Err is success.
1135     if (Err)
1136       (void)!!*Err;
1137   }
1138 
1139   ErrorAsOutParameter(Error &Err) : Err(&Err) {
1140     (void)!!Err;
1141   }
1142 
1143   ~ErrorAsOutParameter() {
1144     // Clear the checked bit.
1145     if (Err && !*Err)
1146       *Err = Error::success();
1147   }
1148 
1149 private:
1150   Error *Err;
1151 };
1152 
1153 /// Helper for Expected<T>s used as out-parameters.
1154 ///
1155 /// See ErrorAsOutParameter.
1156 template <typename T>
1157 class ExpectedAsOutParameter {
1158 public:
1159   ExpectedAsOutParameter(Expected<T> *ValOrErr)
1160     : ValOrErr(ValOrErr) {
1161     if (ValOrErr)
1162       (void)!!*ValOrErr;
1163   }
1164 
1165   ~ExpectedAsOutParameter() {
1166     if (ValOrErr)
1167       ValOrErr->setUnchecked();
1168   }
1169 
1170 private:
1171   Expected<T> *ValOrErr;
1172 };
1173 
1174 /// This class wraps a std::error_code in a Error.
1175 ///
1176 /// This is useful if you're writing an interface that returns a Error
1177 /// (or Expected) and you want to call code that still returns
1178 /// std::error_codes.
1179 class ECError : public ErrorInfo<ECError> {
1180   friend Error errorCodeToError(std::error_code);
1181 
1182   void anchor() override;
1183 
1184 public:
1185   void setErrorCode(std::error_code EC) { this->EC = EC; }
1186   std::error_code convertToErrorCode() const override { return EC; }
1187   void log(raw_ostream &OS) const override { OS << EC.message(); }
1188 
1189   // Used by ErrorInfo::classID.
1190   static char ID;
1191 
1192 protected:
1193   ECError() = default;
1194   ECError(std::error_code EC) : EC(EC) {}
1195 
1196   std::error_code EC;
1197 };
1198 
1199 /// The value returned by this function can be returned from convertToErrorCode
1200 /// for Error values where no sensible translation to std::error_code exists.
1201 /// It should only be used in this situation, and should never be used where a
1202 /// sensible conversion to std::error_code is available, as attempts to convert
1203 /// to/from this error will result in a fatal error. (i.e. it is a programmatic
1204 /// error to try to convert such a value).
1205 std::error_code inconvertibleErrorCode();
1206 
1207 /// Helper for converting an std::error_code to a Error.
1208 Error errorCodeToError(std::error_code EC);
1209 
1210 /// Helper for converting an ECError to a std::error_code.
1211 ///
1212 /// This method requires that Err be Error() or an ECError, otherwise it
1213 /// will trigger a call to abort().
1214 std::error_code errorToErrorCode(Error Err);
1215 
1216 /// Helper to get errno as an std::error_code.
1217 ///
1218 /// errno should always be represented using the generic category as that's what
1219 /// both libc++ and libstdc++ do. On POSIX systems you can also represent them
1220 /// using the system category, however this makes them compare differently for
1221 /// values outside of those used by `std::errc` if one is generic and the other
1222 /// is system.
1223 ///
1224 /// See the libc++ and libstdc++ implementations of `default_error_condition` on
1225 /// the system category for more details on what the difference is.
1226 inline std::error_code errnoAsErrorCode() {
1227   return std::error_code(errno, std::generic_category());
1228 }
1229 
1230 /// Convert an ErrorOr<T> to an Expected<T>.
1231 template <typename T> Expected<T> errorOrToExpected(ErrorOr<T> &&EO) {
1232   if (auto EC = EO.getError())
1233     return errorCodeToError(EC);
1234   return std::move(*EO);
1235 }
1236 
1237 /// Convert an Expected<T> to an ErrorOr<T>.
1238 template <typename T> ErrorOr<T> expectedToErrorOr(Expected<T> &&E) {
1239   if (auto Err = E.takeError())
1240     return errorToErrorCode(std::move(Err));
1241   return std::move(*E);
1242 }
1243 
1244 /// This class wraps a string in an Error.
1245 ///
1246 /// StringError is useful in cases where the client is not expected to be able
1247 /// to consume the specific error message programmatically (for example, if the
1248 /// error message is to be presented to the user).
1249 ///
1250 /// StringError can also be used when additional information is to be printed
1251 /// along with a error_code message. Depending on the constructor called, this
1252 /// class can either display:
1253 ///    1. the error_code message (ECError behavior)
1254 ///    2. a string
1255 ///    3. the error_code message and a string
1256 ///
1257 /// These behaviors are useful when subtyping is required; for example, when a
1258 /// specific library needs an explicit error type. In the example below,
1259 /// PDBError is derived from StringError:
1260 ///
1261 ///   @code{.cpp}
1262 ///   Expected<int> foo() {
1263 ///      return llvm::make_error<PDBError>(pdb_error_code::dia_failed_loading,
1264 ///                                        "Additional information");
1265 ///   }
1266 ///   @endcode
1267 ///
1268 class StringError : public ErrorInfo<StringError> {
1269 public:
1270   static char ID;
1271 
1272   StringError(std::string &&S, std::error_code EC, bool PrintMsgOnly);
1273   /// Prints EC + S and converts to EC.
1274   StringError(std::error_code EC, const Twine &S = Twine());
1275   /// Prints S and converts to EC.
1276   StringError(const Twine &S, std::error_code EC);
1277 
1278   void log(raw_ostream &OS) const override;
1279   std::error_code convertToErrorCode() const override;
1280 
1281   const std::string &getMessage() const { return Msg; }
1282 
1283 private:
1284   std::string Msg;
1285   std::error_code EC;
1286   const bool PrintMsgOnly = false;
1287 };
1288 
1289 /// Create formatted StringError object.
1290 template <typename... Ts>
1291 inline Error createStringError(std::error_code EC, char const *Fmt,
1292                                const Ts &... Vals) {
1293   std::string Buffer;
1294   raw_string_ostream(Buffer) << format(Fmt, Vals...);
1295   return make_error<StringError>(Buffer, EC);
1296 }
1297 
1298 Error createStringError(std::string &&Msg, std::error_code EC);
1299 
1300 inline Error createStringError(std::error_code EC, const char *S) {
1301   return createStringError(std::string(S), EC);
1302 }
1303 
1304 inline Error createStringError(std::error_code EC, const Twine &S) {
1305   return createStringError(S.str(), EC);
1306 }
1307 
1308 /// Create a StringError with an inconvertible error code.
1309 inline Error createStringError(const Twine &S) {
1310   return createStringError(llvm::inconvertibleErrorCode(), S);
1311 }
1312 
1313 template <typename... Ts>
1314 inline Error createStringError(char const *Fmt, const Ts &...Vals) {
1315   return createStringError(llvm::inconvertibleErrorCode(), Fmt, Vals...);
1316 }
1317 
1318 template <typename... Ts>
1319 inline Error createStringError(std::errc EC, char const *Fmt,
1320                                const Ts &... Vals) {
1321   return createStringError(std::make_error_code(EC), Fmt, Vals...);
1322 }
1323 
1324 /// This class wraps a filename and another Error.
1325 ///
1326 /// In some cases, an error needs to live along a 'source' name, in order to
1327 /// show more detailed information to the user.
1328 class FileError final : public ErrorInfo<FileError> {
1329 
1330   friend Error createFileError(const Twine &, Error);
1331   friend Error createFileError(const Twine &, size_t, Error);
1332 
1333 public:
1334   void log(raw_ostream &OS) const override {
1335     assert(Err && "Trying to log after takeError().");
1336     OS << "'" << FileName << "': ";
1337     if (Line)
1338       OS << "line " << *Line << ": ";
1339     Err->log(OS);
1340   }
1341 
1342   std::string messageWithoutFileInfo() const {
1343     std::string Msg;
1344     raw_string_ostream OS(Msg);
1345     Err->log(OS);
1346     return Msg;
1347   }
1348 
1349   StringRef getFileName() const { return FileName; }
1350 
1351   Error takeError() { return Error(std::move(Err)); }
1352 
1353   std::error_code convertToErrorCode() const override;
1354 
1355   // Used by ErrorInfo::classID.
1356   static char ID;
1357 
1358 private:
1359   FileError(const Twine &F, std::optional<size_t> LineNum,
1360             std::unique_ptr<ErrorInfoBase> E) {
1361     assert(E && "Cannot create FileError from Error success value.");
1362     FileName = F.str();
1363     Err = std::move(E);
1364     Line = std::move(LineNum);
1365   }
1366 
1367   static Error build(const Twine &F, std::optional<size_t> Line, Error E) {
1368     std::unique_ptr<ErrorInfoBase> Payload;
1369     handleAllErrors(std::move(E),
1370                     [&](std::unique_ptr<ErrorInfoBase> EIB) -> Error {
1371                       Payload = std::move(EIB);
1372                       return Error::success();
1373                     });
1374     return Error(
1375         std::unique_ptr<FileError>(new FileError(F, Line, std::move(Payload))));
1376   }
1377 
1378   std::string FileName;
1379   std::optional<size_t> Line;
1380   std::unique_ptr<ErrorInfoBase> Err;
1381 };
1382 
1383 /// Concatenate a source file path and/or name with an Error. The resulting
1384 /// Error is unchecked.
1385 inline Error createFileError(const Twine &F, Error E) {
1386   return FileError::build(F, std::optional<size_t>(), std::move(E));
1387 }
1388 
1389 /// Concatenate a source file path and/or name with line number and an Error.
1390 /// The resulting Error is unchecked.
1391 inline Error createFileError(const Twine &F, size_t Line, Error E) {
1392   return FileError::build(F, std::optional<size_t>(Line), std::move(E));
1393 }
1394 
1395 /// Concatenate a source file path and/or name with a std::error_code 
1396 /// to form an Error object.
1397 inline Error createFileError(const Twine &F, std::error_code EC) {
1398   return createFileError(F, errorCodeToError(EC));
1399 }
1400 
1401 /// Concatenate a source file path and/or name with line number and
1402 /// std::error_code to form an Error object.
1403 inline Error createFileError(const Twine &F, size_t Line, std::error_code EC) {
1404   return createFileError(F, Line, errorCodeToError(EC));
1405 }
1406 
1407 /// Create a StringError with the specified error code and prepend the file path
1408 /// to it.
1409 inline Error createFileError(const Twine &F, std::error_code EC,
1410                              const Twine &S) {
1411   Error E = createStringError(EC, S);
1412   return createFileError(F, std::move(E));
1413 }
1414 
1415 /// Create a StringError with the specified error code and prepend the file path
1416 /// to it.
1417 template <typename... Ts>
1418 inline Error createFileError(const Twine &F, std::error_code EC,
1419                              char const *Fmt, const Ts &...Vals) {
1420   Error E = createStringError(EC, Fmt, Vals...);
1421   return createFileError(F, std::move(E));
1422 }
1423 
1424 Error createFileError(const Twine &F, ErrorSuccess) = delete;
1425 
1426 /// Helper for check-and-exit error handling.
1427 ///
1428 /// For tool use only. NOT FOR USE IN LIBRARY CODE.
1429 ///
1430 class ExitOnError {
1431 public:
1432   /// Create an error on exit helper.
1433   ExitOnError(std::string Banner = "", int DefaultErrorExitCode = 1)
1434       : Banner(std::move(Banner)),
1435         GetExitCode([=](const Error &) { return DefaultErrorExitCode; }) {}
1436 
1437   /// Set the banner string for any errors caught by operator().
1438   void setBanner(std::string Banner) { this->Banner = std::move(Banner); }
1439 
1440   /// Set the exit-code mapper function.
1441   void setExitCodeMapper(std::function<int(const Error &)> GetExitCode) {
1442     this->GetExitCode = std::move(GetExitCode);
1443   }
1444 
1445   /// Check Err. If it's in a failure state log the error(s) and exit.
1446   void operator()(Error Err) const { checkError(std::move(Err)); }
1447 
1448   /// Check E. If it's in a success state then return the contained value. If
1449   /// it's in a failure state log the error(s) and exit.
1450   template <typename T> T operator()(Expected<T> &&E) const {
1451     checkError(E.takeError());
1452     return std::move(*E);
1453   }
1454 
1455   /// Check E. If it's in a success state then return the contained reference. If
1456   /// it's in a failure state log the error(s) and exit.
1457   template <typename T> T& operator()(Expected<T&> &&E) const {
1458     checkError(E.takeError());
1459     return *E;
1460   }
1461 
1462 private:
1463   void checkError(Error Err) const {
1464     if (Err) {
1465       int ExitCode = GetExitCode(Err);
1466       logAllUnhandledErrors(std::move(Err), errs(), Banner);
1467       exit(ExitCode);
1468     }
1469   }
1470 
1471   std::string Banner;
1472   std::function<int(const Error &)> GetExitCode;
1473 };
1474 
1475 /// Conversion from Error to LLVMErrorRef for C error bindings.
1476 inline LLVMErrorRef wrap(Error Err) {
1477   return reinterpret_cast<LLVMErrorRef>(Err.takePayload().release());
1478 }
1479 
1480 /// Conversion from LLVMErrorRef to Error for C error bindings.
1481 inline Error unwrap(LLVMErrorRef ErrRef) {
1482   return Error(std::unique_ptr<ErrorInfoBase>(
1483       reinterpret_cast<ErrorInfoBase *>(ErrRef)));
1484 }
1485 
1486 } // end namespace llvm
1487 
1488 #endif // LLVM_SUPPORT_ERROR_H