LCOV - code coverage report
Current view: top level - include/llvm/Support - Error.h (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 201 212 94.8 %
Date: 2017-09-14 15:23:50 Functions: 422 663 63.7 %
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         388 : 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        2592 :   virtual std::string message() const {
      56        5184 :     std::string Msg;
      57        5184 :     raw_string_ostream OS(Msg);
      58        2592 :     log(OS);
      59        7776 :     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       58445 :     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     2384622 :   Error() {
     172     2384622 :     setPtr(nullptr);
     173     2384622 :     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     2649031 :   Error(Error &&Other) {
     187     2649308 :     setChecked(true);
     188     5298616 :     *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       77651 :   Error(std::unique_ptr<ErrorInfoBase> Payload) {
     194       77651 :     setPtr(Payload.release());
     195       77651 :     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     2667046 :     assertIsChecked();
     208     2667046 :     setPtr(Other.getPtr());
     209             : 
     210             :     // This Error is unchecked, even if the source error was checked.
     211     2667046 :     setChecked(false);
     212             : 
     213             :     // Null out Other's payload and set its checked bit.
     214     2667046 :     Other.setPtr(nullptr);
     215     2667046 :     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      106286 :   ~Error() {
     223     5158102 :     assertIsChecked();
     224     5158102 :     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     5086216 :     setChecked(getPtr() == nullptr);
     232     2543162 :     return getPtr() != nullptr;
     233             :   }
     234             : 
     235             :   /// Check whether one error is a subclass of another.
     236             :   template <typename ErrT> bool isA() const {
     237          69 :     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             :   void assertIsChecked() {
     250             : #if LLVM_ENABLE_ABI_BREAKING_CHECKS
     251             :     if (!getChecked() || getPtr()) {
     252             :       dbgs() << "Program aborted due to an unhandled Error:\n";
     253             :       if (getPtr())
     254             :         getPtr()->log(dbgs());
     255             :       else
     256             :         dbgs()
     257             :             << "Error value was Success. (Note: Success values must still be "
     258             :                "checked prior to being destroyed).\n";
     259             :       abort();
     260             :     }
     261             : #endif
     262             :   }
     263             : 
     264             :   ErrorInfoBase *getPtr() const {
     265             :     return reinterpret_cast<ErrorInfoBase*>(
     266     5965801 :              reinterpret_cast<uintptr_t>(Payload) &
     267      763890 :              ~static_cast<uintptr_t>(0x1));
     268             :   }
     269             : 
     270             :   void setPtr(ErrorInfoBase *EI) {
     271             : #if LLVM_ENABLE_ABI_BREAKING_CHECKS
     272             :     Payload = reinterpret_cast<ErrorInfoBase*>(
     273             :                 (reinterpret_cast<uintptr_t>(EI) &
     274             :                  ~static_cast<uintptr_t>(0x1)) |
     275             :                 (reinterpret_cast<uintptr_t>(Payload) & 0x1));
     276             : #else
     277      293280 :     Payload = EI;
     278             : #endif
     279             :   }
     280             : 
     281             :   bool getChecked() const {
     282             : #if LLVM_ENABLE_ABI_BREAKING_CHECKS
     283             :     return (reinterpret_cast<uintptr_t>(Payload) & 0x1) == 0;
     284             : #else
     285             :     return true;
     286             : #endif
     287             :   }
     288             : 
     289             :   void setChecked(bool V) {
     290     4950949 :     Payload = reinterpret_cast<ErrorInfoBase*>(
     291       77649 :                 (reinterpret_cast<uintptr_t>(Payload) &
     292     2863850 :                   ~static_cast<uintptr_t>(0x1)) |
     293     2537553 :                   (V ? 0 : 1));
     294             :   }
     295             : 
     296             :   std::unique_ptr<ErrorInfoBase> takePayload() {
     297      155300 :     std::unique_ptr<ErrorInfoBase> Tmp(getPtr());
     298       77650 :     setPtr(nullptr);
     299       77650 :     setChecked(true);
     300             :     return Tmp;
     301             :   }
     302             : 
     303             :   ErrorInfoBase *Payload = nullptr;
     304             : };
     305             : 
     306             : /// Subclass of Error for the sole purpose of identifying the success path in
     307             : /// the type system. This allows to catch invalid conversion to Expected<T> at
     308             : /// compile time.
     309     9538402 : class ErrorSuccess : public Error {};
     310             : 
     311     4767640 : inline ErrorSuccess Error::success() { return ErrorSuccess(); }
     312             : 
     313             : /// Make a Error instance representing failure using the given error info
     314             : /// type.
     315         223 : template <typename ErrT, typename... ArgTs> Error make_error(ArgTs &&... Args) {
     316      144174 :   return Error(llvm::make_unique<ErrT>(std::forward<ArgTs>(Args)...));
     317             : }
     318             : 
     319             : /// Base class for user error types. Users should declare their error types
     320             : /// like:
     321             : ///
     322             : /// class MyError : public ErrorInfo<MyError> {
     323             : ///   ....
     324             : /// };
     325             : ///
     326             : /// This class provides an implementation of the ErrorInfoBase::kind
     327             : /// method, which is used by the Error RTTI system.
     328             : template <typename ThisErrT, typename ParentErrT = ErrorInfoBase>
     329       63218 : class ErrorInfo : public ParentErrT {
     330             : public:
     331             :   static const void *classID() { return &ThisErrT::ID; }
     332             : 
     333          11 :   const void *dynamicClassID() const override { return &ThisErrT::ID; }
     334             : 
     335       58500 :   bool isA(const void *const ClassID) const override {
     336       58500 :     return ClassID == classID() || ParentErrT::isA(ClassID);
     337             :   }
     338             : };
     339             : 
     340             : /// Special ErrorInfo subclass representing a list of ErrorInfos.
     341             : /// Instances of this class are constructed by joinError.
     342          24 : class ErrorList final : public ErrorInfo<ErrorList> {
     343             :   // handleErrors needs to be able to iterate the payload list of an
     344             :   // ErrorList.
     345             :   template <typename... HandlerTs>
     346             :   friend Error handleErrors(Error E, HandlerTs &&... Handlers);
     347             : 
     348             :   // joinErrors is implemented in terms of join.
     349             :   friend Error joinErrors(Error, Error);
     350             : 
     351             : public:
     352           0 :   void log(raw_ostream &OS) const override {
     353           0 :     OS << "Multiple errors:\n";
     354           0 :     for (auto &ErrPayload : Payloads) {
     355           0 :       ErrPayload->log(OS);
     356           0 :       OS << "\n";
     357             :     }
     358           0 :   }
     359             : 
     360             :   std::error_code convertToErrorCode() const override;
     361             : 
     362             :   // Used by ErrorInfo::classID.
     363             :   static char ID;
     364             : 
     365             : private:
     366             :   ErrorList(std::unique_ptr<ErrorInfoBase> Payload1,
     367          36 :             std::unique_ptr<ErrorInfoBase> Payload2) {
     368             :     assert(!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() &&
     369             :            "ErrorList constructor payloads should be singleton errors");
     370          24 :     Payloads.push_back(std::move(Payload1));
     371          24 :     Payloads.push_back(std::move(Payload2));
     372             :   }
     373             : 
     374          41 :   static Error join(Error E1, Error E2) {
     375          41 :     if (!E1)
     376             :       return E2;
     377          15 :     if (!E2)
     378             :       return E1;
     379          15 :     if (E1.isA<ErrorList>()) {
     380           2 :       auto &E1List = static_cast<ErrorList &>(*E1.getPtr());
     381           1 :       if (E2.isA<ErrorList>()) {
     382           2 :         auto E2Payload = E2.takePayload();
     383           1 :         auto &E2List = static_cast<ErrorList &>(*E2Payload);
     384           6 :         for (auto &Payload : E2List.Payloads)
     385           4 :           E1List.Payloads.push_back(std::move(Payload));
     386             :       } else
     387           4 :         E1List.Payloads.push_back(E2.takePayload());
     388             : 
     389             :       return E1;
     390             :     }
     391           1 :     if (E2.isA<ErrorList>()) {
     392           1 :       auto &E2List = static_cast<ErrorList &>(*E2.getPtr());
     393           6 :       E2List.Payloads.insert(E2List.Payloads.begin(), E1.takePayload());
     394             :       return E2;
     395             :     }
     396          36 :     return Error(std::unique_ptr<ErrorList>(
     397          96 :         new ErrorList(E1.takePayload(), E2.takePayload())));
     398             :   }
     399             : 
     400             :   std::vector<std::unique_ptr<ErrorInfoBase>> Payloads;
     401             : };
     402             : 
     403             : /// Concatenate errors. The resulting Error is unchecked, and contains the
     404             : /// ErrorInfo(s), if any, contained in E1, followed by the
     405             : /// ErrorInfo(s), if any, contained in E2.
     406          15 : inline Error joinErrors(Error E1, Error E2) {
     407          75 :   return ErrorList::join(std::move(E1), std::move(E2));
     408             : }
     409             : 
     410             : /// Tagged union holding either a T or a Error.
     411             : ///
     412             : /// This class parallels ErrorOr, but replaces error_code with Error. Since
     413             : /// Error cannot be copied, this class replaces getError() with
     414             : /// takeError(). It also adds an bool errorIsA<ErrT>() method for testing the
     415             : /// error class type.
     416             : template <class T> class LLVM_NODISCARD Expected {
     417             :   template <class T1> friend class ExpectedAsOutParameter;
     418             :   template <class OtherT> friend class Expected;
     419             : 
     420             :   static const bool isRef = std::is_reference<T>::value;
     421             : 
     422             :   using wrap = ReferenceStorage<typename std::remove_reference<T>::type>;
     423             : 
     424             :   using error_type = std::unique_ptr<ErrorInfoBase>;
     425             : 
     426             : public:
     427             :   using storage_type = typename std::conditional<isRef, wrap, T>::type;
     428             :   using value_type = T;
     429             : 
     430             : private:
     431             :   using reference = typename std::remove_reference<T>::type &;
     432             :   using const_reference = const typename std::remove_reference<T>::type &;
     433             :   using pointer = typename std::remove_reference<T>::type *;
     434             :   using const_pointer = const typename std::remove_reference<T>::type *;
     435             : 
     436             : public:
     437             :   /// Create an Expected<T> error value from the given Error.
     438           9 :   Expected(Error Err)
     439       48410 :       : HasError(true)
     440             : #if LLVM_ENABLE_ABI_BREAKING_CHECKS
     441             :         // Expected is unchecked upon construction in Debug builds.
     442             :         , Unchecked(true)
     443             : #endif
     444             :   {
     445             :     assert(Err && "Cannot create Expected<T> from Error success value.");
     446       96820 :     new (getErrorStorage()) error_type(Err.takePayload());
     447             :   }
     448             : 
     449             :   /// Forbid to convert from Error::success() implicitly, this avoids having
     450             :   /// Expected<T> foo() { return Error::success(); } which compiles otherwise
     451             :   /// but triggers the assertion above.
     452             :   Expected(ErrorSuccess) = delete;
     453             : 
     454             :   /// Create an Expected<T> success value from the given OtherT value, which
     455             :   /// must be convertible to T.
     456             :   template <typename OtherT>
     457         556 :   Expected(OtherT &&Val,
     458             :            typename std::enable_if<std::is_convertible<OtherT, T>::value>::type
     459             :                * = nullptr)
     460   255934705 :       : HasError(false)
     461             : #if LLVM_ENABLE_ABI_BREAKING_CHECKS
     462             :         // Expected is unchecked upon construction in Debug builds.
     463             :         , Unchecked(true)
     464             : #endif
     465             :   {
     466   256318829 :     new (getStorage()) storage_type(std::forward<OtherT>(Val));
     467          34 :   }
     468             : 
     469             :   /// Move construct an Expected<T> value.
     470        2208 :   Expected(Expected &&Other) { moveConstruct(std::move(Other)); }
     471             : 
     472             :   /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT
     473             :   /// must be convertible to T.
     474             :   template <class OtherT>
     475       17459 :   Expected(Expected<OtherT> &&Other,
     476             :            typename std::enable_if<std::is_convertible<OtherT, T>::value>::type
     477             :                * = nullptr) {
     478       31660 :     moveConstruct(std::move(Other));
     479             :   }
     480             : 
     481             :   /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT
     482             :   /// isn't convertible to T.
     483             :   template <class OtherT>
     484             :   explicit Expected(
     485             :       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-assign from another Expected<T>.
     492             :   Expected &operator=(Expected &&Other) {
     493        1100 :     moveAssign(std::move(Other));
     494             :     return *this;
     495             :   }
     496             : 
     497             :   /// Destroy an Expected<T>.
     498      329131 :   ~Expected() {
     499   256001880 :     assertIsChecked();
     500   206833889 :     if (!HasError)
     501      304893 :       getStorage()->~storage_type();
     502             :     else
     503       48697 :       getErrorStorage()->~error_type();
     504    41559379 :   }
     505             : 
     506             :   /// \brief Return false if there is an error.
     507             :   explicit operator bool() {
     508             : #if LLVM_ENABLE_ABI_BREAKING_CHECKS
     509             :     Unchecked = HasError;
     510             : #endif
     511   255672008 :     return !HasError;
     512             :   }
     513             : 
     514             :   /// \brief Returns a reference to the stored T value.
     515             :   reference get() {
     516      286906 :     assertIsChecked();
     517      290244 :     return *getStorage();
     518             :   }
     519             : 
     520             :   /// \brief Returns a const reference to the stored T value.
     521             :   const_reference get() const {
     522             :     assertIsChecked();
     523             :     return const_cast<Expected<T> *>(this)->get();
     524             :   }
     525             : 
     526             :   /// \brief Check that this Expected<T> is an error of type ErrT.
     527             :   template <typename ErrT> bool errorIsA() const {
     528          12 :     return HasError && (*getErrorStorage())->template isA<ErrT>();
     529             :   }
     530             : 
     531             :   /// \brief Take ownership of the stored error.
     532             :   /// After calling this the Expected<T> is in an indeterminate state that can
     533             :   /// only be safely destructed. No further calls (beside the destructor) should
     534             :   /// be made on the Expected<T> vaule.
     535             :   Error takeError() {
     536             : #if LLVM_ENABLE_ABI_BREAKING_CHECKS
     537             :     Unchecked = false;
     538             : #endif
     539      586592 :     return HasError ? Error(std::move(*getErrorStorage())) : Error::success();
     540             :   }
     541             : 
     542             :   /// \brief Returns a pointer to the stored T value.
     543             :   pointer operator->() {
     544       64346 :     assertIsChecked();
     545       66394 :     return toPointer(getStorage());
     546             :   }
     547             : 
     548             :   /// \brief Returns a const pointer to the stored T value.
     549             :   const_pointer operator->() const {
     550             :     assertIsChecked();
     551             :     return toPointer(getStorage());
     552             :   }
     553             : 
     554             :   /// \brief Returns a reference to the stored T value.
     555             :   reference operator*() {
     556   255624090 :     assertIsChecked();
     557   255625923 :     return *getStorage();
     558             :   }
     559             : 
     560             :   /// \brief Returns a const reference to the stored T value.
     561             :   const_reference operator*() const {
     562             :     assertIsChecked();
     563             :     return *getStorage();
     564             :   }
     565             : 
     566             : private:
     567             :   template <class T1>
     568             :   static bool compareThisIfSameType(const T1 &a, const T1 &b) {
     569             :     return &a == &b;
     570             :   }
     571             : 
     572             :   template <class T1, class T2>
     573             :   static bool compareThisIfSameType(const T1 &a, const T2 &b) {
     574             :     return false;
     575             :   }
     576             : 
     577         168 :   template <class OtherT> void moveConstruct(Expected<OtherT> &&Other) {
     578       19233 :     HasError = Other.HasError;
     579             : #if LLVM_ENABLE_ABI_BREAKING_CHECKS
     580             :     Unchecked = true;
     581             :     Other.Unchecked = false;
     582             : #endif
     583             : 
     584       19228 :     if (!HasError)
     585       45534 :       new (getStorage()) storage_type(std::move(*Other.getStorage()));
     586             :     else
     587        1734 :       new (getErrorStorage()) error_type(std::move(*Other.getErrorStorage()));
     588         168 :   }
     589             : 
     590         712 :   template <class OtherT> void moveAssign(Expected<OtherT> &&Other) {
     591         906 :     assertIsChecked();
     592             : 
     593         906 :     if (compareThisIfSameType(*this, Other))
     594             :       return;
     595             : 
     596         906 :     this->~Expected();
     597        1074 :     new (this) Expected(std::move(Other));
     598             :   }
     599             : 
     600             :   pointer toPointer(pointer Val) { return Val; }
     601             : 
     602             :   const_pointer toPointer(const_pointer Val) const { return Val; }
     603             : 
     604        2048 :   pointer toPointer(wrap *Val) { return &Val->get(); }
     605             : 
     606             :   const_pointer toPointer(const wrap *Val) const { return &Val->get(); }
     607             : 
     608             :   storage_type *getStorage() {
     609             :     assert(!HasError && "Cannot get value when an error exists!");
     610      337071 :     return reinterpret_cast<storage_type *>(TStorage.buffer);
     611             :   }
     612             : 
     613             :   const storage_type *getStorage() const {
     614             :     assert(!HasError && "Cannot get value when an error exists!");
     615             :     return reinterpret_cast<const storage_type *>(TStorage.buffer);
     616             :   }
     617             : 
     618             :   error_type *getErrorStorage() {
     619             :     assert(HasError && "Cannot get error when a value exists!");
     620       48988 :     return reinterpret_cast<error_type *>(ErrorStorage.buffer);
     621             :   }
     622             : 
     623             :   const error_type *getErrorStorage() const {
     624             :     assert(HasError && "Cannot get error when a value exists!");
     625             :     return reinterpret_cast<const error_type *>(ErrorStorage.buffer);
     626             :   }
     627             : 
     628             :   // Used by ExpectedAsOutParameter to reset the checked flag.
     629             :   void setUnchecked() {
     630             : #if LLVM_ENABLE_ABI_BREAKING_CHECKS
     631             :     Unchecked = true;
     632             : #endif
     633             :   }
     634             : 
     635             :   void assertIsChecked() {
     636             : #if LLVM_ENABLE_ABI_BREAKING_CHECKS
     637             :     if (Unchecked) {
     638             :       dbgs() << "Expected<T> must be checked before access or destruction.\n";
     639             :       if (HasError) {
     640             :         dbgs() << "Unchecked Expected<T> contained error:\n";
     641             :         (*getErrorStorage())->log(dbgs());
     642             :       } else
     643             :         dbgs() << "Expected<T> value was in success state. (Note: Expected<T> "
     644             :                   "values in success mode must still be checked prior to being "
     645             :                   "destroyed).\n";
     646             :       abort();
     647             :     }
     648             : #endif
     649             :   }
     650             : 
     651             :   union {
     652             :     AlignedCharArrayUnion<storage_type> TStorage;
     653             :     AlignedCharArrayUnion<error_type> ErrorStorage;
     654             :   };
     655             :   bool HasError : 1;
     656             : #if LLVM_ENABLE_ABI_BREAKING_CHECKS
     657             :   bool Unchecked : 1;
     658             : #endif
     659             : };
     660             : 
     661             : /// Report a serious error, calling any installed error handler. See
     662             : /// ErrorHandling.h.
     663             : LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err,
     664             :                                                 bool gen_crash_diag = true);
     665             : 
     666             : /// Report a fatal error if Err is a failure value.
     667             : ///
     668             : /// This function can be used to wrap calls to fallible functions ONLY when it
     669             : /// is known that the Error will always be a success value. E.g.
     670             : ///
     671             : ///   @code{.cpp}
     672             : ///   // foo only attempts the fallible operation if DoFallibleOperation is
     673             : ///   // true. If DoFallibleOperation is false then foo always returns
     674             : ///   // Error::success().
     675             : ///   Error foo(bool DoFallibleOperation);
     676             : ///
     677             : ///   cantFail(foo(false));
     678             : ///   @endcode
     679             : inline void cantFail(Error Err, const char *Msg = nullptr) {
     680      153018 :   if (Err) {
     681             :     if (!Msg)
     682             :       Msg = "Failure value returned from cantFail wrapped call";
     683           0 :     llvm_unreachable(Msg);
     684             :   }
     685             : }
     686             : 
     687             : /// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and
     688             : /// returns the contained value.
     689             : ///
     690             : /// This function can be used to wrap calls to fallible functions ONLY when it
     691             : /// is known that the Error will always be a success value. E.g.
     692             : ///
     693             : ///   @code{.cpp}
     694             : ///   // foo only attempts the fallible operation if DoFallibleOperation is
     695             : ///   // true. If DoFallibleOperation is false then foo always returns an int.
     696             : ///   Expected<int> foo(bool DoFallibleOperation);
     697             : ///
     698             : ///   int X = cantFail(foo(false));
     699             : ///   @endcode
     700             : template <typename T>
     701             : T cantFail(Expected<T> ValOrErr, const char *Msg = nullptr) {
     702         572 :   if (ValOrErr)
     703         572 :     return std::move(*ValOrErr);
     704             :   else {
     705             :     if (!Msg)
     706             :       Msg = "Failure value returned from cantFail wrapped call";
     707           0 :     llvm_unreachable(Msg);
     708             :   }
     709             : }
     710             : 
     711             : /// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and
     712             : /// returns the contained reference.
     713             : ///
     714             : /// This function can be used to wrap calls to fallible functions ONLY when it
     715             : /// is known that the Error will always be a success value. E.g.
     716             : ///
     717             : ///   @code{.cpp}
     718             : ///   // foo only attempts the fallible operation if DoFallibleOperation is
     719             : ///   // true. If DoFallibleOperation is false then foo always returns a Bar&.
     720             : ///   Expected<Bar&> foo(bool DoFallibleOperation);
     721             : ///
     722             : ///   Bar &X = cantFail(foo(false));
     723             : ///   @endcode
     724             : template <typename T>
     725             : T& cantFail(Expected<T&> ValOrErr, const char *Msg = nullptr) {
     726         691 :   if (ValOrErr)
     727         691 :     return *ValOrErr;
     728             :   else {
     729             :     if (!Msg)
     730             :       Msg = "Failure value returned from cantFail wrapped call";
     731           0 :     llvm_unreachable(Msg);
     732             :   }
     733             : }
     734             : 
     735             : /// Helper for testing applicability of, and applying, handlers for
     736             : /// ErrorInfo types.
     737             : template <typename HandlerT>
     738             : class ErrorHandlerTraits
     739             :     : public ErrorHandlerTraits<decltype(
     740             :           &std::remove_reference<HandlerT>::type::operator())> {};
     741             : 
     742             : // Specialization functions of the form 'Error (const ErrT&)'.
     743             : template <typename ErrT> class ErrorHandlerTraits<Error (&)(ErrT &)> {
     744             : public:
     745             :   static bool appliesTo(const ErrorInfoBase &E) {
     746          22 :     return E.template isA<ErrT>();
     747             :   }
     748             : 
     749             :   template <typename HandlerT>
     750             :   static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
     751             :     assert(appliesTo(*E) && "Applying incorrect handler");
     752          22 :     return H(static_cast<ErrT &>(*E));
     753             :   }
     754             : };
     755             : 
     756             : // Specialization functions of the form 'void (const ErrT&)'.
     757             : template <typename ErrT> class ErrorHandlerTraits<void (&)(ErrT &)> {
     758             : public:
     759             :   static bool appliesTo(const ErrorInfoBase &E) {
     760       28990 :     return E.template isA<ErrT>();
     761             :   }
     762             : 
     763             :   template <typename HandlerT>
     764             :   static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
     765             :     assert(appliesTo(*E) && "Applying incorrect handler");
     766       29534 :     H(static_cast<ErrT &>(*E));
     767       86895 :     return Error::success();
     768             :   }
     769             : };
     770             : 
     771             : /// Specialization for functions of the form 'Error (std::unique_ptr<ErrT>)'.
     772             : template <typename ErrT>
     773             : class ErrorHandlerTraits<Error (&)(std::unique_ptr<ErrT>)> {
     774             : public:
     775             :   static bool appliesTo(const ErrorInfoBase &E) {
     776         213 :     return E.template isA<ErrT>();
     777             :   }
     778             : 
     779             :   template <typename HandlerT>
     780         204 :   static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
     781             :     assert(appliesTo(*E) && "Applying incorrect handler");
     782         628 :     std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release()));
     783         837 :     return H(std::move(SubE));
     784             :   }
     785             : };
     786             : 
     787             : /// Specialization for functions of the form 'void (std::unique_ptr<ErrT>)'.
     788             : template <typename ErrT>
     789             : class ErrorHandlerTraits<void (&)(std::unique_ptr<ErrT>)> {
     790             : public:
     791             :   static bool appliesTo(const ErrorInfoBase &E) {
     792           3 :     return E.template isA<ErrT>();
     793             :   }
     794             : 
     795             :   template <typename HandlerT>
     796             :   static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
     797             :     assert(appliesTo(*E) && "Applying incorrect handler");
     798           9 :     std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release()));
     799           9 :     H(std::move(SubE));
     800           9 :     return Error::success();
     801             :   }
     802             : };
     803             : 
     804             : // Specialization for member functions of the form 'RetT (const ErrT&)'.
     805             : template <typename C, typename RetT, typename ErrT>
     806             : class ErrorHandlerTraits<RetT (C::*)(ErrT &)>
     807             :     : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
     808             : 
     809             : // Specialization for member functions of the form 'RetT (const ErrT&) const'.
     810             : template <typename C, typename RetT, typename ErrT>
     811             : class ErrorHandlerTraits<RetT (C::*)(ErrT &) const>
     812             :     : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
     813             : 
     814             : // Specialization for member functions of the form 'RetT (const ErrT&)'.
     815             : template <typename C, typename RetT, typename ErrT>
     816             : class ErrorHandlerTraits<RetT (C::*)(const ErrT &)>
     817             :     : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
     818             : 
     819             : // Specialization for member functions of the form 'RetT (const ErrT&) const'.
     820             : template <typename C, typename RetT, typename ErrT>
     821             : class ErrorHandlerTraits<RetT (C::*)(const ErrT &) const>
     822             :     : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
     823             : 
     824             : /// Specialization for member functions of the form
     825             : /// 'RetT (std::unique_ptr<ErrT>)'.
     826             : template <typename C, typename RetT, typename ErrT>
     827             : class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>)>
     828             :     : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {};
     829             : 
     830             : /// Specialization for member functions of the form
     831             : /// 'RetT (std::unique_ptr<ErrT>) const'.
     832             : template <typename C, typename RetT, typename ErrT>
     833             : class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>) const>
     834             :     : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {};
     835             : 
     836             : inline Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload) {
     837          16 :   return Error(std::move(Payload));
     838             : }
     839             : 
     840             : template <typename HandlerT, typename... HandlerTs>
     841       29228 : Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload,
     842             :                       HandlerT &&Handler, HandlerTs &&... Handlers) {
     843       58456 :   if (ErrorHandlerTraits<HandlerT>::appliesTo(*Payload))
     844             :     return ErrorHandlerTraits<HandlerT>::apply(std::forward<HandlerT>(Handler),
     845       88193 :                                                std::move(Payload));
     846           4 :   return handleErrorImpl(std::move(Payload),
     847          12 :                          std::forward<HandlerTs>(Handlers)...);
     848             : }
     849             : 
     850             : /// Pass the ErrorInfo(s) contained in E to their respective handlers. Any
     851             : /// unhandled errors (or Errors returned by handlers) are re-concatenated and
     852             : /// returned.
     853             : /// Because this function returns an error, its result must also be checked
     854             : /// or returned. If you intend to handle all errors use handleAllErrors
     855             : /// (which returns void, and will abort() on unhandled errors) instead.
     856             : template <typename... HandlerTs>
     857      152578 : Error handleErrors(Error E, HandlerTs &&... Hs) {
     858      152578 :   if (!E)
     859      370095 :     return Error::success();
     860             : 
     861       29213 :   std::unique_ptr<ErrorInfoBase> Payload = E.takePayload();
     862             : 
     863       58426 :   if (Payload->isA<ErrorList>()) {
     864          11 :     ErrorList &List = static_cast<ErrorList &>(*Payload);
     865          22 :     Error R;
     866          70 :     for (auto &P : List.Payloads)
     867         208 :       R = ErrorList::join(
     868          26 :           std::move(R),
     869          26 :           handleErrorImpl(std::move(P), std::forward<HandlerTs>(Hs)...));
     870          11 :     return R;
     871             :   }
     872             : 
     873       87582 :   return handleErrorImpl(std::move(Payload), std::forward<HandlerTs>(Hs)...);
     874             : }
     875             : 
     876             : /// Behaves the same as handleErrors, except that it requires that all
     877             : /// errors be handled by the given handlers. If any unhandled error remains
     878             : /// after the handlers have run, report_fatal_error() will be called.
     879             : template <typename... HandlerTs>
     880      152347 : void handleAllErrors(Error E, HandlerTs &&... Handlers) {
     881      761660 :   cantFail(handleErrors(std::move(E), std::forward<HandlerTs>(Handlers)...));
     882      152322 : }
     883             : 
     884             : /// Check that E is a non-error, then drop it.
     885             : /// If E is an error report_fatal_error will be called.
     886             : inline void handleAllErrors(Error E) {
     887             :   cantFail(std::move(E));
     888             : }
     889             : 
     890             : /// Handle any errors (if present) in an Expected<T>, then try a recovery path.
     891             : ///
     892             : /// If the incoming value is a success value it is returned unmodified. If it
     893             : /// is a failure value then it the contained error is passed to handleErrors.
     894             : /// If handleErrors is able to handle the error then the RecoveryPath functor
     895             : /// is called to supply the final result. If handleErrors is not able to
     896             : /// handle all errors then the unhandled errors are returned.
     897             : ///
     898             : /// This utility enables the follow pattern:
     899             : ///
     900             : ///   @code{.cpp}
     901             : ///   enum FooStrategy { Aggressive, Conservative };
     902             : ///   Expected<Foo> foo(FooStrategy S);
     903             : ///
     904             : ///   auto ResultOrErr =
     905             : ///     handleExpected(
     906             : ///       foo(Aggressive),
     907             : ///       []() { return foo(Conservative); },
     908             : ///       [](AggressiveStrategyError&) {
     909             : ///         // Implicitly conusme this - we'll recover by using a conservative
     910             : ///         // strategy.
     911             : ///       });
     912             : ///
     913             : ///   @endcode
     914             : template <typename T, typename RecoveryFtor, typename... HandlerTs>
     915           3 : Expected<T> handleExpected(Expected<T> ValOrErr, RecoveryFtor &&RecoveryPath,
     916             :                            HandlerTs &&... Handlers) {
     917           3 :   if (ValOrErr)
     918             :     return ValOrErr;
     919             : 
     920           8 :   if (auto Err = handleErrors(ValOrErr.takeError(),
     921             :                               std::forward<HandlerTs>(Handlers)...))
     922           4 :     return std::move(Err);
     923             : 
     924           1 :   return RecoveryPath();
     925             : }
     926             : 
     927             : /// Log all errors (if any) in E to OS. If there are any errors, ErrorBanner
     928             : /// will be printed before the first one is logged. A newline will be printed
     929             : /// after each error.
     930             : ///
     931             : /// This is useful in the base level of your program to allow clean termination
     932             : /// (allowing clean deallocation of resources, etc.), while reporting error
     933             : /// information to the user.
     934             : void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner);
     935             : 
     936             : /// Write all error messages (if any) in E to a string. The newline character
     937             : /// is used to separate error messages.
     938        2561 : inline std::string toString(Error E) {
     939        5122 :   SmallVector<std::string, 2> Errors;
     940       10245 :   handleAllErrors(std::move(E), [&Errors](const ErrorInfoBase &EI) {
     941        5124 :     Errors.push_back(EI.message());
     942        2562 :   });
     943       12805 :   return join(Errors.begin(), Errors.end(), "\n");
     944             : }
     945             : 
     946             : /// Consume a Error without doing anything. This method should be used
     947             : /// only where an error can be considered a reasonable and expected return
     948             : /// value.
     949             : ///
     950             : /// Uses of this method are potentially indicative of design problems: If it's
     951             : /// legitimate to do nothing while processing an "error", the error-producer
     952             : /// might be more clearly refactored to return an Optional<T>.
     953       40089 : inline void consumeError(Error Err) {
     954      120267 :   handleAllErrors(std::move(Err), [](const ErrorInfoBase &) {});
     955       40089 : }
     956             : 
     957             : /// Helper for Errors used as out-parameters.
     958             : ///
     959             : /// This helper is for use with the Error-as-out-parameter idiom, where an error
     960             : /// is passed to a function or method by reference, rather than being returned.
     961             : /// In such cases it is helpful to set the checked bit on entry to the function
     962             : /// so that the error can be written to (unchecked Errors abort on assignment)
     963             : /// and clear the checked bit on exit so that clients cannot accidentally forget
     964             : /// to check the result. This helper performs these actions automatically using
     965             : /// RAII:
     966             : ///
     967             : ///   @code{.cpp}
     968             : ///   Result foo(Error &Err) {
     969             : ///     ErrorAsOutParameter ErrAsOutParam(&Err); // 'Checked' flag set
     970             : ///     // <body of foo>
     971             : ///     // <- 'Checked' flag auto-cleared when ErrAsOutParam is destructed.
     972             : ///   }
     973             : ///   @endcode
     974             : ///
     975             : /// ErrorAsOutParameter takes an Error* rather than Error& so that it can be
     976             : /// used with optional Errors (Error pointers that are allowed to be null). If
     977             : /// ErrorAsOutParameter took an Error reference, an instance would have to be
     978             : /// created inside every condition that verified that Error was non-null. By
     979             : /// taking an Error pointer we can just create one instance at the top of the
     980             : /// function.
     981             : class ErrorAsOutParameter {
     982             : public:
     983        7369 :   ErrorAsOutParameter(Error *Err) : Err(Err) {
     984             :     // Raise the checked bit if Err is success.
     985        4989 :     if (Err)
     986             :       (void)!!*Err;
     987             :   }
     988             : 
     989        5353 :   ~ErrorAsOutParameter() {
     990             :     // Clear the checked bit.
     991       14603 :     if (Err && !*Err)
     992       19701 :       *Err = Error::success();
     993             :   }
     994             : 
     995             : private:
     996             :   Error *Err;
     997             : };
     998             : 
     999             : /// Helper for Expected<T>s used as out-parameters.
    1000             : ///
    1001             : /// See ErrorAsOutParameter.
    1002             : template <typename T>
    1003             : class ExpectedAsOutParameter {
    1004             : public:
    1005             :   ExpectedAsOutParameter(Expected<T> *ValOrErr)
    1006          17 :     : ValOrErr(ValOrErr) {
    1007             :     if (ValOrErr)
    1008             :       (void)!!*ValOrErr;
    1009             :   }
    1010             : 
    1011             :   ~ExpectedAsOutParameter() {
    1012             :     if (ValOrErr)
    1013             :       ValOrErr->setUnchecked();
    1014             :   }
    1015             : 
    1016             : private:
    1017             :   Expected<T> *ValOrErr;
    1018             : };
    1019             : 
    1020             : /// This class wraps a std::error_code in a Error.
    1021             : ///
    1022             : /// This is useful if you're writing an interface that returns a Error
    1023             : /// (or Expected) and you want to call code that still returns
    1024             : /// std::error_codes.
    1025        3420 : class ECError : public ErrorInfo<ECError> {
    1026             :   friend Error errorCodeToError(std::error_code);
    1027             : 
    1028             : public:
    1029        1122 :   void setErrorCode(std::error_code EC) { this->EC = EC; }
    1030         268 :   std::error_code convertToErrorCode() const override { return EC; }
    1031         176 :   void log(raw_ostream &OS) const override { OS << EC.message(); }
    1032             : 
    1033             :   // Used by ErrorInfo::classID.
    1034             :   static char ID;
    1035             : 
    1036             : protected:
    1037        1683 :   ECError() = default;
    1038         770 :   ECError(std::error_code EC) : EC(EC) {}
    1039             : 
    1040             :   std::error_code EC;
    1041             : };
    1042             : 
    1043             : /// The value returned by this function can be returned from convertToErrorCode
    1044             : /// for Error values where no sensible translation to std::error_code exists.
    1045             : /// It should only be used in this situation, and should never be used where a
    1046             : /// sensible conversion to std::error_code is available, as attempts to convert
    1047             : /// to/from this error will result in a fatal error. (i.e. it is a programmatic
    1048             : ///error to try to convert such a value).
    1049             : std::error_code inconvertibleErrorCode();
    1050             : 
    1051             : /// Helper for converting an std::error_code to a Error.
    1052             : Error errorCodeToError(std::error_code EC);
    1053             : 
    1054             : /// Helper for converting an ECError to a std::error_code.
    1055             : ///
    1056             : /// This method requires that Err be Error() or an ECError, otherwise it
    1057             : /// will trigger a call to abort().
    1058             : std::error_code errorToErrorCode(Error Err);
    1059             : 
    1060             : /// Convert an ErrorOr<T> to an Expected<T>.
    1061        5785 : template <typename T> Expected<T> errorOrToExpected(ErrorOr<T> &&EO) {
    1062        5785 :   if (auto EC = EO.getError())
    1063          39 :     return errorCodeToError(EC);
    1064        5772 :   return std::move(*EO);
    1065             : }
    1066             : 
    1067             : /// Convert an Expected<T> to an ErrorOr<T>.
    1068           2 : template <typename T> ErrorOr<T> expectedToErrorOr(Expected<T> &&E) {
    1069           5 :   if (auto Err = E.takeError())
    1070           4 :     return errorToErrorCode(std::move(Err));
    1071           1 :   return std::move(*E);
    1072             : }
    1073             : 
    1074             : /// This class wraps a string in an Error.
    1075             : ///
    1076             : /// StringError is useful in cases where the client is not expected to be able
    1077             : /// to consume the specific error message programmatically (for example, if the
    1078             : /// error message is to be presented to the user).
    1079       81252 : class StringError : public ErrorInfo<StringError> {
    1080             : public:
    1081             :   static char ID;
    1082             : 
    1083             :   StringError(const Twine &S, std::error_code EC);
    1084             : 
    1085             :   void log(raw_ostream &OS) const override;
    1086             :   std::error_code convertToErrorCode() const override;
    1087             : 
    1088           3 :   const std::string &getMessage() const { return Msg; }
    1089             : 
    1090             : private:
    1091             :   std::string Msg;
    1092             :   std::error_code EC;
    1093             : };
    1094             : 
    1095             : /// Helper for check-and-exit error handling.
    1096             : ///
    1097             : /// For tool use only. NOT FOR USE IN LIBRARY CODE.
    1098             : ///
    1099       13611 : class ExitOnError {
    1100             : public:
    1101             :   /// Create an error on exit helper.
    1102             :   ExitOnError(std::string Banner = "", int DefaultErrorExitCode = 1)
    1103        8908 :       : Banner(std::move(Banner)),
    1104       13462 :         GetExitCode([=](const Error &) { return DefaultErrorExitCode; }) {}
    1105             : 
    1106             :   /// Set the banner string for any errors caught by operator().
    1107        1428 :   void setBanner(std::string Banner) { this->Banner = std::move(Banner); }
    1108             : 
    1109             :   /// Set the exit-code mapper function.
    1110             :   void setExitCodeMapper(std::function<int(const Error &)> GetExitCode) {
    1111           3 :     this->GetExitCode = std::move(GetExitCode);
    1112             :   }
    1113             : 
    1114             :   /// Check Err. If it's in a failure state log the error(s) and exit.
    1115        9917 :   void operator()(Error Err) const { checkError(std::move(Err)); }
    1116             : 
    1117             :   /// Check E. If it's in a success state then return the contained value. If
    1118             :   /// it's in a failure state log the error(s) and exit.
    1119        2712 :   template <typename T> T operator()(Expected<T> &&E) const {
    1120        5365 :     checkError(E.takeError());
    1121        4683 :     return std::move(*E);
    1122             :   }
    1123             : 
    1124             :   /// Check E. If it's in a success state then return the contained reference. If
    1125             :   /// it's in a failure state log the error(s) and exit.
    1126         523 :   template <typename T> T& operator()(Expected<T&> &&E) const {
    1127        1046 :     checkError(E.takeError());
    1128         523 :     return *E;
    1129             :   }
    1130             : 
    1131             : private:
    1132        6555 :   void checkError(Error Err) const {
    1133        6555 :     if (Err) {
    1134         204 :       int ExitCode = GetExitCode(Err);
    1135         408 :       logAllUnhandledErrors(std::move(Err), errs(), Banner);
    1136         102 :       exit(ExitCode);
    1137             :     }
    1138        6453 :   }
    1139             : 
    1140             :   std::string Banner;
    1141             :   std::function<int(const Error &)> GetExitCode;
    1142             : };
    1143             : 
    1144             : } // end namespace llvm
    1145             : 
    1146             : #endif // LLVM_SUPPORT_ERROR_H

Generated by: LCOV version 1.13