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