1 //===- llvm/Support/DiagnosticInfo.cpp - Diagnostic Definitions -*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 // This file defines the different classes involved in low level diagnostics.
11 // Diagnostics reporting is still done as part of the LLVMContext.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/IR/DiagnosticInfo.h"
15 #include "LLVMContextImpl.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/ADT/iterator_range.h"
19 #include "llvm/IR/BasicBlock.h"
20 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/DebugInfoMetadata.h"
22 #include "llvm/IR/DerivedTypes.h"
23 #include "llvm/IR/DiagnosticPrinter.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/IR/GlobalValue.h"
26 #include "llvm/IR/Instruction.h"
27 #include "llvm/IR/LLVMContext.h"
28 #include "llvm/IR/Metadata.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/IR/Type.h"
31 #include "llvm/IR/Value.h"
32 #include "llvm/Support/Casting.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/Path.h"
36 #include "llvm/Support/Regex.h"
37 #include "llvm/Support/ScopedPrinter.h"
38 #include "llvm/Support/raw_ostream.h"
46 cl::opt
<bool> UseStringTable("remarks-yaml-string-table", cl::init(false));
48 int llvm::getNextAvailablePluginDiagnosticKind() {
49 static std::atomic
<int> PluginKindID(DK_FirstPluginKind
);
50 return ++PluginKindID
;
53 const char *OptimizationRemarkAnalysis::AlwaysPrint
= "";
55 DiagnosticInfoInlineAsm::DiagnosticInfoInlineAsm(const Instruction
&I
,
57 DiagnosticSeverity Severity
)
58 : DiagnosticInfo(DK_InlineAsm
, Severity
), MsgStr(MsgStr
), Instr(&I
) {
59 if (const MDNode
*SrcLoc
= I
.getMetadata("srcloc")) {
60 if (SrcLoc
->getNumOperands() != 0)
62 mdconst::dyn_extract
<ConstantInt
>(SrcLoc
->getOperand(0)))
63 LocCookie
= CI
->getZExtValue();
67 void DiagnosticInfoInlineAsm::print(DiagnosticPrinter
&DP
) const {
70 DP
<< " at line " << getLocCookie();
73 void DiagnosticInfoResourceLimit::print(DiagnosticPrinter
&DP
) const {
74 DP
<< getResourceName() << " limit";
76 if (getResourceLimit() != 0)
77 DP
<< " of " << getResourceLimit();
79 DP
<< " exceeded (" << getResourceSize() << ") in " << getFunction();
82 void DiagnosticInfoDebugMetadataVersion::print(DiagnosticPrinter
&DP
) const {
83 DP
<< "ignoring debug info with an invalid version (" << getMetadataVersion()
84 << ") in " << getModule();
87 void DiagnosticInfoIgnoringInvalidDebugMetadata::print(
88 DiagnosticPrinter
&DP
) const {
89 DP
<< "ignoring invalid debug info in " << getModule().getModuleIdentifier();
92 void DiagnosticInfoSampleProfile::print(DiagnosticPrinter
&DP
) const {
93 if (!FileName
.empty()) {
96 DP
<< ":" << getLineNum();
102 void DiagnosticInfoPGOProfile::print(DiagnosticPrinter
&DP
) const {
104 DP
<< getFileName() << ": ";
108 void DiagnosticInfo::anchor() {}
109 void DiagnosticInfoStackSize::anchor() {}
110 void DiagnosticInfoWithLocationBase::anchor() {}
111 void DiagnosticInfoIROptimization::anchor() {}
113 DiagnosticLocation::DiagnosticLocation(const DebugLoc
&DL
) {
116 File
= DL
->getFile();
117 Line
= DL
->getLine();
118 Column
= DL
->getColumn();
121 DiagnosticLocation::DiagnosticLocation(const DISubprogram
*SP
) {
125 File
= SP
->getFile();
126 Line
= SP
->getScopeLine();
130 StringRef
DiagnosticLocation::getRelativePath() const {
131 return File
->getFilename();
134 std::string
DiagnosticLocation::getAbsolutePath() const {
135 StringRef Name
= File
->getFilename();
136 if (sys::path::is_absolute(Name
))
139 SmallString
<128> Path
;
140 sys::path::append(Path
, File
->getDirectory(), Name
);
141 return sys::path::remove_leading_dotslash(Path
).str();
144 std::string
DiagnosticInfoWithLocationBase::getAbsolutePath() const {
145 return Loc
.getAbsolutePath();
148 void DiagnosticInfoWithLocationBase::getLocation(StringRef
&RelativePath
,
150 unsigned &Column
) const {
151 RelativePath
= Loc
.getRelativePath();
152 Line
= Loc
.getLine();
153 Column
= Loc
.getColumn();
156 const std::string
DiagnosticInfoWithLocationBase::getLocationStr() const {
157 StringRef
Filename("<unknown>");
160 if (isLocationAvailable())
161 getLocation(Filename
, Line
, Column
);
162 return (Filename
+ ":" + Twine(Line
) + ":" + Twine(Column
)).str();
165 DiagnosticInfoOptimizationBase::Argument::Argument(StringRef Key
, const Value
*V
)
167 if (auto *F
= dyn_cast
<Function
>(V
)) {
168 if (DISubprogram
*SP
= F
->getSubprogram())
171 else if (auto *I
= dyn_cast
<Instruction
>(V
))
172 Loc
= I
->getDebugLoc();
174 // Only include names that correspond to user variables. FIXME: We should use
175 // debug info if available to get the name of the user variable.
176 if (isa
<llvm::Argument
>(V
) || isa
<GlobalValue
>(V
))
177 Val
= GlobalValue::dropLLVMManglingEscape(V
->getName());
178 else if (isa
<Constant
>(V
)) {
179 raw_string_ostream
OS(Val
);
180 V
->printAsOperand(OS
, /*PrintType=*/false);
181 } else if (auto *I
= dyn_cast
<Instruction
>(V
))
182 Val
= I
->getOpcodeName();
185 DiagnosticInfoOptimizationBase::Argument::Argument(StringRef Key
, const Type
*T
)
187 raw_string_ostream
OS(Val
);
191 DiagnosticInfoOptimizationBase::Argument::Argument(StringRef Key
, StringRef S
)
192 : Key(Key
), Val(S
.str()) {}
194 DiagnosticInfoOptimizationBase::Argument::Argument(StringRef Key
, int N
)
195 : Key(Key
), Val(itostr(N
)) {}
197 DiagnosticInfoOptimizationBase::Argument::Argument(StringRef Key
, float N
)
198 : Key(Key
), Val(llvm::to_string(N
)) {}
200 DiagnosticInfoOptimizationBase::Argument::Argument(StringRef Key
, long N
)
201 : Key(Key
), Val(itostr(N
)) {}
203 DiagnosticInfoOptimizationBase::Argument::Argument(StringRef Key
, long long N
)
204 : Key(Key
), Val(itostr(N
)) {}
206 DiagnosticInfoOptimizationBase::Argument::Argument(StringRef Key
, unsigned N
)
207 : Key(Key
), Val(utostr(N
)) {}
209 DiagnosticInfoOptimizationBase::Argument::Argument(StringRef Key
,
211 : Key(Key
), Val(utostr(N
)) {}
213 DiagnosticInfoOptimizationBase::Argument::Argument(StringRef Key
,
214 unsigned long long N
)
215 : Key(Key
), Val(utostr(N
)) {}
217 DiagnosticInfoOptimizationBase::Argument::Argument(StringRef Key
, DebugLoc Loc
)
218 : Key(Key
), Loc(Loc
) {
220 Val
= (Loc
->getFilename() + ":" + Twine(Loc
.getLine()) + ":" +
221 Twine(Loc
.getCol())).str();
223 Val
= "<UNKNOWN LOCATION>";
227 void DiagnosticInfoOptimizationBase::print(DiagnosticPrinter
&DP
) const {
228 DP
<< getLocationStr() << ": " << getMsg();
230 DP
<< " (hotness: " << *Hotness
<< ")";
233 OptimizationRemark::OptimizationRemark(const char *PassName
,
234 StringRef RemarkName
,
235 const DiagnosticLocation
&Loc
,
236 const Value
*CodeRegion
)
237 : DiagnosticInfoIROptimization(
238 DK_OptimizationRemark
, DS_Remark
, PassName
, RemarkName
,
239 *cast
<BasicBlock
>(CodeRegion
)->getParent(), Loc
, CodeRegion
) {}
241 OptimizationRemark::OptimizationRemark(const char *PassName
,
242 StringRef RemarkName
,
243 const Instruction
*Inst
)
244 : DiagnosticInfoIROptimization(DK_OptimizationRemark
, DS_Remark
, PassName
,
245 RemarkName
, *Inst
->getParent()->getParent(),
246 Inst
->getDebugLoc(), Inst
->getParent()) {}
248 // Helper to allow for an assert before attempting to return an invalid
250 static const BasicBlock
&getFirstFunctionBlock(const Function
*Func
) {
251 assert(!Func
->empty() && "Function does not have a body");
252 return Func
->front();
255 OptimizationRemark::OptimizationRemark(const char *PassName
,
256 StringRef RemarkName
,
257 const Function
*Func
)
258 : DiagnosticInfoIROptimization(DK_OptimizationRemark
, DS_Remark
, PassName
,
259 RemarkName
, *Func
, Func
->getSubprogram(),
260 &getFirstFunctionBlock(Func
)) {}
262 bool OptimizationRemark::isEnabled() const {
263 const Function
&Fn
= getFunction();
264 LLVMContext
&Ctx
= Fn
.getContext();
265 return Ctx
.getDiagHandlerPtr()->isPassedOptRemarkEnabled(getPassName());
268 OptimizationRemarkMissed::OptimizationRemarkMissed(
269 const char *PassName
, StringRef RemarkName
, const DiagnosticLocation
&Loc
,
270 const Value
*CodeRegion
)
271 : DiagnosticInfoIROptimization(
272 DK_OptimizationRemarkMissed
, DS_Remark
, PassName
, RemarkName
,
273 *cast
<BasicBlock
>(CodeRegion
)->getParent(), Loc
, CodeRegion
) {}
275 OptimizationRemarkMissed::OptimizationRemarkMissed(const char *PassName
,
276 StringRef RemarkName
,
277 const Instruction
*Inst
)
278 : DiagnosticInfoIROptimization(DK_OptimizationRemarkMissed
, DS_Remark
,
279 PassName
, RemarkName
,
280 *Inst
->getParent()->getParent(),
281 Inst
->getDebugLoc(), Inst
->getParent()) {}
283 bool OptimizationRemarkMissed::isEnabled() const {
284 const Function
&Fn
= getFunction();
285 LLVMContext
&Ctx
= Fn
.getContext();
286 return Ctx
.getDiagHandlerPtr()->isMissedOptRemarkEnabled(getPassName());
289 OptimizationRemarkAnalysis::OptimizationRemarkAnalysis(
290 const char *PassName
, StringRef RemarkName
, const DiagnosticLocation
&Loc
,
291 const Value
*CodeRegion
)
292 : DiagnosticInfoIROptimization(
293 DK_OptimizationRemarkAnalysis
, DS_Remark
, PassName
, RemarkName
,
294 *cast
<BasicBlock
>(CodeRegion
)->getParent(), Loc
, CodeRegion
) {}
296 OptimizationRemarkAnalysis::OptimizationRemarkAnalysis(const char *PassName
,
297 StringRef RemarkName
,
298 const Instruction
*Inst
)
299 : DiagnosticInfoIROptimization(DK_OptimizationRemarkAnalysis
, DS_Remark
,
300 PassName
, RemarkName
,
301 *Inst
->getParent()->getParent(),
302 Inst
->getDebugLoc(), Inst
->getParent()) {}
304 OptimizationRemarkAnalysis::OptimizationRemarkAnalysis(
305 enum DiagnosticKind Kind
, const char *PassName
, StringRef RemarkName
,
306 const DiagnosticLocation
&Loc
, const Value
*CodeRegion
)
307 : DiagnosticInfoIROptimization(Kind
, DS_Remark
, PassName
, RemarkName
,
308 *cast
<BasicBlock
>(CodeRegion
)->getParent(),
311 bool OptimizationRemarkAnalysis::isEnabled() const {
312 const Function
&Fn
= getFunction();
313 LLVMContext
&Ctx
= Fn
.getContext();
314 return Ctx
.getDiagHandlerPtr()->isAnalysisRemarkEnabled(getPassName()) ||
318 void DiagnosticInfoMIRParser::print(DiagnosticPrinter
&DP
) const {
322 DiagnosticInfoOptimizationFailure::DiagnosticInfoOptimizationFailure(
323 const char *PassName
, StringRef RemarkName
, const DiagnosticLocation
&Loc
,
324 const Value
*CodeRegion
)
325 : DiagnosticInfoIROptimization(
326 DK_OptimizationFailure
, DS_Warning
, PassName
, RemarkName
,
327 *cast
<BasicBlock
>(CodeRegion
)->getParent(), Loc
, CodeRegion
) {}
329 bool DiagnosticInfoOptimizationFailure::isEnabled() const {
330 // Only print warnings.
331 return getSeverity() == DS_Warning
;
334 void DiagnosticInfoUnsupported::print(DiagnosticPrinter
&DP
) const {
336 raw_string_ostream
OS(Str
);
338 OS
<< getLocationStr() << ": in function " << getFunction().getName() << ' '
339 << *getFunction().getFunctionType() << ": " << Msg
<< '\n';
344 void DiagnosticInfoISelFallback::print(DiagnosticPrinter
&DP
) const {
345 DP
<< "Instruction selection used fallback path for " << getFunction();
348 void DiagnosticInfoOptimizationBase::insert(StringRef S
) {
349 Args
.emplace_back(S
);
352 void DiagnosticInfoOptimizationBase::insert(Argument A
) {
353 Args
.push_back(std::move(A
));
356 void DiagnosticInfoOptimizationBase::insert(setIsVerbose V
) {
360 void DiagnosticInfoOptimizationBase::insert(setExtraArgs EA
) {
361 FirstExtraArgIndex
= Args
.size();
364 std::string
DiagnosticInfoOptimizationBase::getMsg() const {
366 raw_string_ostream
OS(Str
);
367 for (const DiagnosticInfoOptimizationBase::Argument
&Arg
:
368 make_range(Args
.begin(), FirstExtraArgIndex
== -1
370 : Args
.begin() + FirstExtraArgIndex
))
375 void OptimizationRemarkAnalysisFPCommute::anchor() {}
376 void OptimizationRemarkAnalysisAliasing::anchor() {}
378 template <typename T
>
379 static void mapRemarkHeader(
380 yaml::IO
&io
, T PassName
, T RemarkName
, DiagnosticLocation DL
,
381 T FunctionName
, Optional
<uint64_t> Hotness
,
382 SmallVectorImpl
<DiagnosticInfoOptimizationBase::Argument
> &Args
) {
383 io
.mapRequired("Pass", PassName
);
384 io
.mapRequired("Name", RemarkName
);
385 if (!io
.outputting() || DL
.isValid())
386 io
.mapOptional("DebugLoc", DL
);
387 io
.mapRequired("Function", FunctionName
);
388 io
.mapOptional("Hotness", Hotness
);
389 io
.mapOptional("Args", Args
);
395 void MappingTraits
<DiagnosticInfoOptimizationBase
*>::mapping(
396 IO
&io
, DiagnosticInfoOptimizationBase
*&OptDiag
) {
397 assert(io
.outputting() && "input not yet implemented");
399 if (io
.mapTag("!Passed",
400 (OptDiag
->getKind() == DK_OptimizationRemark
||
401 OptDiag
->getKind() == DK_MachineOptimizationRemark
)))
405 (OptDiag
->getKind() == DK_OptimizationRemarkMissed
||
406 OptDiag
->getKind() == DK_MachineOptimizationRemarkMissed
)))
410 (OptDiag
->getKind() == DK_OptimizationRemarkAnalysis
||
411 OptDiag
->getKind() == DK_MachineOptimizationRemarkAnalysis
)))
413 else if (io
.mapTag("!AnalysisFPCommute",
414 OptDiag
->getKind() ==
415 DK_OptimizationRemarkAnalysisFPCommute
))
417 else if (io
.mapTag("!AnalysisAliasing",
418 OptDiag
->getKind() ==
419 DK_OptimizationRemarkAnalysisAliasing
))
421 else if (io
.mapTag("!Failure", OptDiag
->getKind() == DK_OptimizationFailure
))
424 llvm_unreachable("Unknown remark type");
426 // These are read-only for now.
427 DiagnosticLocation DL
= OptDiag
->getLocation();
429 GlobalValue::dropLLVMManglingEscape(OptDiag
->getFunction().getName());
431 StringRef
PassName(OptDiag
->PassName
);
432 if (UseStringTable
) {
433 remarks::StringTable
&StrTab
=
434 reinterpret_cast<RemarkStreamer
*>(io
.getContext())->getStringTable();
435 unsigned PassID
= StrTab
.add(PassName
).first
;
436 unsigned NameID
= StrTab
.add(OptDiag
->RemarkName
).first
;
437 unsigned FunctionID
= StrTab
.add(FN
).first
;
438 mapRemarkHeader(io
, PassID
, NameID
, DL
, FunctionID
, OptDiag
->Hotness
,
441 mapRemarkHeader(io
, PassName
, OptDiag
->RemarkName
, DL
, FN
, OptDiag
->Hotness
,
446 template <> struct MappingTraits
<DiagnosticLocation
> {
447 static void mapping(IO
&io
, DiagnosticLocation
&DL
) {
448 assert(io
.outputting() && "input not yet implemented");
450 StringRef File
= DL
.getRelativePath();
451 unsigned Line
= DL
.getLine();
452 unsigned Col
= DL
.getColumn();
454 if (UseStringTable
) {
455 remarks::StringTable
&StrTab
=
456 reinterpret_cast<RemarkStreamer
*>(io
.getContext())->getStringTable();
457 unsigned FileID
= StrTab
.add(File
).first
;
458 io
.mapRequired("File", FileID
);
460 io
.mapRequired("File", File
);
463 io
.mapRequired("Line", Line
);
464 io
.mapRequired("Column", Col
);
467 static const bool flow
= true;
470 /// Helper struct for multiline string block literals. Use this type to preserve
471 /// newlines in strings.
472 struct StringBlockVal
{
474 StringBlockVal(const std::string
&Value
) : Value(Value
) {}
477 template <> struct BlockScalarTraits
<StringBlockVal
> {
478 static void output(const StringBlockVal
&S
, void *Ctx
, raw_ostream
&OS
) {
479 return ScalarTraits
<StringRef
>::output(S
.Value
, Ctx
, OS
);
482 static StringRef
input(StringRef Scalar
, void *Ctx
, StringBlockVal
&S
) {
483 return ScalarTraits
<StringRef
>::input(Scalar
, Ctx
, S
.Value
);
487 // Implement this as a mapping for now to get proper quotation for the value.
488 template <> struct MappingTraits
<DiagnosticInfoOptimizationBase::Argument
> {
489 static void mapping(IO
&io
, DiagnosticInfoOptimizationBase::Argument
&A
) {
490 assert(io
.outputting() && "input not yet implemented");
492 if (UseStringTable
) {
493 remarks::StringTable
&StrTab
=
494 reinterpret_cast<RemarkStreamer
*>(io
.getContext())->getStringTable();
495 auto ValueID
= StrTab
.add(A
.Val
).first
;
496 io
.mapRequired(A
.Key
.data(), ValueID
);
497 } else if (StringRef(A
.Val
).count('\n') > 1) {
498 StringBlockVal
S(A
.Val
);
499 io
.mapRequired(A
.Key
.data(), S
);
501 io
.mapRequired(A
.Key
.data(), A
.Val
);
504 io
.mapOptional("DebugLoc", A
.Loc
);
508 } // end namespace yaml
509 } // end namespace llvm
511 LLVM_YAML_IS_SEQUENCE_VECTOR(DiagnosticInfoOptimizationBase::Argument
)