LCOV - code coverage report
Current view: top level - include/llvm/Support - Error.h (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 134 151 88.7 %
Date: 2018-07-13 00:08:38 Functions: 564 888 63.5 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //===- llvm/Support/Error.h - Recoverable error handling --------*- C++ -*-===//
       2             : //
       3             : //                     The LLVM Compiler Infrastructure
       4             : //
       5             : // This file is distributed under the University of Illinois Open Source
       6             : // License. See LICENSE.TXT for details.
       7             : //
       8             : //===----------------------------------------------------------------------===//
       9             : //
      10             : // This file defines an API used to report recoverable errors.
      11             : //
      12             : //===----------------------------------------------------------------------===//
      13             : 
      14             : #ifndef LLVM_SUPPORT_ERROR_H
      15             : #define LLVM_SUPPORT_ERROR_H
      16             : 
      17             : #include "llvm/ADT/SmallVector.h"
      18             : #include "llvm/ADT/STLExtras.h"
      19             : #include "llvm/ADT/StringExtras.h"
      20             : #include "llvm/ADT/Twine.h"
      21             : #include "llvm/Config/abi-breaking.h"
      22             : #include "llvm/Support/AlignOf.h"
      23             : #include "llvm/Support/Compiler.h"
      24             : #include "llvm/Support/Debug.h"
      25             : #include "llvm/Support/ErrorHandling.h"
      26             : #include "llvm/Support/ErrorOr.h"
      27             : #include "llvm/Support/raw_ostream.h"
      28             : #include <algorithm>
      29             : #include <cassert>
      30             : #include <cstdint>
      31             : #include <cstdlib>
      32             : #include <functional>
      33             : #include <memory>
      34             : #include <new>
      35             : #include <string>
      36             : #include <system_error>
      37             : #include <type_traits>
      38             : #include <utility>
      39             : #include <vector>
      40             : 
      41             : namespace llvm {
      42             : 
      43             : class ErrorSuccess;
      44             : 
      45             : /// Base class for error info classes. Do not extend this directly: Extend
      46             : /// the ErrorInfo template subclass instead.
      47        1286 : class ErrorInfoBase {
      48             : public:
      49             :   virtual ~ErrorInfoBase() = default;
      50             : 
      51             :   /// Print an error message to an output stream.
      52             :   virtual void log(raw_ostream &OS) const = 0;
      53             : 
      54             :   /// Return the error message as a string.
      55        2443 :   virtual std::string message() const {
      56             :     std::string Msg;
      57        2443 :     raw_string_ostream OS(Msg);
      58        2443 :     log(OS);
      59        2443 :     return OS.str();
      60             :   }
      61             : 
      62             :   /// Convert this error to a std::error_code.
      63             :   ///
      64             :   /// This is a temporary crutch to enable interaction with code still
      65             :   /// using std::error_code. It will be removed in the future.
      66             :   virtual std::error_code convertToErrorCode() const = 0;
      67             : 
      68             :   // Returns the class ID for this type.
      69             :   static const void *classID() { return &ID; }
      70             : 
      71             :   // Returns the class ID for the dynamic type of this ErrorInfoBase instance.
      72             :   virtual const void *dynamicClassID() const = 0;
      73             : 
      74             :   // Check whether this instance is a subclass of the class identified by
      75             :   // ClassID.
      76           0 :   virtual bool isA(const void *const ClassID) const {
      77           0 :     return ClassID == classID();
      78             :   }
      79             : 
      80             :   // Check whether this instance is a subclass of ErrorInfoT.
      81             :   template <typename ErrorInfoT> bool isA() const {
      82       69222 :     return isA(ErrorInfoT::classID());
      83             :   }
      84             : 
      85             : private:
      86             :   virtual void anchor();
      87             : 
      88             :   static char ID;
      89             : };
      90             : 
      91             : /// Lightweight error class with error context and mandatory checking.
      92             : ///
      93             : /// Instances of this class wrap a ErrorInfoBase pointer. Failure states
      94             : /// are represented by setting the pointer to a ErrorInfoBase subclass
      95             : /// instance containing information describing the failure. Success is
      96             : /// represented by a null pointer value.
      97             : ///
      98             : /// Instances of Error also contains a 'Checked' flag, which must be set
      99             : /// before the destructor is called, otherwise the destructor will trigger a
     100             : /// runtime error. This enforces at runtime the requirement that all Error
     101             : /// instances be checked or returned to the caller.
     102             : ///
     103             : /// There are two ways to set the checked flag, depending on what state the
     104             : /// Error instance is in. For Error instances indicating success, it
     105             : /// is sufficient to invoke the boolean conversion operator. E.g.:
     106             : ///
     107             : ///   @code{.cpp}
     108             : ///   Error foo(<...>);
     109             : ///
     110             : ///   if (auto E = foo(<...>))
     111             : ///     return E; // <- Return E if it is in the error state.
     112             : ///   // We have verified that E was in the success state. It can now be safely
     113             : ///   // destroyed.
     114             : ///   @endcode
     115             : ///
     116             : /// A success value *can not* be dropped. For example, just calling 'foo(<...>)'
     117             : /// without testing the return value will raise a runtime error, even if foo
     118             : /// returns success.
     119             : ///
     120             : /// For Error instances representing failure, you must use either the
     121             : /// handleErrors or handleAllErrors function with a typed handler. E.g.:
     122             : ///
     123             : ///   @code{.cpp}
     124             : ///   class MyErrorInfo : public ErrorInfo<MyErrorInfo> {
     125             : ///     // Custom error info.
     126             : ///   };
     127             : ///
     128             : ///   Error foo(<...>) { return make_error<MyErrorInfo>(...); }
     129             : ///
     130             : ///   auto E = foo(<...>); // <- foo returns failure with MyErrorInfo.
     131             : ///   auto NewE =
     132             : ///     handleErrors(E,
     133             : ///       [](const MyErrorInfo &M) {
     134             : ///         // Deal with the error.
     135             : ///       },
     136             : ///       [](std::unique_ptr<OtherError> M) -> Error {
     137             : ///         if (canHandle(*M)) {
     138             : ///           // handle error.
     139             : ///           return Error::success();
     140             : ///         }
     141             : ///         // Couldn't handle this error instance. Pass it up the stack.
     142             : ///         return Error(std::move(M));
     143             : ///       );
     144             : ///   // Note - we must check or return NewE in case any of the handlers
     145             : ///   // returned a new error.
     146             : ///   @endcode
     147             : ///
     148             : /// The handleAllErrors function is identical to handleErrors, except
     149             : /// that it has a void return type, and requires all errors to be handled and
     150             : /// no new errors be returned. It prevents errors (assuming they can all be
     151             : /// handled) from having to be bubbled all the way to the top-level.
     152             : ///
     153             : /// *All* Error instances must be checked before destruction, even if
     154             : /// they're moved-assigned or constructed from Success values that have already
     155             : /// been checked. This enforces checking through all levels of the call stack.
     156             : class LLVM_NODISCARD Error {
     157             :   // ErrorList needs to be able to yank ErrorInfoBase pointers out of this
     158             :   // class to add to the error list.
     159             :   friend class ErrorList;
     160             : 
     161             :   // handleErrors needs to be able to set the Checked flag.
     162             :   template <typename... HandlerTs>
     163             :   friend Error handleErrors(Error E, HandlerTs &&... Handlers);
     164             : 
     165             :   // Expected<T> needs to be able to steal the payload when constructed from an
     166             :   // error.
     167             :   template <typename T> friend class Expected;
     168             : 
     169             : protected:
     170             :   /// Create a success value. Prefer using 'Error::success()' for readability
     171             :   Error() {
     172             :     setPtr(nullptr);
     173             :     setChecked(false);
     174             :   }
     175             : 
     176             : public:
     177             :   /// Create a success value.
     178             :   static ErrorSuccess success();
     179             : 
     180             :   // Errors are not copy-constructable.
     181             :   Error(const Error &Other) = delete;
     182             : 
     183             :   /// Move-construct an error value. The newly constructed error is considered
     184             :   /// unchecked, even if the source error had been checked. The original error
     185             :   /// becomes a checked Success value, regardless of its original state.
     186      369867 :   Error(Error &&Other) {
     187             :     setChecked(true);
     188             :     *this = std::move(Other);
     189             :   }
     190             : 
     191             :   /// Create an error value. Prefer using the 'make_error' function, but
     192             :   /// this constructor can be useful when "re-throwing" errors from handlers.
     193          24 :   Error(std::unique_ptr<ErrorInfoBase> Payload) {
     194             :     setPtr(Payload.release());
     195             :     setChecked(false);
     196             :   }
     197             : 
     198             :   // Errors are not copy-assignable.
     199             :   Error &operator=(const Error &Other) = delete;
     200             : 
     201             :   /// Move-assign an error value. The current error must represent success, you
     202             :   /// you cannot overwrite an unhandled error. The current error is then
     203             :   /// considered unchecked. The source error becomes a checked success value,
     204             :   /// regardless of its original state.
     205             :   Error &operator=(Error &&Other) {
     206             :     // Don't allow overwriting of unchecked values.
     207             :     assertIsChecked();
     208             :     setPtr(Other.getPtr());
     209             : 
     210             :     // This Error is unchecked, even if the source error was checked.
     211             :     setChecked(false);
     212             : 
     213             :     // Null out Other's payload and set its checked bit.
     214             :     Other.setPtr(nullptr);
     215             :     Other.setChecked(true);
     216             : 
     217             :     return *this;
     218             :   }
     219             : 
     220             :   /// Destroy a Error. Fails with a call to abort() if the error is
     221             :   /// unchecked.
     222       11735 :   ~Error() {
     223             :     assertIsChecked();
     224      916854 :     delete getPtr();
     225             :   }
     226             : 
     227             :   /// Bool conversion. Returns true if this Error is in a failure state,
     228             :   /// and false if it is in an accept state. If the error is in a Success state
     229             :   /// it will be considered checked.
     230             :   explicit operator bool() {
     231             :     setChecked(getPtr() == nullptr);
     232          39 :     return getPtr() != nullptr;
     233             :   }
     234             : 
     235             :   /// Check whether one error is a subclass of another.
     236             :   template <typename ErrT> bool isA() const {
     237         195 :     return getPtr() && getPtr()->isA(ErrT::classID());
     238             :   }
     239             : 
     240             :   /// Returns the dynamic class id of this error, or null if this is a success
     241             :   /// value.
     242             :   const void* dynamicClassID() const {
     243             :     if (!getPtr())
     244             :       return nullptr;
     245             :     return getPtr()->dynamicClassID();
     246             :   }
     247             : 
     248             : private:
     249             : #if LLVM_ENABLE_ABI_BREAKING_CHECKS
     250             :   // assertIsChecked() happens very frequently, but under normal circumstances
     251             :   // is supposed to be a no-op.  So we want it to be inlined, but having a bunch
     252             :   // of debug prints can cause the function to be too large for inlining.  So
     253             :   // it's important that we define this function out of line so that it can't be
     254             :   // inlined.
     255             :   LLVM_ATTRIBUTE_NORETURN
     256             :   void fatalUncheckedError() const;
     257             : #endif
     258             : 
     259             :   void assertIsChecked() {
     260             : #if LLVM_ENABLE_ABI_BREAKING_CHECKS
     261             :     if (LLVM_UNLIKELY(!getChecked() || getPtr()))
     262             :       fatalUncheckedError();
     263             : #endif
     264             :   }
     265             : 
     266             :   ErrorInfoBase *getPtr() const {
     267             :     return reinterpret_cast<ErrorInfoBase*>(
     268     8544513 :              reinterpret_cast<uintptr_t>(Payload) &
     269     1011252 :              ~static_cast<uintptr_t>(0x1));
     270             :   }
     271             : 
     272             :   void setPtr(ErrorInfoBase *EI) {
     273             : #if LLVM_ENABLE_ABI_BREAKING_CHECKS
     274             :     Payload = reinterpret_cast<ErrorInfoBase*>(
     275             :                 (reinterpret_cast<uintptr_t>(EI) &
     276             :                  ~static_cast<uintptr_t>(0x1)) |
     277             :                 (reinterpret_cast<uintptr_t>(Payload) & 0x1));
     278             : #else
     279      371593 :     Payload = EI;
     280             : #endif
     281             :   }
     282             : 
     283             :   bool getChecked() const {
     284             : #if LLVM_ENABLE_ABI_BREAKING_CHECKS
     285             :     return (reinterpret_cast<uintptr_t>(Payload) & 0x1) == 0;
     286             : #else
     287             :     return true;
     288             : #endif
     289             :   }
     290             : 
     291             :   void setChecked(bool V) {
     292     6364543 :     Payload = reinterpret_cast<ErrorInfoBase*>(
     293       94270 :                 (reinterpret_cast<uintptr_t>(Payload) &
     294     4121149 :                   ~static_cast<uintptr_t>(0x1)) |
     295     3652239 :                   (V ? 0 : 1));
     296             :   }
     297             : 
     298             :   std::unique_ptr<ErrorInfoBase> takePayload() {
     299             :     std::unique_ptr<ErrorInfoBase> Tmp(getPtr());
     300             :     setPtr(nullptr);
     301             :     setChecked(true);
     302             :     return Tmp;
     303             :   }
     304             : 
     305           2 :   friend raw_ostream &operator<<(raw_ostream &OS, const Error &E) {
     306           2 :     if (auto P = E.getPtr())
     307           1 :       P->log(OS);
     308             :     else
     309           1 :       OS << "success";
     310           2 :     return OS;
     311             :   }
     312             : 
     313             :   ErrorInfoBase *Payload = nullptr;
     314             : };
     315             : 
     316             : /// Subclass of Error for the sole purpose of identifying the success path in
     317             : /// the type system. This allows to catch invalid conversion to Expected<T> at
     318             : /// compile time.
     319             : class ErrorSuccess : public Error {};
     320             : 
     321             : inline ErrorSuccess Error::success() { return ErrorSuccess(); }
     322             : 
     323             : /// Make a Error instance representing failure using the given error info
     324             : /// type.
     325         280 : template <typename ErrT, typename... ArgTs> Error make_error(ArgTs &&... Args) {
     326       63489 :   return Error(llvm::make_unique<ErrT>(std::forward<ArgTs>(Args)...));
     327             : }
     328             : 
     329             : /// Base class for user error types. Users should declare their error types
     330             : /// like:
     331             : ///
     332             : /// class MyError : public ErrorInfo<MyError> {
     333             : ///   ....
     334             : /// };
     335             : ///
     336             : /// This class provides an implementation of the ErrorInfoBase::kind
     337             : /// method, which is used by the Error RTTI system.
     338             : template <typename ThisErrT, typename ParentErrT = ErrorInfoBase>
     339         730 : class ErrorInfo : public ParentErrT {
     340             : public:
     341             :   static const void *classID() { return &ThisErrT::ID; }
     342             : 
     343          11 :   const void *dynamicClassID() const override { return &ThisErrT::ID; }
     344             : 
     345       69364 :   bool isA(const void *const ClassID) const override {
     346       69364 :     return ClassID == classID() || ParentErrT::isA(ClassID);
     347             :   }
     348             : };
     349             : 
     350             : /// Special ErrorInfo subclass representing a list of ErrorInfos.
     351             : /// Instances of this class are constructed by joinError.
     352          46 : class ErrorList final : public ErrorInfo<ErrorList> {
     353             :   // handleErrors needs to be able to iterate the payload list of an
     354             :   // ErrorList.
     355             :   template <typename... HandlerTs>
     356             :   friend Error handleErrors(Error E, HandlerTs &&... Handlers);
     357             : 
     358             :   // joinErrors is implemented in terms of join.
     359             :   friend Error joinErrors(Error, Error);
     360             : 
     361             : public:
     362           0 :   void log(raw_ostream &OS) const override {
     363           0 :     OS << "Multiple errors:\n";
     364           0 :     for (auto &ErrPayload : Payloads) {
     365           0 :       ErrPayload->log(OS);
     366           0 :       OS << "\n";
     367             :     }
     368           0 :   }
     369             : 
     370             :   std::error_code convertToErrorCode() const override;
     371             : 
     372             :   // Used by ErrorInfo::classID.
     373             :   static char ID;
     374             : 
     375             : private:
     376             :   ErrorList(std::unique_ptr<ErrorInfoBase> Payload1,
     377          46 :             std::unique_ptr<ErrorInfoBase> Payload2) {
     378             :     assert(!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() &&
     379             :            "ErrorList constructor payloads should be singleton errors");
     380             :     Payloads.push_back(std::move(Payload1));
     381             :     Payloads.push_back(std::move(Payload2));
     382             :   }
     383             : 
     384         162 :   static Error join(Error E1, Error E2) {
     385         162 :     if (!E1)
     386             :       return E2;
     387          55 :     if (!E2)
     388             :       return E1;
     389             :     if (E1.isA<ErrorList>()) {
     390             :       auto &E1List = static_cast<ErrorList &>(*E1.getPtr());
     391             :       if (E2.isA<ErrorList>()) {
     392             :         auto E2Payload = E2.takePayload();
     393             :         auto &E2List = static_cast<ErrorList &>(*E2Payload);
     394           3 :         for (auto &Payload : E2List.Payloads)
     395           2 :           E1List.Payloads.push_back(std::move(Payload));
     396             :       } else
     397           2 :         E1List.Payloads.push_back(E2.takePayload());
     398             : 
     399             :       return E1;
     400             :     }
     401             :     if (E2.isA<ErrorList>()) {
     402             :       auto &E2List = static_cast<ErrorList &>(*E2.getPtr());
     403          14 :       E2List.Payloads.insert(E2List.Payloads.begin(), E1.takePayload());
     404             :       return E2;
     405             :     }
     406             :     return Error(std::unique_ptr<ErrorList>(
     407         138 :         new ErrorList(E1.takePayload(), E2.takePayload())));
     408             :   }
     409             : 
     410             :   std::vector<std::unique_ptr<ErrorInfoBase>> Payloads;
     411             : };
     412             : 
     413             : /// Concatenate errors. The resulting Error is unchecked, and contains the
     414             : /// ErrorInfo(s), if any, contained in E1, followed by the
     415             : /// ErrorInfo(s), if any, contained in E2.
     416          62 : inline Error joinErrors(Error E1, Error E2) {
     417         186 :   return ErrorList::join(std::move(E1), std::move(E2));
     418             : }
     419             : 
     420             : /// Tagged union holding either a T or a Error.
     421             : ///
     422             : /// This class parallels ErrorOr, but replaces error_code with Error. Since
     423             : /// Error cannot be copied, this class replaces getError() with
     424             : /// takeError(). It also adds an bool errorIsA<ErrT>() method for testing the
     425             : /// error class type.
     426             : template <class T> class LLVM_NODISCARD Expected {
     427             :   template <class T1> friend class ExpectedAsOutParameter;
     428             :   template <class OtherT> friend class Expected;
     429             : 
     430             :   static const bool isRef = std::is_reference<T>::value;
     431             : 
     432             :   using wrap = ReferenceStorage<typename std::remove_reference<T>::type>;
     433             : 
     434             :   using error_type = std::unique_ptr<ErrorInfoBase>;
     435             : 
     436             : public:
     437             :   using storage_type = typename std::conditional<isRef, wrap, T>::type;
     438             :   using value_type = T;
     439             : 
     440             : private:
     441             :   using reference = typename std::remove_reference<T>::type &;
     442             :   using const_reference = const typename std::remove_reference<T>::type &;
     443             :   using pointer = typename std::remove_reference<T>::type *;
     444             :   using const_pointer = const typename std::remove_reference<T>::type *;
     445             : 
     446             : public:
     447             :   /// Create an Expected<T> error value from the given Error.
     448          45 :   Expected(Error Err)
     449       59580 :       : HasError(true)
     450             : #if LLVM_ENABLE_ABI_BREAKING_CHECKS
     451             :         // Expected is unchecked upon construction in Debug builds.
     452             :         , Unchecked(true)
     453             : #endif
     454             :   {
     455             :     assert(Err && "Cannot create Expected<T> from Error success value.");
     456             :     new (getErrorStorage()) error_type(Err.takePayload());
     457             :   }
     458             : 
     459             :   /// Forbid to convert from Error::success() implicitly, this avoids having
     460             :   /// Expected<T> foo() { return Error::success(); } which compiles otherwise
     461             :   /// but triggers the assertion above.
     462             :   Expected(ErrorSuccess) = delete;
     463             : 
     464             :   /// Create an Expected<T> success value from the given OtherT value, which
     465             :   /// must be convertible to T.
     466             :   template <typename OtherT>
     467        1175 :   Expected(OtherT &&Val,
     468             :            typename std::enable_if<std::is_convertible<OtherT, T>::value>::type
     469             :                * = nullptr)
     470   400532981 :       : HasError(false)
     471             : #if LLVM_ENABLE_ABI_BREAKING_CHECKS
     472             :         // Expected is unchecked upon construction in Debug builds.
     473             :         , Unchecked(true)
     474             : #endif
     475             :   {
     476   400400774 :     new (getStorage()) storage_type(std::forward<OtherT>(Val));
     477          53 :   }
     478             : 
     479             :   /// Move construct an Expected<T> value.
     480        3050 :   Expected(Expected &&Other) { moveConstruct(std::move(Other)); }
     481             : 
     482             :   /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT
     483             :   /// must be convertible to T.
     484             :   template <class OtherT>
     485        2125 :   Expected(Expected<OtherT> &&Other,
     486             :            typename std::enable_if<std::is_convertible<OtherT, T>::value>::type
     487             :                * = nullptr) {
     488             :     moveConstruct(std::move(Other));
     489             :   }
     490             : 
     491             :   /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT
     492             :   /// isn't convertible to T.
     493             :   template <class OtherT>
     494             :   explicit Expected(
     495             :       Expected<OtherT> &&Other,
     496             :       typename std::enable_if<!std::is_convertible<OtherT, T>::value>::type * =
     497             :           nullptr) {
     498             :     moveConstruct(std::move(Other));
     499             :   }
     500             : 
     501             :   /// Move-assign from another Expected<T>.
     502             :   Expected &operator=(Expected &&Other) {
     503        1754 :     moveAssign(std::move(Other));
     504             :     return *this;
     505             :   }
     506             : 
     507             :   /// Destroy an Expected<T>.
     508      453817 :   ~Expected() {
     509             :     assertIsChecked();
     510   322524438 :     if (!HasError)
     511       62680 :       getStorage()->~storage_type();
     512             :     else
     513             :       getErrorStorage()->~error_type();
     514    64649331 :   }
     515             : 
     516             :   /// Return false if there is an error.
     517             :   explicit operator bool() {
     518             : #if LLVM_ENABLE_ABI_BREAKING_CHECKS
     519             :     Unchecked = HasError;
     520             : #endif
     521   400168270 :     return !HasError;
     522             :   }
     523             : 
     524             :   /// Returns a reference to the stored T value.
     525             :   reference get() {
     526             :     assertIsChecked();
     527             :     return *getStorage();
     528             :   }
     529             : 
     530             :   /// Returns a const reference to the stored T value.
     531             :   const_reference get() const {
     532             :     assertIsChecked();
     533             :     return const_cast<Expected<T> *>(this)->get();
     534             :   }
     535             : 
     536             :   /// Check that this Expected<T> is an error of type ErrT.
     537             :   template <typename ErrT> bool errorIsA() const {
     538           4 :     return HasError && (*getErrorStorage())->template isA<ErrT>();
     539             :   }
     540             : 
     541             :   /// Take ownership of the stored error.
     542             :   /// After calling this the Expected<T> is in an indeterminate state that can
     543             :   /// only be safely destructed. No further calls (beside the destructor) should
     544             :   /// be made on the Expected<T> vaule.
     545             :   Error takeError() {
     546             : #if LLVM_ENABLE_ABI_BREAKING_CHECKS
     547             :     Unchecked = false;
     548             : #endif
     549      429924 :     return HasError ? Error(std::move(*getErrorStorage())) : Error::success();
     550             :   }
     551             : 
     552             :   /// Returns a pointer to the stored T value.
     553             :   pointer operator->() {
     554             :     assertIsChecked();
     555             :     return toPointer(getStorage());
     556             :   }
     557             : 
     558             :   /// Returns a const pointer to the stored T value.
     559             :   const_pointer operator->() const {
     560             :     assertIsChecked();
     561             :     return toPointer(getStorage());
     562             :   }
     563             : 
     564             :   /// Returns a reference to the stored T value.
     565             :   reference operator*() {
     566             :     assertIsChecked();
     567             :     return *getStorage();
     568             :   }
     569             : 
     570             :   /// Returns a const reference to the stored T value.
     571             :   const_reference operator*() const {
     572             :     assertIsChecked();
     573             :     return *getStorage();
     574             :   }
     575             : 
     576             : private:
     577             :   template <class T1>
     578             :   static bool compareThisIfSameType(const T1 &a, const T1 &b) {
     579             :     return &a == &b;
     580             :   }
     581             : 
     582             :   template <class T1, class T2>
     583             :   static bool compareThisIfSameType(const T1 &a, const T2 &b) {
     584             :     return false;
     585             :   }
     586             : 
     587         383 :   template <class OtherT> void moveConstruct(Expected<OtherT> &&Other) {
     588       40040 :     HasError = Other.HasError;
     589             : #if LLVM_ENABLE_ABI_BREAKING_CHECKS
     590             :     Unchecked = true;
     591             :     Other.Unchecked = false;
     592             : #endif
     593             : 
     594       40033 :     if (!HasError)
     595        7141 :       new (getStorage()) storage_type(std::move(*Other.getStorage()));
     596             :     else
     597             :       new (getErrorStorage()) error_type(std::move(*Other.getErrorStorage()));
     598         383 :   }
     599             : 
     600        1754 :   template <class OtherT> void moveAssign(Expected<OtherT> &&Other) {
     601             :     assertIsChecked();
     602             : 
     603        1754 :     if (compareThisIfSameType(*this, Other))
     604             :       return;
     605             : 
     606        1007 :     this->~Expected();
     607             :     new (this) Expected(std::move(Other));
     608             :   }
     609             : 
     610             :   pointer toPointer(pointer Val) { return Val; }
     611             : 
     612             :   const_pointer toPointer(const_pointer Val) const { return Val; }
     613             : 
     614             :   pointer toPointer(wrap *Val) { return &Val->get(); }
     615             : 
     616             :   const_pointer toPointer(const wrap *Val) const { return &Val->get(); }
     617             : 
     618             :   storage_type *getStorage() {
     619             :     assert(!HasError && "Cannot get value when an error exists!");
     620      369234 :     return reinterpret_cast<storage_type *>(TStorage.buffer);
     621             :   }
     622             : 
     623             :   const storage_type *getStorage() const {
     624             :     assert(!HasError && "Cannot get value when an error exists!");
     625             :     return reinterpret_cast<const storage_type *>(TStorage.buffer);
     626             :   }
     627             : 
     628             :   error_type *getErrorStorage() {
     629             :     assert(HasError && "Cannot get error when a value exists!");
     630             :     return reinterpret_cast<error_type *>(ErrorStorage.buffer);
     631             :   }
     632             : 
     633             :   const error_type *getErrorStorage() const {
     634             :     assert(HasError && "Cannot get error when a value exists!");
     635             :     return reinterpret_cast<const error_type *>(ErrorStorage.buffer);
     636             :   }
     637             : 
     638             :   // Used by ExpectedAsOutParameter to reset the checked flag.
     639             :   void setUnchecked() {
     640             : #if LLVM_ENABLE_ABI_BREAKING_CHECKS
     641             :     Unchecked = true;
     642             : #endif
     643             :   }
     644             : 
     645             : #if LLVM_ENABLE_ABI_BREAKING_CHECKS
     646             :   LLVM_ATTRIBUTE_NORETURN
     647             :   LLVM_ATTRIBUTE_NOINLINE
     648             :   void fatalUncheckedExpected() const {
     649             :     dbgs() << "Expected<T> must be checked before access or destruction.\n";
     650             :     if (HasError) {
     651             :       dbgs() << "Unchecked Expected<T> contained error:\n";
     652             :       (*getErrorStorage())->log(dbgs());
     653             :     } else
     654             :       dbgs() << "Expected<T> value was in success state. (Note: Expected<T> "
     655             :                 "values in success mode must still be checked prior to being "
     656             :                 "destroyed).\n";
     657             :     abort();
     658             :   }
     659             : #endif
     660             : 
     661             :   void assertIsChecked() {
     662             : #if LLVM_ENABLE_ABI_BREAKING_CHECKS
     663             :     if (LLVM_UNLIKELY(Unchecked))
     664             :       fatalUncheckedExpected();
     665             : #endif
     666             :   }
     667             : 
     668             :   union {
     669             :     AlignedCharArrayUnion<storage_type> TStorage;
     670             :     AlignedCharArrayUnion<error_type> ErrorStorage;
     671             :   };
     672             :   bool HasError : 1;
     673             : #if LLVM_ENABLE_ABI_BREAKING_CHECKS
     674             :   bool Unchecked : 1;
     675             : #endif
     676             : };
     677             : 
     678             : /// Report a serious error, calling any installed error handler. See
     679             : /// ErrorHandling.h.
     680             : LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err,
     681             :                                                 bool gen_crash_diag = true);
     682             : 
     683             : /// Report a fatal error if Err is a failure value.
     684             : ///
     685             : /// This function can be used to wrap calls to fallible functions ONLY when it
     686             : /// is known that the Error will always be a success value. E.g.
     687             : ///
     688             : ///   @code{.cpp}
     689             : ///   // foo only attempts the fallible operation if DoFallibleOperation is
     690             : ///   // true. If DoFallibleOperation is false then foo always returns
     691             : ///   // Error::success().
     692             : ///   Error foo(bool DoFallibleOperation);
     693             : ///
     694             : ///   cantFail(foo(false));
     695             : ///   @endcode
     696             : inline void cantFail(Error Err, const char *Msg = nullptr) {
     697      292581 :   if (Err) {
     698             :     if (!Msg)
     699             :       Msg = "Failure value returned from cantFail wrapped call";
     700           0 :     llvm_unreachable(Msg);
     701             :   }
     702             : }
     703             : 
     704             : /// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and
     705             : /// returns the contained value.
     706             : ///
     707             : /// This function can be used to wrap calls to fallible functions ONLY when it
     708             : /// is known that the Error will always be a success value. E.g.
     709             : ///
     710             : ///   @code{.cpp}
     711             : ///   // foo only attempts the fallible operation if DoFallibleOperation is
     712             : ///   // true. If DoFallibleOperation is false then foo always returns an int.
     713             : ///   Expected<int> foo(bool DoFallibleOperation);
     714             : ///
     715             : ///   int X = cantFail(foo(false));
     716             : ///   @endcode
     717             : template <typename T>
     718             : T cantFail(Expected<T> ValOrErr, const char *Msg = nullptr) {
     719     1344756 :   if (ValOrErr)
     720     1344720 :     return std::move(*ValOrErr);
     721             :   else {
     722             :     if (!Msg)
     723             :       Msg = "Failure value returned from cantFail wrapped call";
     724           0 :     llvm_unreachable(Msg);
     725             :   }
     726             : }
     727             : 
     728             : /// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and
     729             : /// returns the contained reference.
     730             : ///
     731             : /// This function can be used to wrap calls to fallible functions ONLY when it
     732             : /// is known that the Error will always be a success value. E.g.
     733             : ///
     734             : ///   @code{.cpp}
     735             : ///   // foo only attempts the fallible operation if DoFallibleOperation is
     736             : ///   // true. If DoFallibleOperation is false then foo always returns a Bar&.
     737             : ///   Expected<Bar&> foo(bool DoFallibleOperation);
     738             : ///
     739             : ///   Bar &X = cantFail(foo(false));
     740             : ///   @endcode
     741             : template <typename T>
     742             : T& cantFail(Expected<T&> ValOrErr, const char *Msg = nullptr) {
     743         743 :   if (ValOrErr)
     744             :     return *ValOrErr;
     745             :   else {
     746             :     if (!Msg)
     747             :       Msg = "Failure value returned from cantFail wrapped call";
     748           0 :     llvm_unreachable(Msg);
     749             :   }
     750             : }
     751             : 
     752             : /// Helper for testing applicability of, and applying, handlers for
     753             : /// ErrorInfo types.
     754             : template <typename HandlerT>
     755             : class ErrorHandlerTraits
     756             :     : public ErrorHandlerTraits<decltype(
     757             :           &std::remove_reference<HandlerT>::type::operator())> {};
     758             : 
     759             : // Specialization functions of the form 'Error (const ErrT&)'.
     760             : template <typename ErrT> class ErrorHandlerTraits<Error (&)(ErrT &)> {
     761             : public:
     762             :   static bool appliesTo(const ErrorInfoBase &E) {
     763             :     return E.template isA<ErrT>();
     764             :   }
     765             : 
     766             :   template <typename HandlerT>
     767             :   static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
     768             :     assert(appliesTo(*E) && "Applying incorrect handler");
     769          18 :     return H(static_cast<ErrT &>(*E));
     770             :   }
     771             : };
     772             : 
     773             : // Specialization functions of the form 'void (const ErrT&)'.
     774             : template <typename ErrT> class ErrorHandlerTraits<void (&)(ErrT &)> {
     775             : public:
     776             :   static bool appliesTo(const ErrorInfoBase &E) {
     777             :     return E.template isA<ErrT>();
     778             :   }
     779             : 
     780             :   template <typename HandlerT>
     781           0 :   static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
     782             :     assert(appliesTo(*E) && "Applying incorrect handler");
     783        3433 :     H(static_cast<ErrT &>(*E));
     784           0 :     return Error::success();
     785             :   }
     786             : };
     787             : 
     788             : /// Specialization for functions of the form 'Error (std::unique_ptr<ErrT>)'.
     789             : template <typename ErrT>
     790             : class ErrorHandlerTraits<Error (&)(std::unique_ptr<ErrT>)> {
     791             : public:
     792             :   static bool appliesTo(const ErrorInfoBase &E) {
     793             :     return E.template isA<ErrT>();
     794             :   }
     795             : 
     796             :   template <typename HandlerT>
     797         204 :   static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
     798             :     assert(appliesTo(*E) && "Applying incorrect handler");
     799             :     std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release()));
     800         410 :     return H(std::move(SubE));
     801             :   }
     802             : };
     803             : 
     804             : /// Specialization for functions of the form 'void (std::unique_ptr<ErrT>)'.
     805             : template <typename ErrT>
     806             : class ErrorHandlerTraits<void (&)(std::unique_ptr<ErrT>)> {
     807             : public:
     808             :   static bool appliesTo(const ErrorInfoBase &E) {
     809             :     return E.template isA<ErrT>();
     810             :   }
     811             : 
     812             :   template <typename HandlerT>
     813          89 :   static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
     814             :     assert(appliesTo(*E) && "Applying incorrect handler");
     815             :     std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release()));
     816          91 :     H(std::move(SubE));
     817          89 :     return Error::success();
     818             :   }
     819             : };
     820             : 
     821             : // Specialization for member functions of the form 'RetT (const ErrT&)'.
     822             : template <typename C, typename RetT, typename ErrT>
     823             : class ErrorHandlerTraits<RetT (C::*)(ErrT &)>
     824             :     : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
     825             : 
     826             : // Specialization for member functions of the form 'RetT (const ErrT&) const'.
     827             : template <typename C, typename RetT, typename ErrT>
     828             : class ErrorHandlerTraits<RetT (C::*)(ErrT &) const>
     829             :     : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
     830             : 
     831             : // Specialization for member functions of the form 'RetT (const ErrT&)'.
     832             : template <typename C, typename RetT, typename ErrT>
     833             : class ErrorHandlerTraits<RetT (C::*)(const ErrT &)>
     834             :     : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
     835             : 
     836             : // Specialization for member functions of the form 'RetT (const ErrT&) const'.
     837             : template <typename C, typename RetT, typename ErrT>
     838             : class ErrorHandlerTraits<RetT (C::*)(const ErrT &) const>
     839             :     : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
     840             : 
     841             : /// Specialization for member functions of the form
     842             : /// 'RetT (std::unique_ptr<ErrT>)'.
     843             : template <typename C, typename RetT, typename ErrT>
     844             : class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>)>
     845             :     : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {};
     846             : 
     847             : /// Specialization for member functions of the form
     848             : /// 'RetT (std::unique_ptr<ErrT>) const'.
     849             : template <typename C, typename RetT, typename ErrT>
     850             : class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>) const>
     851             :     : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {};
     852             : 
     853             : inline Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload) {
     854             :   return Error(std::move(Payload));
     855             : }
     856             : 
     857             : template <typename HandlerT, typename... HandlerTs>
     858       34645 : Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload,
     859             :                       HandlerT &&Handler, HandlerTs &&... Handlers) {
     860       34645 :   if (ErrorHandlerTraits<HandlerT>::appliesTo(*Payload))
     861             :     return ErrorHandlerTraits<HandlerT>::apply(std::forward<HandlerT>(Handler),
     862         586 :                                                std::move(Payload));
     863             :   return handleErrorImpl(std::move(Payload),
     864          50 :                          std::forward<HandlerTs>(Handlers)...);
     865             : }
     866             : 
     867             : /// Pass the ErrorInfo(s) contained in E to their respective handlers. Any
     868             : /// unhandled errors (or Errors returned by handlers) are re-concatenated and
     869             : /// returned.
     870             : /// Because this function returns an error, its result must also be checked
     871             : /// or returned. If you intend to handle all errors use handleAllErrors
     872             : /// (which returns void, and will abort() on unhandled errors) instead.
     873             : template <typename... HandlerTs>
     874      249836 : Error handleErrors(Error E, HandlerTs &&... Hs) {
     875      249836 :   if (!E)
     876             :     return Error::success();
     877             : 
     878             :   std::unique_ptr<ErrorInfoBase> Payload = E.takePayload();
     879             : 
     880       34566 :   if (Payload->isA<ErrorList>()) {
     881             :     ErrorList &List = static_cast<ErrorList &>(*Payload);
     882             :     Error R;
     883         145 :     for (auto &P : List.Payloads)
     884         600 :       R = ErrorList::join(
     885             :           std::move(R),
     886             :           handleErrorImpl(std::move(P), std::forward<HandlerTs>(Hs)...));
     887             :     return R;
     888             :   }
     889             : 
     890       69012 :   return handleErrorImpl(std::move(Payload), std::forward<HandlerTs>(Hs)...);
     891             : }
     892             : 
     893             : /// Behaves the same as handleErrors, except that by contract all errors
     894             : /// *must* be handled by the given handlers (i.e. there must be no remaining
     895             : /// errors after running the handlers, or llvm_unreachable is called).
     896             : template <typename... HandlerTs>
     897      249487 : void handleAllErrors(Error E, HandlerTs &&... Handlers) {
     898      748405 :   cantFail(handleErrors(std::move(E), std::forward<HandlerTs>(Handlers)...));
     899      249459 : }
     900             : 
     901             : /// Check that E is a non-error, then drop it.
     902             : /// If E is an error, llvm_unreachable will be called.
     903             : inline void handleAllErrors(Error E) {
     904             :   cantFail(std::move(E));
     905             : }
     906             : 
     907             : /// Handle any errors (if present) in an Expected<T>, then try a recovery path.
     908             : ///
     909             : /// If the incoming value is a success value it is returned unmodified. If it
     910             : /// is a failure value then it the contained error is passed to handleErrors.
     911             : /// If handleErrors is able to handle the error then the RecoveryPath functor
     912             : /// is called to supply the final result. If handleErrors is not able to
     913             : /// handle all errors then the unhandled errors are returned.
     914             : ///
     915             : /// This utility enables the follow pattern:
     916             : ///
     917             : ///   @code{.cpp}
     918             : ///   enum FooStrategy { Aggressive, Conservative };
     919             : ///   Expected<Foo> foo(FooStrategy S);
     920             : ///
     921             : ///   auto ResultOrErr =
     922             : ///     handleExpected(
     923             : ///       foo(Aggressive),
     924             : ///       []() { return foo(Conservative); },
     925             : ///       [](AggressiveStrategyError&) {
     926             : ///         // Implicitly conusme this - we'll recover by using a conservative
     927             : ///         // strategy.
     928             : ///       });
     929             : ///
     930             : ///   @endcode
     931             : template <typename T, typename RecoveryFtor, typename... HandlerTs>
     932           3 : Expected<T> handleExpected(Expected<T> ValOrErr, RecoveryFtor &&RecoveryPath,
     933             :                            HandlerTs &&... Handlers) {
     934           3 :   if (ValOrErr)
     935             :     return ValOrErr;
     936             : 
     937           6 :   if (auto Err = handleErrors(ValOrErr.takeError(),
     938             :                               std::forward<HandlerTs>(Handlers)...))
     939             :     return std::move(Err);
     940             : 
     941             :   return RecoveryPath();
     942             : }
     943             : 
     944             : /// Log all errors (if any) in E to OS. If there are any errors, ErrorBanner
     945             : /// will be printed before the first one is logged. A newline will be printed
     946             : /// after each error.
     947             : ///
     948             : /// This is useful in the base level of your program to allow clean termination
     949             : /// (allowing clean deallocation of resources, etc.), while reporting error
     950             : /// information to the user.
     951             : void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner);
     952             : 
     953             : /// Write all error messages (if any) in E to a string. The newline character
     954             : /// is used to separate error messages.
     955        2359 : inline std::string toString(Error E) {
     956        2359 :   SmallVector<std::string, 2> Errors;
     957        9414 :   handleAllErrors(std::move(E), [&Errors](const ErrorInfoBase &EI) {
     958        4674 :     Errors.push_back(EI.message());
     959        2337 :   });
     960        2359 :   return join(Errors.begin(), Errors.end(), "\n");
     961             : }
     962             : 
     963             : /// Consume a Error without doing anything. This method should be used
     964             : /// only where an error can be considered a reasonable and expected return
     965             : /// value.
     966             : ///
     967             : /// Uses of this method are potentially indicative of design problems: If it's
     968             : /// legitimate to do nothing while processing an "error", the error-producer
     969             : /// might be more clearly refactored to return an Optional<T>.
     970       53818 : inline void consumeError(Error Err) {
     971      107636 :   handleAllErrors(std::move(Err), [](const ErrorInfoBase &) {});
     972       53818 : }
     973             : 
     974             : /// Helper for converting an Error to a bool.
     975             : ///
     976             : /// This method returns true if Err is in an error state, or false if it is
     977             : /// in a success state.  Puts Err in a checked state in both cases (unlike
     978             : /// Error::operator bool(), which only does this for success states).
     979           0 : inline bool errorToBool(Error Err) {
     980             :   bool IsError = static_cast<bool>(Err);
     981           0 :   if (IsError)
     982           0 :     consumeError(std::move(Err));
     983           0 :   return IsError;
     984             : }
     985             : 
     986             : /// Helper for Errors used as out-parameters.
     987             : ///
     988             : /// This helper is for use with the Error-as-out-parameter idiom, where an error
     989             : /// is passed to a function or method by reference, rather than being returned.
     990             : /// In such cases it is helpful to set the checked bit on entry to the function
     991             : /// so that the error can be written to (unchecked Errors abort on assignment)
     992             : /// and clear the checked bit on exit so that clients cannot accidentally forget
     993             : /// to check the result. This helper performs these actions automatically using
     994             : /// RAII:
     995             : ///
     996             : ///   @code{.cpp}
     997             : ///   Result foo(Error &Err) {
     998             : ///     ErrorAsOutParameter ErrAsOutParam(&Err); // 'Checked' flag set
     999             : ///     // <body of foo>
    1000             : ///     // <- 'Checked' flag auto-cleared when ErrAsOutParam is destructed.
    1001             : ///   }
    1002             : ///   @endcode
    1003             : ///
    1004             : /// ErrorAsOutParameter takes an Error* rather than Error& so that it can be
    1005             : /// used with optional Errors (Error pointers that are allowed to be null). If
    1006             : /// ErrorAsOutParameter took an Error reference, an instance would have to be
    1007             : /// created inside every condition that verified that Error was non-null. By
    1008             : /// taking an Error pointer we can just create one instance at the top of the
    1009             : /// function.
    1010             : class ErrorAsOutParameter {
    1011             : public:
    1012             :   ErrorAsOutParameter(Error *Err) : Err(Err) {
    1013             :     // Raise the checked bit if Err is success.
    1014        6678 :     if (Err)
    1015             :       (void)!!*Err;
    1016             :   }
    1017             : 
    1018             :   ~ErrorAsOutParameter() {
    1019             :     // Clear the checked bit.
    1020       13937 :     if (Err && !*Err)
    1021             :       *Err = Error::success();
    1022             :   }
    1023             : 
    1024             : private:
    1025             :   Error *Err;
    1026             : };
    1027             : 
    1028             : /// Helper for Expected<T>s used as out-parameters.
    1029             : ///
    1030             : /// See ErrorAsOutParameter.
    1031             : template <typename T>
    1032             : class ExpectedAsOutParameter {
    1033             : public:
    1034             :   ExpectedAsOutParameter(Expected<T> *ValOrErr)
    1035             :     : ValOrErr(ValOrErr) {
    1036             :     if (ValOrErr)
    1037             :       (void)!!*ValOrErr;
    1038             :   }
    1039             : 
    1040             :   ~ExpectedAsOutParameter() {
    1041             :     if (ValOrErr)
    1042             :       ValOrErr->setUnchecked();
    1043             :   }
    1044             : 
    1045             : private:
    1046             :   Expected<T> *ValOrErr;
    1047             : };
    1048             : 
    1049             : /// This class wraps a std::error_code in a Error.
    1050             : ///
    1051             : /// This is useful if you're writing an interface that returns a Error
    1052             : /// (or Expected) and you want to call code that still returns
    1053             : /// std::error_codes.
    1054        3843 : class ECError : public ErrorInfo<ECError> {
    1055             :   friend Error errorCodeToError(std::error_code);
    1056             : 
    1057             : public:
    1058        1460 :   void setErrorCode(std::error_code EC) { this->EC = EC; }
    1059         283 :   std::error_code convertToErrorCode() const override { return EC; }
    1060         228 :   void log(raw_ostream &OS) const override { OS << EC.message(); }
    1061             : 
    1062             :   // Used by ErrorInfo::classID.
    1063             :   static char ID;
    1064             : 
    1065             : protected:
    1066             :   ECError() = default;
    1067             :   ECError(std::error_code EC) : EC(EC) {}
    1068             : 
    1069             :   std::error_code EC;
    1070             : };
    1071             : 
    1072             : /// The value returned by this function can be returned from convertToErrorCode
    1073             : /// for Error values where no sensible translation to std::error_code exists.
    1074             : /// It should only be used in this situation, and should never be used where a
    1075             : /// sensible conversion to std::error_code is available, as attempts to convert
    1076             : /// to/from this error will result in a fatal error. (i.e. it is a programmatic
    1077             : ///error to try to convert such a value).
    1078             : std::error_code inconvertibleErrorCode();
    1079             : 
    1080             : /// Helper for converting an std::error_code to a Error.
    1081             : Error errorCodeToError(std::error_code EC);
    1082             : 
    1083             : /// Helper for converting an ECError to a std::error_code.
    1084             : ///
    1085             : /// This method requires that Err be Error() or an ECError, otherwise it
    1086             : /// will trigger a call to abort().
    1087             : std::error_code errorToErrorCode(Error Err);
    1088             : 
    1089             : /// Convert an ErrorOr<T> to an Expected<T>.
    1090        1110 : template <typename T> Expected<T> errorOrToExpected(ErrorOr<T> &&EO) {
    1091        1110 :   if (auto EC = EO.getError())
    1092          10 :     return errorCodeToError(EC);
    1093             :   return std::move(*EO);
    1094             : }
    1095             : 
    1096             : /// Convert an Expected<T> to an ErrorOr<T>.
    1097           2 : template <typename T> ErrorOr<T> expectedToErrorOr(Expected<T> &&E) {
    1098           2 :   if (auto Err = E.takeError())
    1099           2 :     return errorToErrorCode(std::move(Err));
    1100             :   return std::move(*E);
    1101             : }
    1102             : 
    1103             : /// This class wraps a string in an Error.
    1104             : ///
    1105             : /// StringError is useful in cases where the client is not expected to be able
    1106             : /// to consume the specific error message programmatically (for example, if the
    1107             : /// error message is to be presented to the user).
    1108       60800 : class StringError : public ErrorInfo<StringError> {
    1109             : public:
    1110             :   static char ID;
    1111             : 
    1112             :   StringError(const Twine &S, std::error_code EC);
    1113             : 
    1114             :   void log(raw_ostream &OS) const override;
    1115             :   std::error_code convertToErrorCode() const override;
    1116             : 
    1117           1 :   const std::string &getMessage() const { return Msg; }
    1118             : 
    1119             : private:
    1120             :   std::string Msg;
    1121             :   std::error_code EC;
    1122             : };
    1123             : 
    1124             : /// Helper for check-and-exit error handling.
    1125             : ///
    1126             : /// For tool use only. NOT FOR USE IN LIBRARY CODE.
    1127             : ///
    1128       11442 : class ExitOnError {
    1129             : public:
    1130             :   /// Create an error on exit helper.
    1131             :   ExitOnError(std::string Banner = "", int DefaultErrorExitCode = 1)
    1132        5734 :       : Banner(std::move(Banner)),
    1133         147 :         GetExitCode([=](const Error &) { return DefaultErrorExitCode; }) {}
    1134             : 
    1135             :   /// Set the banner string for any errors caught by operator().
    1136        1592 :   void setBanner(std::string Banner) { this->Banner = std::move(Banner); }
    1137             : 
    1138             :   /// Set the exit-code mapper function.
    1139             :   void setExitCodeMapper(std::function<int(const Error &)> GetExitCode) {
    1140           3 :     this->GetExitCode = std::move(GetExitCode);
    1141             :   }
    1142             : 
    1143             :   /// Check Err. If it's in a failure state log the error(s) and exit.
    1144       12858 :   void operator()(Error Err) const { checkError(std::move(Err)); }
    1145             : 
    1146             :   /// Check E. If it's in a success state then return the contained value. If
    1147             :   /// it's in a failure state log the error(s) and exit.
    1148        5402 :   template <typename T> T operator()(Expected<T> &&E) const {
    1149       10730 :     checkError(E.takeError());
    1150        5328 :     return std::move(*E);
    1151             :   }
    1152             : 
    1153             :   /// Check E. If it's in a success state then return the contained reference. If
    1154             :   /// it's in a failure state log the error(s) and exit.
    1155         611 :   template <typename T> T& operator()(Expected<T&> &&E) const {
    1156        1222 :     checkError(E.takeError());
    1157         611 :     return *E;
    1158             :   }
    1159             : 
    1160             : private:
    1161       10324 :   void checkError(Error Err) const {
    1162       10324 :     if (Err) {
    1163             :       int ExitCode = GetExitCode(Err);
    1164         596 :       logAllUnhandledErrors(std::move(Err), errs(), Banner);
    1165         149 :       exit(ExitCode);
    1166             :     }
    1167       10175 :   }
    1168             : 
    1169             :   std::string Banner;
    1170             :   std::function<int(const Error &)> GetExitCode;
    1171             : };
    1172             : 
    1173             : } // end namespace llvm
    1174             : 
    1175             : #endif // LLVM_SUPPORT_ERROR_H

Generated by: LCOV version 1.13