LLVM  9.0.0svn
RemarkParser.cpp
Go to the documentation of this file.
1 //===- RemarkParser.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 // This file provides utility methods used by clients that want to use the
10 // parser for remark diagnostics in LLVM.
11 //
12 //===----------------------------------------------------------------------===//
13 
15 #include "YAMLRemarkParser.h"
16 #include "llvm-c/Remarks.h"
17 #include "llvm/ADT/STLExtras.h"
19 
20 using namespace llvm;
21 using namespace llvm::remarks;
22 
24 
26  : Impl(llvm::make_unique<YAMLParserImpl>(Buf, StrTabBuf)) {}
27 
28 Parser::~Parser() = default;
29 
31  YAMLRemarkParser &YAMLParser = Impl.YAMLParser;
32  // Check for EOF.
33  if (Impl.YAMLIt == Impl.YAMLParser.Stream.end())
34  return nullptr;
35 
36  auto CurrentIt = Impl.YAMLIt;
37 
38  // Try to parse an entry.
39  if (Error E = YAMLParser.parseYAMLElement(*CurrentIt)) {
40  // Set the iterator to the end, in case the user calls getNext again.
41  Impl.YAMLIt = Impl.YAMLParser.Stream.end();
42  return std::move(E);
43  }
44 
45  // Move on.
46  ++Impl.YAMLIt;
47 
48  // Return the just-parsed remark.
49  if (const Optional<YAMLRemarkParser::ParseState> &State = YAMLParser.State)
50  return &State->TheRemark;
51  else
52  return createStringError(std::make_error_code(std::errc::invalid_argument),
53  "unexpected error while parsing.");
54 }
55 
57  if (auto *Impl = dyn_cast<YAMLParserImpl>(this->Impl.get()))
58  return getNextYAML(*Impl);
59  llvm_unreachable("Get next called with an unknown parsing implementation.");
60 }
61 
62 ParsedStringTable::ParsedStringTable(StringRef InBuffer) : Buffer(InBuffer) {
63  while (!InBuffer.empty()) {
64  // Strings are separated by '\0' bytes.
65  std::pair<StringRef, StringRef> Split = InBuffer.split('\0');
66  // We only store the offset from the beginning of the buffer.
67  Offsets.push_back(Split.first.data() - Buffer.data());
68  InBuffer = Split.second;
69  }
70 }
71 
73  if (Index >= Offsets.size())
74  return createStringError(
75  std::make_error_code(std::errc::invalid_argument),
76  "String with index %u is out of bounds (size = %u).", Index,
77  Offsets.size());
78 
79  size_t Offset = Offsets[Index];
80  // If it's the last offset, we can't use the next offset to know the size of
81  // the string.
82  size_t NextOffset =
83  (Index == Offsets.size() - 1) ? Buffer.size() : Offsets[Index + 1];
84  return StringRef(Buffer.data() + Offset, NextOffset - Offset - 1);
85 }
86 
87 // Create wrappers for C Binding types (see CBindingWrapping.h).
89 
91  uint64_t Size) {
92  return wrap(
93  new remarks::Parser(StringRef(static_cast<const char *>(Buf), Size)));
94 }
95 
98  std::move(E),
99  [&](const YAMLParseError &PE) {
100  Impl.YAMLParser.Stream.printError(&PE.getNode(),
101  Twine(PE.getMessage()) + Twine('\n'));
102  },
103  [&](const ErrorInfoBase &EIB) { EIB.log(Impl.YAMLParser.ErrorStream); });
104  Impl.HasErrors = true;
105 }
106 
107 extern "C" LLVMRemarkEntryRef
109  remarks::Parser &TheParser = *unwrap(Parser);
110 
111  Expected<const remarks::Remark *> RemarkOrErr = TheParser.getNext();
112  if (!RemarkOrErr) {
113  // Error during parsing.
114  if (auto *Impl = dyn_cast<remarks::YAMLParserImpl>(TheParser.Impl.get()))
115  handleYAMLError(*Impl, RemarkOrErr.takeError());
116  else
117  llvm_unreachable("unkown parser implementation.");
118  return nullptr;
119  }
120 
121  if (*RemarkOrErr == nullptr)
122  return nullptr;
123  // Valid remark.
124  return wrap(*RemarkOrErr);
125 }
126 
128  if (auto *Impl =
129  dyn_cast<remarks::YAMLParserImpl>(unwrap(Parser)->Impl.get()))
130  return Impl->HasErrors;
131  llvm_unreachable("unkown parser implementation.");
132 }
133 
134 extern "C" const char *
136  if (auto *Impl =
137  dyn_cast<remarks::YAMLParserImpl>(unwrap(Parser)->Impl.get()))
138  return Impl->YAMLParser.ErrorStream.str().c_str();
139  llvm_unreachable("unkown parser implementation.");
140 }
141 
143  delete unwrap(Parser);
144 }
uint64_t CallInst * C
Parses and holds the state of the latest parsed remark.
This class represents lattice values for constants.
Definition: AllocatorList.h:23
static Expected< const Remark * > getNextYAML(YAMLParserImpl &Impl)
void push_back(const T &Elt)
Definition: SmallVector.h:211
struct LLVMRemarkOpaqueParser * LLVMRemarkParserRef
Definition: Remarks.h:216
std::enable_if<!std::is_array< T >::value, std::unique_ptr< T > >::type make_unique(Args &&... args)
Constructs a new T() with the given args and returns a unique_ptr<T> which owns the object...
Definition: STLExtras.h:1403
Expected< StringRef > operator[](size_t Index)
Error takeError()
Take ownership of the stored error.
Definition: Error.h:552
Base class for error info classes.
Definition: Error.h:48
document_iterator end()
Optional< ParseState > State
The current state of the parser.
#define DEFINE_SIMPLE_CONVERSION_FUNCTIONS(ty, ref)
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:80
Attribute unwrap(LLVMAttributeRef Attr)
Definition: Attributes.h:194
const char * LLVMRemarkParserGetErrorMessage(LLVMRemarkParserRef Parser)
Returns a null-terminated string containing an error message.
std::error_code make_error_code(BitcodeError E)
void LLVMRemarkParserDispose(LLVMRemarkParserRef Parser)
Releases all the resources used by Parser.
Tagged union holding either a T or a Error.
Definition: CachePruning.h:22
LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:126
LLVM_NODISCARD size_t size() const
size - Get the string size.
Definition: StringRef.h:130
LLVMBool LLVMRemarkParserHasError(LLVMRemarkParserRef Parser)
Returns 1 if the parser encountered an error while parsing the buffer.
static void handleYAMLError(remarks::YAMLParserImpl &Impl, Error E)
ParsedStringTable(StringRef Buffer)
bool HasErrors
Set to true if we had any errors during parsing.
StringRef Buffer
The buffer mapped from the section contents.
Definition: RemarkParser.h:53
void printError(Node *N, const Twine &Msg)
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
LLVMRemarkEntryRef LLVMRemarkParserGetNext(LLVMRemarkParserRef Parser)
Returns the next remark in the file.
std::unique_ptr< ParserImpl > Impl
The hidden implementation of the parser.
Definition: RemarkParser.h:30
Regular YAML to Remark parser.
Parser(StringRef Buffer)
Create a parser parsing Buffer to Remark objects.
int LLVMBool
Definition: Types.h:29
Expected< const Remark * > getNext() const
Returns an empty Optional if it reached the end.
size_t size() const
Definition: SmallVector.h:52
SmallVector< size_t, 8 > Offsets
Collection of offsets in the buffer for each string entry.
Definition: RemarkParser.h:55
Parser used to parse a raw buffer to remarks::Remark objects.
Definition: RemarkParser.h:28
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
YAMLRemarkParser YAMLParser
The object parsing the YAML.
yaml::document_iterator YAMLIt
Iterator in the YAML stream.
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:904
LLVM_NODISCARD std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition: StringRef.h:696
yaml::Node & getNode() const
LLVMAttributeRef wrap(Attribute Attr)
Definition: Attributes.h:189
uint32_t Size
Definition: Profile.cpp:46
LLVMRemarkParserRef LLVMRemarkParserCreateYAML(const void *Buf, uint64_t Size)
Creates a remark parser that can be used to parse the buffer located in Buf of size Size bytes...
static Attribute get(LLVMContext &Context, AttrKind Kind, uint64_t Val=0)
Return a uniquified Attribute object.
Definition: Attributes.cpp:80
Error parseYAMLElement(yaml::Document &Remark)
Parse a YAML element.
LLVM_NODISCARD const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition: StringRef.h:122
raw_string_ostream ErrorStream
The error stream.
aarch64 promote const
yaml::Stream Stream
Stream for yaml parsing.
Lightweight error class with error context and mandatory checking.
Definition: Error.h:157
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
struct LLVMRemarkOpaqueEntry * LLVMRemarkEntryRef
A remark emitted by the compiler.
Definition: Remarks.h:137
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition: Error.h:1163