xref: /llvm-project/llvm/tools/llvm-profgen/ErrorHandling.h (revision aab1810006a6788e32ee04e7d40d0b2474754aa2)
1 //===-- ErrorHandling.h - Error handler -------------------------*- 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 #ifndef LLVM_TOOLS_LLVM_PROFGEN_ERRORHANDLING_H
10 #define LLVM_TOOLS_LLVM_PROFGEN_ERRORHANDLING_H
11 
12 #include "llvm/ADT/Twine.h"
13 #include "llvm/Support/Errc.h"
14 #include "llvm/Support/Error.h"
15 #include "llvm/Support/ErrorOr.h"
16 #include "llvm/Support/WithColor.h"
17 #include <system_error>
18 
19 using namespace llvm;
20 
21 [[noreturn]] inline void exitWithError(const Twine &Message,
22                                        StringRef Whence = StringRef(),
23                                        StringRef Hint = StringRef()) {
24   WithColor::error(errs(), "llvm-profgen");
25   if (!Whence.empty())
26     errs() << Whence.str() << ": ";
27   errs() << Message << "\n";
28   if (!Hint.empty())
29     WithColor::note() << Hint.str() << "\n";
30   ::exit(EXIT_FAILURE);
31 }
32 
33 [[noreturn]] inline void exitWithError(std::error_code EC,
34                                        StringRef Whence = StringRef()) {
35   exitWithError(EC.message(), Whence);
36 }
37 
exitWithError(Error E,StringRef Whence)38 [[noreturn]] inline void exitWithError(Error E, StringRef Whence) {
39   exitWithError(errorToErrorCode(std::move(E)), Whence);
40 }
41 
42 template <typename T, typename... Ts>
unwrapOrError(Expected<T> EO,Ts &&...Args)43 T unwrapOrError(Expected<T> EO, Ts &&... Args) {
44   if (EO)
45     return std::move(*EO);
46   exitWithError(EO.takeError(), std::forward<Ts>(Args)...);
47 }
48 
emitWarningSummary(uint64_t Num,uint64_t Total,StringRef Msg)49 inline void emitWarningSummary(uint64_t Num, uint64_t Total, StringRef Msg) {
50   if (!Total || !Num)
51     return;
52   WithColor::warning() << format("%.2f", static_cast<double>(Num) * 100 / Total)
53                        << "%(" << Num << "/" << Total << ") " << Msg << "\n";
54 }
55 
56 #endif
57