LLVM  10.0.0
RemarkStreamer.cpp
Go to the documentation of this file.
1 //===- llvm/IR/RemarkStreamer.cpp - Remark Streamer -*- 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 contains the implementation of the remark outputting as part of
10 // LLVMContext.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/IR/RemarkStreamer.h"
15 #include "llvm/IR/DiagnosticInfo.h"
16 #include "llvm/IR/Function.h"
17 #include "llvm/IR/GlobalValue.h"
22 
23 using namespace llvm;
24 
26  "remarks-section",
27  cl::desc(
28  "Emit a section containing remark diagnostics metadata. By default, "
29  "this is enabled for the following formats: yaml-strtab, bitstream."),
31 
33  std::unique_ptr<remarks::RemarkSerializer> RemarkSerializer,
34  Optional<StringRef> FilenameIn)
35  : PassFilter(), RemarkSerializer(std::move(RemarkSerializer)),
36  Filename(FilenameIn ? Optional<std::string>(FilenameIn->str()) : None) {}
37 
39  Regex R = Regex(Filter);
40  std::string RegexError;
41  if (!R.isValid(RegexError))
42  return createStringError(std::make_error_code(std::errc::invalid_argument),
43  RegexError.data());
44  PassFilter = std::move(R);
45  return Error::success();
46 }
47 
48 /// DiagnosticKind -> remarks::Type
50  switch (Kind) {
51  default:
55  return remarks::Type::Passed;
58  return remarks::Type::Missed;
68  }
69 }
70 
71 /// DiagnosticLocation -> remarks::RemarkLocation.
74  if (!DL.isValid())
75  return None;
77  unsigned Line = DL.getLine();
78  unsigned Col = DL.getColumn();
79  return remarks::RemarkLocation{File, Line, Col};
80 }
81 
82 /// LLVM Diagnostic -> Remark
84 RemarkStreamer::toRemark(const DiagnosticInfoOptimizationBase &Diag) {
85  remarks::Remark R; // The result.
86  R.RemarkType = toRemarkType(static_cast<DiagnosticKind>(Diag.getKind()));
87  R.PassName = Diag.getPassName();
88  R.RemarkName = Diag.getRemarkName();
89  R.FunctionName =
91  R.Loc = toRemarkLocation(Diag.getLocation());
92  R.Hotness = Diag.getHotness();
93 
95  R.Args.emplace_back();
96  R.Args.back().Key = Arg.Key;
97  R.Args.back().Val = Arg.Val;
98  R.Args.back().Loc = toRemarkLocation(Arg.Loc);
99  }
100 
101  return R;
102 }
103 
105  if (Optional<Regex> &Filter = PassFilter)
106  if (!Filter->match(Diag.getPassName()))
107  return;
108 
109  // First, convert the diagnostic to a remark.
110  remarks::Remark R = toRemark(Diag);
111  // Then, emit the remark through the serializer.
112  RemarkSerializer->emit(R);
113 }
114 
117  return true;
118 
120  return false;
121 
123 
124  // We only need a section if we're in separate mode.
125  if (RemarkSerializer->Mode != remarks::SerializerMode::Separate)
126  return false;
127 
128  // Only some formats need a section:
129  // * bitstream
130  // * yaml-strtab
131  switch (RemarkSerializer->SerializerFormat) {
134  return true;
135  default:
136  return false;
137  }
138 }
139 
140 char RemarkSetupFileError::ID = 0;
143 
147  bool RemarksWithHotness,
148  unsigned RemarksHotnessThreshold) {
149  if (RemarksWithHotness)
150  Context.setDiagnosticsHotnessRequested(true);
151 
152  if (RemarksHotnessThreshold)
153  Context.setDiagnosticsHotnessThreshold(RemarksHotnessThreshold);
154 
155  if (RemarksFilename.empty())
156  return nullptr;
157 
159  if (Error E = Format.takeError())
160  return make_error<RemarkSetupFormatError>(std::move(E));
161 
162  std::error_code EC;
163  auto Flags = *Format == remarks::Format::YAML ? sys::fs::OF_Text
165  auto RemarksFile =
166  std::make_unique<ToolOutputFile>(RemarksFilename, EC, Flags);
167  // We don't use llvm::FileError here because some diagnostics want the file
168  // name separately.
169  if (EC)
170  return make_error<RemarkSetupFileError>(errorCodeToError(EC));
171 
174  *Format, remarks::SerializerMode::Separate, RemarksFile->os());
175  if (Error E = RemarkSerializer.takeError())
176  return make_error<RemarkSetupFormatError>(std::move(E));
177 
178  Context.setRemarkStreamer(std::make_unique<RemarkStreamer>(
179  std::move(*RemarkSerializer), RemarksFilename));
180 
181  if (!RemarksPasses.empty())
182  if (Error E = Context.getRemarkStreamer()->setFilter(RemarksPasses))
183  return make_error<RemarkSetupPatternError>(std::move(E));
184 
185  return std::move(RemarksFile);
186 }
187 
191  bool RemarksWithHotness,
192  unsigned RemarksHotnessThreshold) {
193  if (RemarksWithHotness)
194  Context.setDiagnosticsHotnessRequested(true);
195 
196  if (RemarksHotnessThreshold)
197  Context.setDiagnosticsHotnessThreshold(RemarksHotnessThreshold);
198 
200  if (Error E = Format.takeError())
201  return make_error<RemarkSetupFormatError>(std::move(E));
202 
206  if (Error E = RemarkSerializer.takeError())
207  return make_error<RemarkSetupFormatError>(std::move(E));
208 
209  Context.setRemarkStreamer(
210  std::make_unique<RemarkStreamer>(std::move(*RemarkSerializer)));
211 
212  if (!RemarksPasses.empty())
213  if (Error E = Context.getRemarkStreamer()->setFilter(RemarksPasses))
214  return make_error<RemarkSetupPatternError>(std::move(E));
215 
216  return Error::success();
217 }
const NoneType None
Definition: None.h:23
Error setFilter(StringRef Filter)
Set a pass filter based on a regex Filter.
DiagnosticKind
Defines the different supported kind of a diagnostic.
void setRemarkStreamer(std::unique_ptr< RemarkStreamer > RemarkStreamer)
Set the diagnostics output used for optimization diagnostics.
LLVMContext & Context
This class represents lattice values for constants.
Definition: AllocatorList.h:23
StringRef PassName
Name of the pass that triggers the emission of this remark.
Definition: Remark.h:72
cl::opt< bool > RemarksWithHotness("lto-pass-remarks-with-hotness", cl::desc("With PGO, include profile count in optimization remarks"), cl::Hidden)
bool needsSection() const
Check if the remarks also need to have associated metadata in a section.
RemarkStreamer * getRemarkStreamer()
Return the streamer used by the backend to save remark diagnostics.
unsigned getLine() const
Optional< uint64_t > Hotness
If profile information is available, this is the number of times the corresponding code was executed ...
Definition: Remark.h:87
Error takeError()
Take ownership of the stored error.
Definition: Error.h:552
static remarks::Type toRemarkType(enum DiagnosticKind Kind)
DiagnosticKind -> remarks::Type.
void setDiagnosticsHotnessThreshold(uint64_t Threshold)
Set the minimum hotness value a diagnostic needs in order to be included in optimization diagnostics...
cl::opt< std::string > RemarksPasses("lto-pass-remarks-filter", cl::desc("Only record optimization remarks from passes whose " "names match the given regular expression"), cl::value_desc("regex"))
Definition: BitVector.h:937
A remark type used for both emission and parsing.
Definition: Remark.h:67
std::error_code make_error_code(BitcodeError E)
StringRef RemarkName
Textual identifier for the remark (single-word, camel-case).
Definition: Remark.h:77
Expected< Format > parseFormat(StringRef FormatStr)
Parse and validate a string for the remark format.
Tagged union holding either a T or a Error.
Definition: APFloat.h:41
LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:147
void setDiagnosticsHotnessRequested(bool Requested)
Set if a code hotness metric should be included in optimization diagnostics.
Optional< RemarkLocation > Loc
The location in the source file of the remark.
Definition: Remark.h:83
The file should be opened in text mode on platforms that make this distinction.
Definition: FileSystem.h:767
Type
The type of the remark.
Definition: Remark.h:54
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:435
const Function & getFunction() const
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:63
Instrumentation for Order File
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:87
The debug location used to track a remark back to the source file.
Definition: Remark.h:30
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
void getLocation(StringRef &RelativePath, unsigned &Line, unsigned &Column) const
Return location information for this diagnostic in three parts: the relative source file path...
Used in the streaming interface as the general argument type.
static Optional< remarks::RemarkLocation > toRemarkLocation(const DiagnosticLocation &DL)
DiagnosticLocation -> remarks::RemarkLocation.
static ErrorSuccess success()
Create a success value.
Definition: Error.h:326
Common features for diagnostics dealing with optimization remarks that are used by both IR and MIR pa...
bool isValid(std::string &Error) const
isValid - returns the error encountered during regex compilation, if any.
Definition: Regex.cpp:68
StringRef getRelativePath() const
Return the file name relative to the compilation directory.
static StringRef dropLLVMManglingEscape(StringRef Name)
If the given string begins with the GlobalValue name mangling escape character &#39;\1&#39;, drop it.
Definition: GlobalValue.h:481
Type RemarkType
The type of the remark.
Definition: Remark.h:69
StringRef FunctionName
Mangled name of the function that triggers the emssion of this remark.
Definition: Remark.h:80
Expected< std::unique_ptr< ToolOutputFile > > setupOptimizationRemarks(LLVMContext &Context, StringRef RemarksFilename, StringRef RemarksPasses, StringRef RemarksFormat, bool RemarksWithHotness, unsigned RemarksHotnessThreshold=0)
Setup optimization remarks that output to a file.
ArrayRef< Argument > getArgs() const
static cl::opt< cl::boolOrDefault > EnableRemarksSection("remarks-section", cl::desc("Emit a section containing remark diagnostics metadata. By default, " "this is enabled for the following formats: yaml-strtab, bitstream."), cl::init(cl::BOU_UNSET), cl::Hidden)
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:215
Expected< std::unique_ptr< RemarkSerializer > > createRemarkSerializer(Format RemarksFormat, SerializerMode Mode, raw_ostream &OS)
Create a remark serializer.
RemarkStreamer(std::unique_ptr< remarks::RemarkSerializer > RemarkSerializer, Optional< StringRef > Filename=None)
Optional< uint64_t > getHotness() const
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
cl::opt< std::string > RemarksFormat("lto-pass-remarks-format", cl::desc("The format used for serializing remarks (default: YAML)"), cl::value_desc("format"), cl::init("yaml"))
cl::opt< std::string > RemarksFilename("lto-pass-remarks-output", cl::desc("Output filename for pass remarks"), cl::value_desc("filename"))
SmallVector< Argument, 5 > Args
Arguments collected via the streaming interface.
Definition: Remark.h:90
Lightweight error class with error context and mandatory checking.
Definition: Error.h:157
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:46
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:54
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition: Error.h:1197
void emit(const DiagnosticInfoOptimizationBase &Diag)
Emit a diagnostic through the streamer.
unsigned getColumn() const