1 //===- RemarkFormat.cpp --------------------------------------------------===//
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 // Implementation of utilities to handle the different remark formats.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "llvm/Remarks/RemarkFormat.h"
14 #include "llvm/ADT/StringSwitch.h"
15 #include "llvm/Remarks/BitstreamRemarkContainer.h"
16
17 using namespace llvm;
18 using namespace llvm::remarks;
19
parseFormat(StringRef FormatStr)20 Expected<Format> llvm::remarks::parseFormat(StringRef FormatStr) {
21 auto Result = StringSwitch<Format>(FormatStr)
22 .Cases("", "yaml", Format::YAML)
23 .Case("bitstream", Format::Bitstream)
24 .Default(Format::Unknown);
25
26 if (Result == Format::Unknown)
27 return createStringError(std::make_error_code(std::errc::invalid_argument),
28 "Unknown remark format: '%s'",
29 FormatStr.data());
30
31 return Result;
32 }
33
magicToFormat(StringRef MagicStr)34 Expected<Format> llvm::remarks::magicToFormat(StringRef MagicStr) {
35 auto Result =
36 StringSwitch<Format>(MagicStr)
37 .StartsWith("--- ", Format::YAML) // This is only an assumption.
38 .StartsWith(remarks::Magic,
39 Format::YAML) // Needed for remark meta section
40 .StartsWith(remarks::ContainerMagic, Format::Bitstream)
41 .Default(Format::Unknown);
42
43 if (Result == Format::Unknown)
44 return createStringError(std::make_error_code(std::errc::invalid_argument),
45 "Automatic detection of remark format failed. "
46 "Unknown magic number: '%.4s'",
47 MagicStr.data());
48 return Result;
49 }
50
detectFormat(Format Selected,StringRef MagicStr)51 Expected<Format> llvm::remarks::detectFormat(Format Selected,
52 StringRef MagicStr) {
53 if (Selected == Format::Unknown)
54 return createStringError(std::make_error_code(std::errc::invalid_argument),
55 "Unknown remark parser format.");
56 if (Selected != Format::Auto)
57 return Selected;
58
59 // Empty files are valid bitstream files
60 if (MagicStr.empty())
61 return Format::Bitstream;
62 return magicToFormat(MagicStr);
63 }
64