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