LCOV - code coverage report
Current view: top level - include/llvm/Support - Error.h (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 1124 1575 71.4 %
Date: 2018-10-20 13:21:21 Functions: 499 1477 33.8 %
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-c/Error.h"
      18             : #include "llvm/ADT/STLExtras.h"
      19             : #include "llvm/ADT/SmallVector.h"
      20             : #include "llvm/ADT/StringExtras.h"
      21             : #include "llvm/ADT/Twine.h"
      22             : #include "llvm/Config/abi-breaking.h"
      23             : #include "llvm/Support/AlignOf.h"
      24             : #include "llvm/Support/Compiler.h"
      25             : #include "llvm/Support/Debug.h"
      26             : #include "llvm/Support/ErrorHandling.h"
      27             : #include "llvm/Support/ErrorOr.h"
      28             : #include "llvm/Support/Format.h"
      29             : #include "llvm/Support/raw_ostream.h"
      30             : #include <algorithm>
      31             : #include <cassert>
      32             : #include <cstdint>
      33             : #include <cstdlib>
      34             : #include <functional>
      35             : #include <memory>
      36             : #include <new>
      37             : #include <string>
      38             : #include <system_error>
      39             : #include <type_traits>
      40             : #include <utility>
      41             : #include <vector>
      42             : 
      43             : namespace llvm {
      44             : 
      45             : class ErrorSuccess;
      46             : 
      47             : /// Base class for error info classes. Do not extend this directly: Extend
      48             : /// the ErrorInfo template subclass instead.
      49         703 : class ErrorInfoBase {
      50             : public:
      51           0 :   virtual ~ErrorInfoBase() = default;
      52             : 
      53             :   /// Print an error message to an output stream.
      54             :   virtual void log(raw_ostream &OS) const = 0;
      55             : 
      56             :   /// Return the error message as a string.
      57        3005 :   virtual std::string message() const {
      58             :     std::string Msg;
      59        3005 :     raw_string_ostream OS(Msg);
      60        3005 :     log(OS);
      61        3005 :     return OS.str();
      62             :   }
      63             : 
      64             :   /// Convert this error to a std::error_code.
      65             :   ///
      66             :   /// This is a temporary crutch to enable interaction with code still
      67             :   /// using std::error_code. It will be removed in the future.
      68             :   virtual std::error_code convertToErrorCode() const = 0;
      69             : 
      70             :   // Returns the class ID for this type.
      71             :   static const void *classID() { return &ID; }
      72             : 
      73             :   // Returns the class ID for the dynamic type of this ErrorInfoBase instance.
      74             :   virtual const void *dynamicClassID() const = 0;
      75             : 
      76             :   // Check whether this instance is a subclass of the class identified by
      77             :   // ClassID.
      78           0 :   virtual bool isA(const void *const ClassID) const {
      79           0 :     return ClassID == classID();
      80             :   }
      81             : 
      82             :   // Check whether this instance is a subclass of ErrorInfoT.
      83             :   template <typename ErrorInfoT> bool isA() const {
      84       35002 :     return isA(ErrorInfoT::classID());
      85             :   }
      86             : 
      87             : private:
      88             :   virtual void anchor();
      89             : 
      90             :   static char ID;
      91             : };
      92             : 
      93             : /// Lightweight error class with error context and mandatory checking.
      94             : ///
      95             : /// Instances of this class wrap a ErrorInfoBase pointer. Failure states
      96             : /// are represented by setting the pointer to a ErrorInfoBase subclass
      97             : /// instance containing information describing the failure. Success is
      98             : /// represented by a null pointer value.
      99             : ///
     100             : /// Instances of Error also contains a 'Checked' flag, which must be set
     101             : /// before the destructor is called, otherwise the destructor will trigger a
     102             : /// runtime error. This enforces at runtime the requirement that all Error
     103             : /// instances be checked or returned to the caller.
     104             : ///
     105             : /// There are two ways to set the checked flag, depending on what state the
     106             : /// Error instance is in. For Error instances indicating success, it
     107             : /// is sufficient to invoke the boolean conversion operator. E.g.:
     108             : ///
     109             : ///   @code{.cpp}
     110             : ///   Error foo(<...>);
     111             : ///
     112             : ///   if (auto E = foo(<...>))
     113             : ///     return E; // <- Return E if it is in the error state.
     114             : ///   // We have verified that E was in the success state. It can now be safely
     115             : ///   // destroyed.
     116             : ///   @endcode
     117             : ///
     118             : /// A success value *can not* be dropped. For example, just calling 'foo(<...>)'
     119             : /// without testing the return value will raise a runtime error, even if foo
     120             : /// returns success.
     121             : ///
     122             : /// For Error instances representing failure, you must use either the
     123             : /// handleErrors or handleAllErrors function with a typed handler. E.g.:
     124             : ///
     125             : ///   @code{.cpp}
     126             : ///   class MyErrorInfo : public ErrorInfo<MyErrorInfo> {
     127             : ///     // Custom error info.
     128             : ///   };
     129             : ///
     130             : ///   Error foo(<...>) { return make_error<MyErrorInfo>(...); }
     131             : ///
     132             : ///   auto E = foo(<...>); // <- foo returns failure with MyErrorInfo.
     133             : ///   auto NewE =
     134             : ///     handleErrors(E,
     135             : ///       [](const MyErrorInfo &M) {
     136             : ///         // Deal with the error.
     137             : ///       },
     138             : ///       [](std::unique_ptr<OtherError> M) -> Error {
     139             : ///         if (canHandle(*M)) {
     140             : ///           // handle error.
     141             : ///           return Error::success();
     142             : ///         }
     143             : ///         // Couldn't handle this error instance. Pass it up the stack.
     144             : ///         return Error(std::move(M));
     145             : ///       );
     146             : ///   // Note - we must check or return NewE in case any of the handlers
     147             : ///   // returned a new error.
     148             : ///   @endcode
     149             : ///
     150             : /// The handleAllErrors function is identical to handleErrors, except
     151             : /// that it has a void return type, and requires all errors to be handled and
     152             : /// no new errors be returned. It prevents errors (assuming they can all be
     153             : /// handled) from having to be bubbled all the way to the top-level.
     154             : ///
     155             : /// *All* Error instances must be checked before destruction, even if
     156             : /// they're moved-assigned or constructed from Success values that have already
     157             : /// been checked. This enforces checking through all levels of the call stack.
     158             : class LLVM_NODISCARD Error {
     159             :   // Both ErrorList and FileError need to be able to yank ErrorInfoBase
     160             :   // pointers out of this class to add to the error list.
     161             :   friend class ErrorList;
     162             :   friend class FileError;
     163             : 
     164             :   // handleErrors needs to be able to set the Checked flag.
     165             :   template <typename... HandlerTs>
     166             :   friend Error handleErrors(Error E, HandlerTs &&... Handlers);
     167             : 
     168             :   // Expected<T> needs to be able to steal the payload when constructed from an
     169             :   // error.
     170             :   template <typename T> friend class Expected;
     171             : 
     172             :   // wrap needs to be able to steal the payload.
     173             :   friend LLVMErrorRef wrap(Error);
     174             : 
     175             : protected:
     176             :   /// Create a success value. Prefer using 'Error::success()' for readability
     177             :   Error() {
     178             :     setPtr(nullptr);
     179             :     setChecked(false);
     180             :   }
     181             : 
     182             : public:
     183             :   /// Create a success value.
     184             :   static ErrorSuccess success();
     185             : 
     186             :   // Errors are not copy-constructable.
     187             :   Error(const Error &Other) = delete;
     188             : 
     189             :   /// Move-construct an error value. The newly constructed error is considered
     190             :   /// unchecked, even if the source error had been checked. The original error
     191             :   /// becomes a checked Success value, regardless of its original state.
     192      210268 :   Error(Error &&Other) {
     193             :     setChecked(true);
     194             :     *this = std::move(Other);
     195             :   }
     196             : 
     197             :   /// Create an error value. Prefer using the 'make_error' function, but
     198             :   /// this constructor can be useful when "re-throwing" errors from handlers.
     199          18 :   Error(std::unique_ptr<ErrorInfoBase> Payload) {
     200             :     setPtr(Payload.release());
     201             :     setChecked(false);
     202             :   }
     203             : 
     204             :   // Errors are not copy-assignable.
     205             :   Error &operator=(const Error &Other) = delete;
     206             : 
     207             :   /// Move-assign an error value. The current error must represent success, you
     208             :   /// you cannot overwrite an unhandled error. The current error is then
     209             :   /// considered unchecked. The source error becomes a checked success value,
     210             :   /// regardless of its original state.
     211             :   Error &operator=(Error &&Other) {
     212             :     // Don't allow overwriting of unchecked values.
     213             :     assertIsChecked();
     214     1021829 :     setPtr(Other.getPtr());
     215             : 
     216             :     // This Error is unchecked, even if the source error was checked.
     217             :     setChecked(false);
     218             : 
     219             :     // Null out Other's payload and set its checked bit.
     220             :     Other.setPtr(nullptr);
     221             :     Other.setChecked(true);
     222             : 
     223             :     return *this;
     224             :   }
     225             : 
     226             :   /// Destroy a Error. Fails with a call to abort() if the error is
     227             :   /// unchecked.
     228       12002 :   ~Error() {
     229             :     assertIsChecked();
     230           0 :     delete getPtr();
     231           0 :   }
     232             : 
     233             :   /// Bool conversion. Returns true if this Error is in a failure state,
     234             :   /// and false if it is in an accept state. If the error is in a Success state
     235             :   /// it will be considered checked.
     236             :   explicit operator bool() {
     237     5220355 :     setChecked(getPtr() == nullptr);
     238         271 :     return getPtr() != nullptr;
     239             :   }
     240             : 
     241             :   /// Check whether one error is a subclass of another.
     242             :   template <typename ErrT> bool isA() const {
     243         149 :     return getPtr() && getPtr()->isA(ErrT::classID());
     244             :   }
     245             : 
     246             :   /// Returns the dynamic class id of this error, or null if this is a success
     247             :   /// value.
     248             :   const void* dynamicClassID() const {
     249             :     if (!getPtr())
     250             :       return nullptr;
     251             :     return getPtr()->dynamicClassID();
     252             :   }
     253             : 
     254             : private:
     255             : #if LLVM_ENABLE_ABI_BREAKING_CHECKS
     256             :   // assertIsChecked() happens very frequently, but under normal circumstances
     257             :   // is supposed to be a no-op.  So we want it to be inlined, but having a bunch
     258             :   // of debug prints can cause the function to be too large for inlining.  So
     259             :   // it's important that we define this function out of line so that it can't be
     260             :   // inlined.
     261             :   LLVM_ATTRIBUTE_NORETURN
     262             :   void fatalUncheckedError() const;
     263             : #endif
     264             : 
     265           0 :   void assertIsChecked() {
     266             : #if LLVM_ENABLE_ABI_BREAKING_CHECKS
     267             :     if (LLVM_UNLIKELY(!getChecked() || getPtr()))
     268             :       fatalUncheckedError();
     269             : #endif
     270           0 :   }
     271             : 
     272           0 :   ErrorInfoBase *getPtr() const {
     273             :     return reinterpret_cast<ErrorInfoBase*>(
     274    13404869 :              reinterpret_cast<uintptr_t>(Payload) &
     275     1396334 :              ~static_cast<uintptr_t>(0x1));
     276             :   }
     277             : 
     278           0 :   void setPtr(ErrorInfoBase *EI) {
     279             : #if LLVM_ENABLE_ABI_BREAKING_CHECKS
     280             :     Payload = reinterpret_cast<ErrorInfoBase*>(
     281             :                 (reinterpret_cast<uintptr_t>(EI) &
     282             :                  ~static_cast<uintptr_t>(0x1)) |
     283             :                 (reinterpret_cast<uintptr_t>(Payload) & 0x1));
     284             : #else
     285       38467 :     Payload = EI;
     286             : #endif
     287           0 :   }
     288             : 
     289             :   bool getChecked() const {
     290             : #if LLVM_ENABLE_ABI_BREAKING_CHECKS
     291             :     return (reinterpret_cast<uintptr_t>(Payload) & 0x1) == 0;
     292             : #else
     293             :     return true;
     294             : #endif
     295             :   }
     296             : 
     297             :   void setChecked(bool V) {
     298     5319348 :     Payload = reinterpret_cast<ErrorInfoBase*>(
     299       95450 :                 (reinterpret_cast<uintptr_t>(Payload) &
     300     5816521 :                   ~static_cast<uintptr_t>(0x1)) |
     301     5356923 :                   (V ? 0 : 1));
     302             :   }
     303             : 
     304             :   std::unique_ptr<ErrorInfoBase> takePayload() {
     305         479 :     std::unique_ptr<ErrorInfoBase> Tmp(getPtr());
     306             :     setPtr(nullptr);
     307             :     setChecked(true);
     308             :     return Tmp;
     309             :   }
     310             : 
     311          33 :   friend raw_ostream &operator<<(raw_ostream &OS, const Error &E) {
     312          33 :     if (auto P = E.getPtr())
     313          32 :       P->log(OS);
     314             :     else
     315           1 :       OS << "success";
     316          33 :     return OS;
     317             :   }
     318             : 
     319             :   ErrorInfoBase *Payload = nullptr;
     320             : };
     321             : 
     322             : /// Subclass of Error for the sole purpose of identifying the success path in
     323             : /// the type system. This allows to catch invalid conversion to Expected<T> at
     324             : /// compile time.
     325             : class ErrorSuccess final : public Error {};
     326             : 
     327           0 : inline ErrorSuccess Error::success() { return ErrorSuccess(); }
     328             : 
     329             : /// Make a Error instance representing failure using the given error info
     330             : /// type.
     331         297 : template <typename ErrT, typename... ArgTs> Error make_error(ArgTs &&... Args) {
     332       33098 :   return Error(llvm::make_unique<ErrT>(std::forward<ArgTs>(Args)...));
     333             : }
     334           3 : 
     335           3 : /// Base class for user error types. Users should declare their error types
     336             : /// like:
     337           0 : ///
     338           0 : /// class MyError : public ErrorInfo<MyError> {
     339             : ///   ....
     340           0 : /// };
     341           0 : ///
     342             : /// This class provides an implementation of the ErrorInfoBase::kind
     343           1 : /// method, which is used by the Error RTTI system.
     344           1 : template <typename ThisErrT, typename ParentErrT = ErrorInfoBase>
     345         762 : class ErrorInfo : public ParentErrT {
     346           0 : public:
     347         159 :   using ParentErrT::ParentErrT; // inherit constructors
     348             : 
     349           0 :   static const void *classID() { return &ThisErrT::ID; }
     350           0 : 
     351           8 :   const void *dynamicClassID() const override { return &ThisErrT::ID; }
     352           2 : 
     353       71059 :   bool isA(const void *const ClassID) const override {
     354       71057 :     return ClassID == classID() || ParentErrT::isA(ClassID);
     355           0 :   }
     356        1413 : };
     357        1413 : 
     358           0 : /// Special ErrorInfo subclass representing a list of ErrorInfos.
     359          74 : /// Instances of this class are constructed by joinError.
     360          76 : class ErrorList final : public ErrorInfo<ErrorList> {
     361           0 :   // handleErrors needs to be able to iterate the payload list of an
     362          33 :   // ErrorList.
     363          35 :   template <typename... HandlerTs>
     364           0 :   friend Error handleErrors(Error E, HandlerTs &&... Handlers);
     365       64890 : 
     366       64890 :   // joinErrors is implemented in terms of join.
     367           0 :   friend Error joinErrors(Error, Error);
     368        3801 : 
     369        3801 : public:
     370           0 :   void log(raw_ostream &OS) const override {
     371         283 :     OS << "Multiple errors:\n";
     372         283 :     for (auto &ErrPayload : Payloads) {
     373           0 :       ErrPayload->log(OS);
     374         244 :       OS << "\n";
     375         244 :     }
     376           0 :   }
     377           2 : 
     378           2 :   std::error_code convertToErrorCode() const override;
     379           0 : 
     380           4 :   // Used by ErrorInfo::classID.
     381           4 :   static char ID;
     382           0 : 
     383           0 : private:
     384           0 :   ErrorList(std::unique_ptr<ErrorInfoBase> Payload1,
     385           0 :             std::unique_ptr<ErrorInfoBase> Payload2) {
     386          12 :     assert(!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() &&
     387          12 :            "ErrorList constructor payloads should be singleton errors");
     388           0 :     Payloads.push_back(std::move(Payload1));
     389         130 :     Payloads.push_back(std::move(Payload2));
     390         130 :   }
     391           0 : 
     392         115 :   static Error join(Error E1, Error E2) {
     393         115 :     if (!E1)
     394           0 :       return E2;
     395          10 :     if (!E2)
     396          10 :       return E1;
     397           2 :     if (E1.isA<ErrorList>()) {
     398           0 :       auto &E1List = static_cast<ErrorList &>(*E1.getPtr());
     399           0 :       if (E2.isA<ErrorList>()) {
     400           0 :         auto E2Payload = E2.takePayload();
     401           8 :         auto &E2List = static_cast<ErrorList &>(*E2Payload);
     402           8 :         for (auto &Payload : E2List.Payloads)
     403           0 :           E1List.Payloads.push_back(std::move(Payload));
     404         103 :       } else
     405         103 :         E1List.Payloads.push_back(E2.takePayload());
     406           6 : 
     407           2 :       return E1;
     408           0 :     }
     409           0 :     if (E2.isA<ErrorList>()) {
     410           0 :       auto &E2List = static_cast<ErrorList &>(*E2.getPtr());
     411           0 :       E2List.Payloads.insert(E2List.Payloads.begin(), E1.takePayload());
     412          31 :       return E2;
     413           6 :     }
     414           6 :     return Error(std::unique_ptr<ErrorList>(
     415           0 :         new ErrorList(E1.takePayload(), E2.takePayload())));
     416           6 :   }
     417           0 : 
     418           0 :   std::vector<std::unique_ptr<ErrorInfoBase>> Payloads;
     419          37 : };
     420          37 : 
     421           0 : /// Concatenate errors. The resulting Error is unchecked, and contains the
     422          37 : /// ErrorInfo(s), if any, contained in E1, followed by the
     423           0 : /// ErrorInfo(s), if any, contained in E2.
     424           0 : inline Error joinErrors(Error E1, Error E2) {
     425           0 :   return ErrorList::join(std::move(E1), std::move(E2));
     426           0 : }
     427          14 : 
     428           0 : /// Tagged union holding either a T or a Error.
     429           0 : ///
     430           0 : /// This class parallels ErrorOr, but replaces error_code with Error. Since
     431           0 : /// Error cannot be copied, this class replaces getError() with
     432           0 : /// takeError(). It also adds an bool errorIsA<ErrT>() method for testing the
     433           0 : /// error class type.
     434          27 : template <class T> class LLVM_NODISCARD Expected {
     435          27 :   template <class T1> friend class ExpectedAsOutParameter;
     436          21 :   template <class OtherT> friend class Expected;
     437          37 : 
     438           6 :   static const bool isRef = std::is_reference<T>::value;
     439           0 : 
     440           2 :   using wrap = std::reference_wrapper<typename std::remove_reference<T>::type>;
     441           0 : 
     442          62 :   using error_type = std::unique_ptr<ErrorInfoBase>;
     443           0 : 
     444           3 : public:
     445           8 :   using storage_type = typename std::conditional<isRef, wrap, T>::type;
     446          12 :   using value_type = T;
     447           2 : 
     448           0 : private:
     449           0 :   using reference = typename std::remove_reference<T>::type &;
     450           0 :   using const_reference = const typename std::remove_reference<T>::type &;
     451          37 :   using pointer = typename std::remove_reference<T>::type *;
     452          75 :   using const_pointer = const typename std::remove_reference<T>::type *;
     453           1 : 
     454           0 : public:
     455           0 :   /// Create an Expected<T> error value from the given Error.
     456           0 :   Expected(Error Err)
     457          20 :       : HasError(true)
     458           0 : #if LLVM_ENABLE_ABI_BREAKING_CHECKS
     459           0 :         // Expected is unchecked upon construction in Debug builds.
     460           0 :         , Unchecked(true)
     461             : #endif
     462           0 :   {
     463             :     assert(Err && "Cannot create Expected<T> from Error success value.");
     464             :     new (getErrorStorage()) error_type(Err.takePayload());
     465             :   }
     466          44 : 
     467          26 :   /// Forbid to convert from Error::success() implicitly, this avoids having
     468           1 :   /// Expected<T> foo() { return Error::success(); } which compiles otherwise
     469       57372 :   /// but triggers the assertion above.
     470             :   Expected(ErrorSuccess) = delete;
     471           0 : 
     472        2070 :   /// Create an Expected<T> success value from the given OtherT value, which
     473             :   /// must be convertible to T.
     474          26 :   template <typename OtherT>
     475         361 :   Expected(OtherT &&Val,
     476             :            typename std::enable_if<std::is_convertible<OtherT, T>::value>::type
     477          30 :                * = nullptr)
     478         187 :       : HasError(false)
     479             : #if LLVM_ENABLE_ABI_BREAKING_CHECKS
     480           2 :         // Expected is unchecked upon construction in Debug builds.
     481           4 :         , Unchecked(true)
     482             : #endif
     483           0 :   {
     484         937 :     new (getStorage()) storage_type(std::forward<OtherT>(Val));
     485             :   }
     486           0 : 
     487       17898 :   /// Move construct an Expected<T> value.
     488             :   Expected(Expected &&Other) { moveConstruct(std::move(Other)); }
     489           0 : 
     490       89921 :   /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT
     491             :   /// must be convertible to T.
     492             :   template <class OtherT>
     493      703153 :   Expected(Expected<OtherT> &&Other,
     494         915 :            typename std::enable_if<std::is_convertible<OtherT, T>::value>::type
     495           0 :                * = nullptr) {
     496     1414136 :     moveConstruct(std::move(Other));
     497         120 :   }
     498           6 : 
     499   417212114 :   /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT
     500         880 :   /// isn't convertible to T.
     501           1 :   template <class OtherT>
     502     1495025 :   explicit Expected(
     503         293 :       Expected<OtherT> &&Other,
     504           0 :       typename std::enable_if<!std::is_convertible<OtherT, T>::value>::type * =
     505      224569 :           nullptr) {
     506         298 :     moveConstruct(std::move(Other));
     507           0 :   }
     508       18802 : 
     509         177 :   /// Move-assign from another Expected<T>.
     510           0 :   Expected &operator=(Expected &&Other) {
     511        8932 :     moveAssign(std::move(Other));
     512           0 :     return *this;
     513           3 :   }
     514         456 : 
     515         306 :   /// Destroy an Expected<T>.
     516           0 :   ~Expected() {
     517        1381 :     assertIsChecked();
     518         327 :     if (!HasError)
     519           0 :       getStorage()->~storage_type();
     520         174 :     else
     521         327 :       getErrorStorage()->~error_type();
     522           0 :   }
     523         154 : 
     524           0 :   /// Return false if there is an error.
     525      490394 :   explicit operator bool() {
     526          78 : #if LLVM_ENABLE_ABI_BREAKING_CHECKS
     527      495971 :     Unchecked = HasError;
     528       45226 : #endif
     529         378 :     return !HasError;
     530      152822 :   }
     531      573186 : 
     532         452 :   /// Returns a reference to the stored T value.
     533   324206191 :   reference get() {
     534       76820 :     assertIsChecked();
     535        9110 :     return *getStorage();
     536      367896 :   }
     537    67342866 : 
     538     1417507 :   /// Returns a const reference to the stored T value.
     539        7222 :   const_reference get() const {
     540       96052 :     assertIsChecked();
     541       24848 :     return const_cast<Expected<T> *>(this)->get();
     542       44383 :   }
     543       10193 : 
     544   174326966 :   /// Check that this Expected<T> is an error of type ErrT.
     545      146895 :   template <typename ErrT> bool errorIsA() const {
     546       10988 :     return HasError && (*getErrorStorage())->template isA<ErrT>();
     547       44019 :   }
     548       19211 : 
     549       18871 :   /// Take ownership of the stored error.
     550        7220 :   /// After calling this the Expected<T> is in an indeterminate state that can
     551       41505 :   /// only be safely destructed. No further calls (beside the destructor) should
     552        7576 :   /// be made on the Expected<T> vaule.
     553       27941 :   Error takeError() {
     554        4742 : #if LLVM_ENABLE_ABI_BREAKING_CHECKS
     555       28316 :     Unchecked = false;
     556      119235 : #endif
     557       20617 :     return HasError ? Error(std::move(*getErrorStorage())) : Error::success();
     558      984141 :   }
     559       13487 : 
     560       12123 :   /// Returns a pointer to the stored T value.
     561        9396 :   pointer operator->() {
     562       12559 :     assertIsChecked();
     563       12482 :     return toPointer(getStorage());
     564        6231 :   }
     565      356371 : 
     566       11159 :   /// Returns a const pointer to the stored T value.
     567        5523 :   const_pointer operator->() const {
     568      380260 :     assertIsChecked();
     569       41696 :     return toPointer(getStorage());
     570       17562 :   }
     571       16334 : 
     572     2450676 :   /// Returns a reference to the stored T value.
     573       12275 :   reference operator*() {
     574        5739 :     assertIsChecked();
     575       16710 :     return *getStorage();
     576        6632 :   }
     577        6650 : 
     578        3104 :   /// Returns a const reference to the stored T value.
     579        4926 :   const_reference operator*() const {
     580        1130 :     assertIsChecked();
     581       16364 :     return *getStorage();
     582        6726 :   }
     583       32338 : 
     584         882 : private:
     585       92892 :   template <class T1>
     586        9036 :   static bool compareThisIfSameType(const T1 &a, const T1 &b) {
     587        4038 :     return &a == &b;
     588         233 :   }
     589       34750 : 
     590        2489 :   template <class T1, class T2>
     591        5468 :   static bool compareThisIfSameType(const T1 &a, const T2 &b) {
     592         106 :     return false;
     593        3067 :   }
     594           2 : 
     595           6 :   template <class OtherT> void moveConstruct(Expected<OtherT> &&Other) {
     596         120 :     HasError = Other.HasError;
     597       92568 : #if LLVM_ENABLE_ABI_BREAKING_CHECKS
     598        1333 :     Unchecked = true;
     599         125 :     Other.Unchecked = false;
     600   239354611 : #endif
     601         478 : 
     602         259 :     if (!HasError)
     603          16 :       new (getStorage()) storage_type(std::move(*Other.getStorage()));
     604        1409 :     else
     605         295 :       new (getErrorStorage()) error_type(std::move(*Other.getErrorStorage()));
     606          93 :   }
     607         178 : 
     608         210 :   template <class OtherT> void moveAssign(Expected<OtherT> &&Other) {
     609           4 :     assertIsChecked();
     610           2 : 
     611         306 :     if (compareThisIfSameType(*this, Other))
     612         153 :       return;
     613           7 : 
     614         286 :     this->~Expected();
     615          37 :     new (this) Expected(std::move(Other));
     616          15 :   }
     617         245 : 
     618          43 :   pointer toPointer(pointer Val) { return Val; }
     619         124 : 
     620         323 :   const_pointer toPointer(const_pointer Val) const { return Val; }
     621        1134 : 
     622         656 :   pointer toPointer(wrap *Val) { return &Val->get(); }
     623         468 : 
     624       92324 :   const_pointer toPointer(const wrap *Val) const { return &Val->get(); }
     625       14641 : 
     626         232 :   storage_type *getStorage() {
     627         356 :     assert(!HasError && "Cannot get value when an error exists!");
     628       17446 :     return reinterpret_cast<storage_type *>(TStorage.buffer);
     629         198 :   }
     630           8 : 
     631       14781 :   const storage_type *getStorage() const {
     632        6194 :     assert(!HasError && "Cannot get value when an error exists!");
     633         692 :     return reinterpret_cast<const storage_type *>(TStorage.buffer);
     634         494 :   }
     635         926 : 
     636          22 :   error_type *getErrorStorage() {
     637        9378 :     assert(HasError && "Cannot get error when a value exists!");
     638          26 :     return reinterpret_cast<error_type *>(ErrorStorage.buffer);
     639        4757 :   }
     640      373965 : 
     641         233 :   const error_type *getErrorStorage() const {
     642         815 :     assert(HasError && "Cannot get error when a value exists!");
     643        2515 :     return reinterpret_cast<const error_type *>(ErrorStorage.buffer);
     644         145 :   }
     645        4083 : 
     646        2343 :   // Used by ExpectedAsOutParameter to reset the checked flag.
     647         392 :   void setUnchecked() {
     648         548 : #if LLVM_ENABLE_ABI_BREAKING_CHECKS
     649        9279 :     Unchecked = true;
     650           0 : #endif
     651         105 :   }
     652         140 : 
     653         154 : #if LLVM_ENABLE_ABI_BREAKING_CHECKS
     654        2282 :   LLVM_ATTRIBUTE_NORETURN
     655        9607 :   LLVM_ATTRIBUTE_NOINLINE
     656          23 :   void fatalUncheckedExpected() const {
     657        2051 :     dbgs() << "Expected<T> must be checked before access or destruction.\n";
     658        6654 :     if (HasError) {
     659         135 :       dbgs() << "Unchecked Expected<T> contained error:\n";
     660         553 :       (*getErrorStorage())->log(dbgs());
     661         599 :     } else
     662          40 :       dbgs() << "Expected<T> value was in success state. (Note: Expected<T> "
     663         657 :                 "values in success mode must still be checked prior to being "
     664        9244 :                 "destroyed).\n";
     665          42 :     abort();
     666         123 :   }
     667        9078 : #endif
     668        1578 : 
     669         827 :   void assertIsChecked() {
     670        2385 : #if LLVM_ENABLE_ABI_BREAKING_CHECKS
     671         588 :     if (LLVM_UNLIKELY(Unchecked))
     672         665 :       fatalUncheckedExpected();
     673        6559 : #endif
     674         513 :   }
     675        2812 : 
     676             :   union {
     677         255 :     AlignedCharArrayUnion<storage_type> TStorage;
     678         504 :     AlignedCharArrayUnion<error_type> ErrorStorage;
     679         107 :   };
     680        2972 :   bool HasError : 1;
     681        5716 : #if LLVM_ENABLE_ABI_BREAKING_CHECKS
     682         224 :   bool Unchecked : 1;
     683           7 : #endif
     684         122 : };
     685           0 : 
     686          10 : /// Report a serious error, calling any installed error handler. See
     687          78 : /// ErrorHandling.h.
     688           1 : LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err,
     689          12 :                                                 bool gen_crash_diag = true);
     690       11001 : 
     691           4 : /// Report a fatal error if Err is a failure value.
     692          11 : ///
     693          10 : /// This function can be used to wrap calls to fallible functions ONLY when it
     694             : /// is known that the Error will always be a success value. E.g.
     695        9372 : ///
     696         238 : ///   @code{.cpp}
     697           0 : ///   // foo only attempts the fallible operation if DoFallibleOperation is
     698           1 : ///   // true. If DoFallibleOperation is false then foo always returns
     699       12762 : ///   // Error::success().
     700          14 : ///   Error foo(bool DoFallibleOperation);
     701           0 : ///
     702           2 : ///   cantFail(foo(false));
     703          48 : ///   @endcode
     704           0 : inline void cantFail(Error Err, const char *Msg = nullptr) {
     705          14 :   if (Err) {
     706          12 :     if (!Msg)
     707           4 :       Msg = "Failure value returned from cantFail wrapped call";
     708         229 :     llvm_unreachable(Msg);
     709         464 :   }
     710          10 : }
     711           0 : 
     712          36 : /// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and
     713         654 : /// returns the contained value.
     714        1911 : ///
     715          35 : /// This function can be used to wrap calls to fallible functions ONLY when it
     716          16 : /// is known that the Error will always be a success value. E.g.
     717       13515 : ///
     718           4 : ///   @code{.cpp}
     719         672 : ///   // foo only attempts the fallible operation if DoFallibleOperation is
     720         673 : ///   // true. If DoFallibleOperation is false then foo always returns an int.
     721           0 : ///   Expected<int> foo(bool DoFallibleOperation);
     722           0 : ///
     723       45753 : ///   int X = cantFail(foo(false));
     724           0 : ///   @endcode
     725         327 : template <typename T>
     726        3932 : T cantFail(Expected<T> ValOrErr, const char *Msg = nullptr) {
     727           0 :   if (ValOrErr)
     728         642 :     return std::move(*ValOrErr);
     729           0 :   else {
     730         527 :     if (!Msg)
     731          26 :       Msg = "Failure value returned from cantFail wrapped call";
     732          85 :     llvm_unreachable(Msg);
     733           0 :   }
     734         201 : }
     735           0 : 
     736      892514 : /// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and
     737      892639 : /// returns the contained reference.
     738           2 : ///
     739           0 : /// This function can be used to wrap calls to fallible functions ONLY when it
     740           0 : /// is known that the Error will always be a success value. E.g.
     741          40 : ///
     742           2 : ///   @code{.cpp}
     743         448 : ///   // foo only attempts the fallible operation if DoFallibleOperation is
     744        8449 : ///   // true. If DoFallibleOperation is false then foo always returns a Bar&.
     745           2 : ///   Expected<Bar&> foo(bool DoFallibleOperation);
     746         344 : ///
     747           4 : ///   Bar &X = cantFail(foo(false));
     748         300 : ///   @endcode
     749         609 : template <typename T>
     750          40 : T& cantFail(Expected<T&> ValOrErr, const char *Msg = nullptr) {
     751           3 :   if (ValOrErr)
     752           3 :     return *ValOrErr;
     753           0 :   else {
     754         311 :     if (!Msg)
     755           8 :       Msg = "Failure value returned from cantFail wrapped call";
     756         457 :     llvm_unreachable(Msg);
     757         221 :   }
     758         396 : }
     759         296 : 
     760           0 : /// Helper for testing applicability of, and applying, handlers for
     761           0 : /// ErrorInfo types.
     762           0 : template <typename HandlerT>
     763           0 : class ErrorHandlerTraits
     764         491 :     : public ErrorHandlerTraits<decltype(
     765          67 :           &std::remove_reference<HandlerT>::type::operator())> {};
     766         175 : 
     767           1 : // Specialization functions of the form 'Error (const ErrT&)'.
     768           0 : template <typename ErrT> class ErrorHandlerTraits<Error (&)(ErrT &)> {
     769           4 : public:
     770          28 :   static bool appliesTo(const ErrorInfoBase &E) {
     771       11611 :     return E.template isA<ErrT>();
     772         174 :   }
     773          30 : 
     774          11 :   template <typename HandlerT>
     775           0 :   static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
     776         267 :     assert(appliesTo(*E) && "Applying incorrect handler");
     777           0 :     return H(static_cast<ErrT &>(*E));
     778           0 :   }
     779          78 : };
     780         620 : 
     781           4 : // Specialization functions of the form 'void (const ErrT&)'.
     782          78 : template <typename ErrT> class ErrorHandlerTraits<void (&)(ErrT &)> {
     783           0 : public:
     784           7 :   static bool appliesTo(const ErrorInfoBase &E) {
     785          18 :     return E.template isA<ErrT>();
     786           0 :   }
     787           0 : 
     788          24 :   template <typename HandlerT>
     789           0 :   static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
     790           3 :     assert(appliesTo(*E) && "Applying incorrect handler");
     791          24 :     H(static_cast<ErrT &>(*E));
     792        7966 :     return Error::success();
     793           0 :   }
     794           0 : };
     795          20 : 
     796       29104 : /// Specialization for functions of the form 'Error (std::unique_ptr<ErrT>)'.
     797           0 : template <typename ErrT>
     798         205 : class ErrorHandlerTraits<Error (&)(std::unique_ptr<ErrT>)> {
     799         206 : public:
     800          79 :   static bool appliesTo(const ErrorInfoBase &E) {
     801           0 :     return E.template isA<ErrT>();
     802          96 :   }
     803         760 : 
     804           0 :   template <typename HandlerT>
     805         249 :   static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
     806          61 :     assert(appliesTo(*E) && "Applying incorrect handler");
     807           0 :     std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release()));
     808          80 :     return H(std::move(SubE));
     809         323 :   }
     810           0 : };
     811           0 : 
     812           0 : /// Specialization for functions of the form 'void (std::unique_ptr<ErrT>)'.
     813           0 : template <typename ErrT>
     814           0 : class ErrorHandlerTraits<void (&)(std::unique_ptr<ErrT>)> {
     815           0 : public:
     816           0 :   static bool appliesTo(const ErrorInfoBase &E) {
     817           0 :     return E.template isA<ErrT>();
     818          27 :   }
     819           0 : 
     820           0 :   template <typename HandlerT>
     821           1 :   static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
     822           0 :     assert(appliesTo(*E) && "Applying incorrect handler");
     823           9 :     std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release()));
     824           5 :     H(std::move(SubE));
     825           0 :     return Error::success();
     826           3 :   }
     827           0 : };
     828           0 : 
     829         464 : // Specialization for member functions of the form 'RetT (const ErrT&)'.
     830         114 : template <typename C, typename RetT, typename ErrT>
     831         637 : class ErrorHandlerTraits<RetT (C::*)(ErrT &)>
     832           7 :     : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
     833         114 : 
     834         114 : // Specialization for member functions of the form 'RetT (const ErrT&) const'.
     835          59 : template <typename C, typename RetT, typename ErrT>
     836          23 : class ErrorHandlerTraits<RetT (C::*)(ErrT &) const>
     837           0 :     : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
     838           1 : 
     839           0 : // Specialization for member functions of the form 'RetT (const ErrT&)'.
     840           0 : template <typename C, typename RetT, typename ErrT>
     841           1 : class ErrorHandlerTraits<RetT (C::*)(const ErrT &)>
     842           5 :     : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
     843           0 : 
     844           1 : // Specialization for member functions of the form 'RetT (const ErrT&) const'.
     845          69 : template <typename C, typename RetT, typename ErrT>
     846           9 : class ErrorHandlerTraits<RetT (C::*)(const ErrT &) const>
     847           0 :     : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
     848           1 : 
     849           0 : /// Specialization for member functions of the form
     850           3 : /// 'RetT (std::unique_ptr<ErrT>)'.
     851          69 : template <typename C, typename RetT, typename ErrT>
     852           0 : class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>)>
     853           0 :     : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {};
     854           0 : 
     855           0 : /// Specialization for member functions of the form
     856           0 : /// 'RetT (std::unique_ptr<ErrT>) const'.
     857           1 : template <typename C, typename RetT, typename ErrT>
     858           0 : class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>) const>
     859           0 :     : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {};
     860           3 : 
     861           0 : inline Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload) {
     862           0 :   return Error(std::move(Payload));
     863           0 : }
     864           0 : 
     865           0 : template <typename HandlerT, typename... HandlerTs>
     866           0 : Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload,
     867           0 :                       HandlerT &&Handler, HandlerTs &&... Handlers) {
     868           0 :   if (ErrorHandlerTraits<HandlerT>::appliesTo(*Payload))
     869           0 :     return ErrorHandlerTraits<HandlerT>::apply(std::forward<HandlerT>(Handler),
     870           7 :                                                std::move(Payload));
     871           0 :   return handleErrorImpl(std::move(Payload),
     872           0 :                          std::forward<HandlerTs>(Handlers)...);
     873           0 : }
     874           0 : 
     875         203 : /// Pass the ErrorInfo(s) contained in E to their respective handlers. Any
     876           0 : /// unhandled errors (or Errors returned by handlers) are re-concatenated and
     877         203 : /// returned.
     878        2784 : /// Because this function returns an error, its result must also be checked
     879         228 : /// or returned. If you intend to handle all errors use handleAllErrors
     880        2780 : /// (which returns void, and will abort() on unhandled errors) instead.
     881          62 : template <typename... HandlerTs>
     882        2626 : Error handleErrors(Error E, HandlerTs &&... Hs) {
     883          63 :   if (!E)
     884         352 :     return Error::success();
     885           5 : 
     886         433 :   std::unique_ptr<ErrorInfoBase> Payload = E.takePayload();
     887          49 : 
     888         147 :   if (Payload->isA<ErrorList>()) {
     889          49 :     ErrorList &List = static_cast<ErrorList &>(*Payload);
     890          66 :     Error R;
     891        1664 :     for (auto &P : List.Payloads)
     892        1673 :       R = ErrorList::join(
     893           3 :           std::move(R),
     894        8214 :           handleErrorImpl(std::move(P), std::forward<HandlerTs>(Hs)...));
     895        7706 :     return R;
     896         536 :   }
     897         257 : 
     898          93 :   return handleErrorImpl(std::move(Payload), std::forward<HandlerTs>(Hs)...);
     899           0 : }
     900        2444 : 
     901          12 : /// Behaves the same as handleErrors, except that by contract all errors
     902         321 : /// *must* be handled by the given handlers (i.e. there must be no remaining
     903        3826 : /// errors after running the handlers, or llvm_unreachable is called).
     904        3907 : template <typename... HandlerTs>
     905         341 : void handleAllErrors(Error E, HandlerTs &&... Handlers) {
     906         149 :   cantFail(handleErrors(std::move(E), std::forward<HandlerTs>(Handlers)...));
     907         735 : }
     908           8 : 
     909          57 : /// Check that E is a non-error, then drop it.
     910        4400 : /// If E is an error, llvm_unreachable will be called.
     911          59 : inline void handleAllErrors(Error E) {
     912         395 :   cantFail(std::move(E));
     913         175 : }
     914        2018 : 
     915        3326 : /// Handle any errors (if present) in an Expected<T>, then try a recovery path.
     916        2102 : ///
     917        7748 : /// If the incoming value is a success value it is returned unmodified. If it
     918       15536 : /// is a failure value then it the contained error is passed to handleErrors.
     919        7930 : /// If handleErrors is able to handle the error then the RecoveryPath functor
     920         554 : /// is called to supply the final result. If handleErrors is not able to
     921        8656 : /// handle all errors then the unhandled errors are returned.
     922        8904 : ///
     923          38 : /// This utility enables the follow pattern:
     924          29 : ///
     925          55 : ///   @code{.cpp}
     926        9481 : ///   enum FooStrategy { Aggressive, Conservative };
     927       13455 : ///   Expected<Foo> foo(FooStrategy S);
     928        4146 : ///
     929          26 : ///   auto ResultOrErr =
     930         583 : ///     handleExpected(
     931           2 : ///       foo(Aggressive),
     932        1062 : ///       []() { return foo(Conservative); },
     933          49 : ///       [](AggressiveStrategyError&) {
     934          43 : ///         // Implicitly conusme this - we'll recover by using a conservative
     935         123 : ///         // strategy.
     936         319 : ///       });
     937         709 : ///
     938          91 : ///   @endcode
     939         394 : template <typename T, typename RecoveryFtor, typename... HandlerTs>
     940         663 : Expected<T> handleExpected(Expected<T> ValOrErr, RecoveryFtor &&RecoveryPath,
     941         834 :                            HandlerTs &&... Handlers) {
     942        1354 :   if (ValOrErr)
     943         661 :     return ValOrErr;
     944       13547 : 
     945       21918 :   if (auto Err = handleErrors(ValOrErr.takeError(),
     946        8774 :                               std::forward<HandlerTs>(Handlers)...))
     947          29 :     return std::move(Err);
     948          73 : 
     949         469 :   return RecoveryPath();
     950         966 : }
     951         419 : 
     952         334 : /// Log all errors (if any) in E to OS. If there are any errors, ErrorBanner
     953         439 : /// will be printed before the first one is logged. A newline will be printed
     954          69 : /// after each error.
     955         199 : ///
     956         720 : /// This is useful in the base level of your program to allow clean termination
     957       29827 : /// (allowing clean deallocation of resources, etc.), while reporting error
     958        1207 : /// information to the user.
     959       28994 : void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner);
     960         353 : 
     961          75 : /// Write all error messages (if any) in E to a string. The newline character
     962         856 : /// is used to separate error messages.
     963        1288 : inline std::string toString(Error E) {
     964          15 :   SmallVector<std::string, 2> Errors;
     965       26479 :   handleAllErrors(std::move(E), [&Errors](const ErrorInfoBase &EI) {
     966         514 :     Errors.push_back(EI.message());
     967       26893 :   });
     968        2068 :   return join(Errors.begin(), Errors.end(), "\n");
     969         238 : }
     970         293 : 
     971         527 : /// Consume a Error without doing anything. This method should be used
     972         284 : /// only where an error can be considered a reasonable and expected return
     973        3708 : /// value.
     974         168 : ///
     975        2673 : /// Uses of this method are potentially indicative of design problems: If it's
     976         716 : /// legitimate to do nothing while processing an "error", the error-producer
     977         463 : /// might be more clearly refactored to return an Optional<T>.
     978        1582 : inline void consumeError(Error Err) {
     979          74 :   handleAllErrors(std::move(Err), [](const ErrorInfoBase &) {});
     980        1059 : }
     981        1411 : 
     982        1047 : /// Helper for converting an Error to a bool.
     983         375 : ///
     984         108 : /// This method returns true if Err is in an error state, or false if it is
     985         195 : /// in a success state.  Puts Err in a checked state in both cases (unlike
     986        1408 : /// Error::operator bool(), which only does this for success states).
     987         347 : inline bool errorToBool(Error Err) {
     988         280 :   bool IsError = static_cast<bool>(Err);
     989       28978 :   if (IsError)
     990       53349 :     consumeError(std::move(Err));
     991       24506 :   return IsError;
     992       13382 : }
     993        7471 : 
     994        7474 : /// Helper for Errors used as out-parameters.
     995       28995 : ///
     996        1604 : /// This helper is for use with the Error-as-out-parameter idiom, where an error
     997         285 : /// is passed to a function or method by reference, rather than being returned.
     998        1602 : /// In such cases it is helpful to set the checked bit on entry to the function
     999        1035 : /// so that the error can be written to (unchecked Errors abort on assignment)
    1000         606 : /// and clear the checked bit on exit so that clients cannot accidentally forget
    1001         823 : /// to check the result. This helper performs these actions automatically using
    1002        2570 : /// RAII:
    1003        2395 : ///
    1004        2130 : ///   @code{.cpp}
    1005       58239 : ///   Result foo(Error &Err) {
    1006         562 : ///     ErrorAsOutParameter ErrAsOutParam(&Err); // 'Checked' flag set
    1007       26656 : ///     // <body of foo>
    1008       26816 : ///     // <- 'Checked' flag auto-cleared when ErrAsOutParam is destructed.
    1009         999 : ///   }
    1010         498 : ///   @endcode
    1011         740 : ///
    1012        1546 : /// ErrorAsOutParameter takes an Error* rather than Error& so that it can be
    1013       27112 : /// used with optional Errors (Error pointers that are allowed to be null). If
    1014         458 : /// ErrorAsOutParameter took an Error reference, an instance would have to be
    1015         487 : /// created inside every condition that verified that Error was non-null. By
    1016         258 : /// taking an Error pointer we can just create one instance at the top of the
    1017           6 : /// function.
    1018           8 : class ErrorAsOutParameter {
    1019          17 : public:
    1020           0 :   ErrorAsOutParameter(Error *Err) : Err(Err) {
    1021        5696 :     // Raise the checked bit if Err is success.
    1022       11257 :     if (Err)
    1023       58560 :       (void)!!*Err;
    1024        5205 :   }
    1025       13003 : 
    1026       19409 :   ~ErrorAsOutParameter() {
    1027       12847 :     // Clear the checked bit.
    1028        5675 :     if (Err && !*Err)
    1029        8358 :       *Err = Error::success();
    1030        7507 :   }
    1031        2641 : 
    1032          45 : private:
    1033         419 :   Error *Err;
    1034         793 : };
    1035         453 : 
    1036          13 : /// Helper for Expected<T>s used as out-parameters.
    1037         322 : ///
    1038         150 : /// See ErrorAsOutParameter.
    1039         428 : template <typename T>
    1040         751 : class ExpectedAsOutParameter {
    1041        5681 : public:
    1042         413 :   ExpectedAsOutParameter(Expected<T> *ValOrErr)
    1043        1169 :     : ValOrErr(ValOrErr) {
    1044         483 :     if (ValOrErr)
    1045         346 :       (void)!!*ValOrErr;
    1046         532 :   }
    1047          86 : 
    1048       29047 :   ~ExpectedAsOutParameter() {
    1049       57966 :     if (ValOrErr)
    1050       29104 :       ValOrErr->setUnchecked();
    1051       26622 :   }
    1052       52862 : 
    1053       27160 : private:
    1054        3735 :   Expected<T> *ValOrErr;
    1055        6027 : };
    1056        2727 : 
    1057          38 : /// This class wraps a std::error_code in a Error.
    1058        5347 : ///
    1059        5656 : /// This is useful if you're writing an interface that returns a Error
    1060        5926 : /// (or Expected) and you want to call code that still returns
    1061         300 : /// std::error_codes.
    1062           4 : class ECError : public ErrorInfo<ECError> {
    1063          10 :   friend Error errorCodeToError(std::error_code);
    1064         118 : 
    1065         114 : public:
    1066         235 :   void setErrorCode(std::error_code EC) { this->EC = EC; }
    1067         110 :   std::error_code convertToErrorCode() const override { return EC; }
    1068         100 :   void log(raw_ostream &OS) const override { OS << EC.message(); }
    1069          11 : 
    1070        7481 :   // Used by ErrorInfo::classID.
    1071       14961 :   static char ID;
    1072        7480 : 
    1073        7478 : protected:
    1074       14938 :   ECError() = default;
    1075        7520 :   ECError(std::error_code EC) : EC(EC) {}
    1076          20 : 
    1077        4265 :   std::error_code EC;
    1078        4253 : };
    1079        4607 : 
    1080          23 : /// The value returned by this function can be returned from convertToErrorCode
    1081        1524 : /// for Error values where no sensible translation to std::error_code exists.
    1082         197 : /// It should only be used in this situation, and should never be used where a
    1083         220 : /// sensible conversion to std::error_code is available, as attempts to convert
    1084          17 : /// to/from this error will result in a fatal error. (i.e. it is a programmatic
    1085       14416 : ///error to try to convert such a value).
    1086       23229 : std::error_code inconvertibleErrorCode();
    1087       12062 : 
    1088          30 : /// Helper for converting an std::error_code to a Error.
    1089          27 : Error errorCodeToError(std::error_code EC);
    1090          13 : 
    1091       11860 : /// Helper for converting an ECError to a std::error_code.
    1092       23234 : ///
    1093       11827 : /// This method requires that Err be Error() or an ECError, otherwise it
    1094          37 : /// will trigger a call to abort().
    1095         435 : std::error_code errorToErrorCode(Error Err);
    1096          35 : 
    1097         163 : /// Convert an ErrorOr<T> to an Expected<T>.
    1098           1 : template <typename T> Expected<T> errorOrToExpected(ErrorOr<T> &&EO) {
    1099        5827 :   if (auto EC = EO.getError())
    1100          18 :     return errorCodeToError(EC);
    1101          14 :   return std::move(*EO);
    1102          15 : }
    1103         228 : 
    1104         110 : /// Convert an Expected<T> to an ErrorOr<T>.
    1105        9527 : template <typename T> ErrorOr<T> expectedToErrorOr(Expected<T> &&E) {
    1106           7 :   if (auto Err = E.takeError())
    1107          79 :     return errorToErrorCode(std::move(Err));
    1108          52 :   return std::move(*E);
    1109           2 : }
    1110         217 : 
    1111           2 : /// This class wraps a string in an Error.
    1112        2609 : ///
    1113        2611 : /// StringError is useful in cases where the client is not expected to be able
    1114        5226 : /// to consume the specific error message programmatically (for example, if the
    1115         217 : /// error message is to be presented to the user).
    1116         215 : ///
    1117        2608 : /// StringError can also be used when additional information is to be printed
    1118          25 : /// along with a error_code message. Depending on the constructor called, this
    1119          28 : /// class can either display:
    1120          20 : ///    1. the error_code message (ECError behavior)
    1121         221 : ///    2. a string
    1122         126 : ///    3. the error_code message and a string
    1123          38 : ///
    1124          74 : /// These behaviors are useful when subtyping is required; for example, when a
    1125          96 : /// specific library needs an explicit error type. In the example below,
    1126          51 : /// PDBError is derived from StringError:
    1127       26363 : ///
    1128       26627 : ///   @code{.cpp}
    1129       26369 : ///   Expected<int> foo() {
    1130          61 : ///      return llvm::make_error<PDBError>(pdb_error_code::dia_failed_loading,
    1131         430 : ///                                        "Additional information");
    1132           0 : ///   }
    1133         226 : ///   @endcode
    1134         241 : ///
    1135           0 : class StringError : public ErrorInfo<StringError> {
    1136          20 : public:
    1137          20 :   static char ID;
    1138           2 : 
    1139         367 :   // Prints EC + S and converts to EC
    1140           2 :   StringError(std::error_code EC, const Twine &S = Twine());
    1141          35 : 
    1142          66 :   // Prints S and converts to EC
    1143          61 :   StringError(const Twine &S, std::error_code EC);
    1144           0 : 
    1145           0 :   void log(raw_ostream &OS) const override;
    1146          45 :   std::error_code convertToErrorCode() const override;
    1147         115 : 
    1148           0 :   const std::string &getMessage() const { return Msg; }
    1149        1891 : 
    1150        1461 : private:
    1151        1461 :   std::string Msg;
    1152         934 :   std::error_code EC;
    1153         924 :   const bool PrintMsgOnly = false;
    1154           7 : };
    1155          40 : 
    1156          37 : /// Create formatted StringError object.
    1157          74 : template <typename... Ts>
    1158           0 : Error createStringError(std::error_code EC, char const *Fmt,
    1159           0 :                         const Ts &... Vals) {
    1160          40 :   std::string Buffer;
    1161           0 :   raw_string_ostream Stream(Buffer);
    1162           0 :   Stream << format(Fmt, Vals...);
    1163          14 :   return make_error<StringError>(Stream.str(), EC);
    1164           0 : }
    1165           0 : 
    1166           1 : Error createStringError(std::error_code EC, char const *Msg);
    1167         410 : 
    1168           1 : /// This class wraps a filename and another Error.
    1169           0 : ///
    1170          44 : /// In some cases, an error needs to live along a 'source' name, in order to
    1171          37 : /// show more detailed information to the user.
    1172          37 : class FileError final : public ErrorInfo<FileError> {
    1173         911 : 
    1174         216 :   friend Error createFileError(std::string, Error);
    1175         431 : 
    1176         307 : public:
    1177         426 :   void log(raw_ostream &OS) const override {
    1178         568 :     assert(Err && !FileName.empty() && "Trying to log after takeError().");
    1179         246 :     OS << "'" << FileName << "': ";
    1180          33 :     Err->log(OS);
    1181          44 :   }
    1182          21 : 
    1183          12 :   Error takeError() { return Error(std::move(Err)); }
    1184          26 : 
    1185          12 :   std::error_code convertToErrorCode() const override;
    1186           0 : 
    1187           5 :   // Used by ErrorInfo::classID.
    1188           1 :   static char ID;
    1189           1 : 
    1190         707 : private:
    1191          18 :   FileError(std::string F, std::unique_ptr<ErrorInfoBase> E) {
    1192          14 :     assert(E && "Cannot create FileError from Error success value.");
    1193          24 :     assert(!F.empty() &&
    1194           5 :            "The file name provided to FileError must not be empty.");
    1195          91 :     FileName = F;
    1196         134 :     Err = std::move(E);
    1197           5 :   }
    1198          10 : 
    1199           5 :   static Error build(std::string F, Error E) {
    1200           0 :     return Error(std::unique_ptr<FileError>(new FileError(F, E.takePayload())));
    1201          21 :   }
    1202           0 : 
    1203         703 :   std::string FileName;
    1204          21 :   std::unique_ptr<ErrorInfoBase> Err;
    1205          42 : };
    1206          21 : 
    1207           0 : /// Concatenate a source file path and/or name with an Error. The resulting
    1208          15 : /// Error is unchecked.
    1209           0 : inline Error createFileError(std::string F, Error E) {
    1210           0 :   return FileError::build(F, std::move(E));
    1211          15 : }
    1212          30 : 
    1213          15 : Error createFileError(std::string F, ErrorSuccess) = delete;
    1214           1 : 
    1215          16 : /// Helper for check-and-exit error handling.
    1216           2 : ///
    1217           0 : /// For tool use only. NOT FOR USE IN LIBRARY CODE.
    1218          16 : ///
    1219          32 : class ExitOnError {
    1220          16 : public:
    1221           0 :   /// Create an error on exit helper.
    1222          22 :   ExitOnError(std::string Banner = "", int DefaultErrorExitCode = 1)
    1223          32 :       : Banner(std::move(Banner)),
    1224           0 :         GetExitCode([=](const Error &) { return DefaultErrorExitCode; }) {}
    1225          22 : 
    1226          44 :   /// Set the banner string for any errors caught by operator().
    1227          22 :   void setBanner(std::string Banner) { this->Banner = std::move(Banner); }
    1228           0 : 
    1229          64 :   /// Set the exit-code mapper function.
    1230           0 :   void setExitCodeMapper(std::function<int(const Error &)> GetExitCode) {
    1231           0 :     this->GetExitCode = std::move(GetExitCode);
    1232         162 :   }
    1233           4 : 
    1234          26 :   /// Check Err. If it's in a failure state log the error(s) and exit.
    1235           0 :   void operator()(Error Err) const { checkError(std::move(Err)); }
    1236           0 : 
    1237           0 :   /// Check E. If it's in a success state then return the contained value. If
    1238           0 :   /// it's in a failure state log the error(s) and exit.
    1239           4 :   template <typename T> T operator()(Expected<T> &&E) const {
    1240           0 :     checkError(E.takeError());
    1241           0 :     return std::move(*E);
    1242           0 :   }
    1243           0 : 
    1244         276 :   /// Check E. If it's in a success state then return the contained reference. If
    1245           0 :   /// it's in a failure state log the error(s) and exit.
    1246           0 :   template <typename T> T& operator()(Expected<T&> &&E) const {
    1247           0 :     checkError(E.takeError());
    1248         311 :     return *E;
    1249          55 :   }
    1250          47 : 
    1251           0 : private:
    1252           0 :   void checkError(Error Err) const {
    1253         108 :     if (Err) {
    1254         109 :       int ExitCode = GetExitCode(Err);
    1255         108 :       logAllUnhandledErrors(std::move(Err), errs(), Banner);
    1256         863 :       exit(ExitCode);
    1257          20 :     }
    1258          30 :   }
    1259          48 : 
    1260         115 :   std::string Banner;
    1261        1446 :   std::function<int(const Error &)> GetExitCode;
    1262        1544 : };
    1263        2208 : 
    1264        2244 : /// Conversion from Error to LLVMErrorRef for C error bindings.
    1265        2235 : inline LLVMErrorRef wrap(Error Err) {
    1266          19 :   return reinterpret_cast<LLVMErrorRef>(Err.takePayload().release());
    1267        1428 : }
    1268          38 : 
    1269          42 : /// Conversion from LLVMErrorRef to Error for C error bindings.
    1270        4269 : inline Error unwrap(LLVMErrorRef ErrRef) {
    1271        4912 :   return Error(std::unique_ptr<ErrorInfoBase>(
    1272           0 :       reinterpret_cast<ErrorInfoBase *>(ErrRef)));
    1273         404 : }
    1274         749 : 
    1275        1429 : } // end namespace llvm
    1276        1386 : 
    1277        1080 : #endif // LLVM_SUPPORT_ERROR_H

Generated by: LCOV version 1.13