llvm-config: Include -stdlib= in --cxxflags
[llvm-project.git] / llvm / lib / IR / DiagnosticInfo.cpp
blob14bee35dc2929ec6060c63c8e6fdc1cdb44c8151
1 //===- llvm/Support/DiagnosticInfo.cpp - Diagnostic Definitions -*- 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 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"
39 #include <atomic>
40 #include <cassert>
41 #include <memory>
42 #include <string>
44 using namespace llvm;
46 int llvm::getNextAvailablePluginDiagnosticKind() {
47 static std::atomic<int> PluginKindID(DK_FirstPluginKind);
48 return ++PluginKindID;
51 const char *OptimizationRemarkAnalysis::AlwaysPrint = "";
53 DiagnosticInfoInlineAsm::DiagnosticInfoInlineAsm(const Instruction &I,
54 const Twine &MsgStr,
55 DiagnosticSeverity Severity)
56 : DiagnosticInfo(DK_InlineAsm, Severity), MsgStr(MsgStr), Instr(&I) {
57 if (const MDNode *SrcLoc = I.getMetadata("srcloc")) {
58 if (SrcLoc->getNumOperands() != 0)
59 if (const auto *CI =
60 mdconst::dyn_extract<ConstantInt>(SrcLoc->getOperand(0)))
61 LocCookie = CI->getZExtValue();
65 void DiagnosticInfoInlineAsm::print(DiagnosticPrinter &DP) const {
66 DP << getMsgStr();
67 if (getLocCookie())
68 DP << " at line " << getLocCookie();
71 void DiagnosticInfoResourceLimit::print(DiagnosticPrinter &DP) const {
72 DP << getResourceName() << " limit";
74 if (getResourceLimit() != 0)
75 DP << " of " << getResourceLimit();
77 DP << " exceeded (" << getResourceSize() << ") in " << getFunction();
80 void DiagnosticInfoDebugMetadataVersion::print(DiagnosticPrinter &DP) const {
81 DP << "ignoring debug info with an invalid version (" << getMetadataVersion()
82 << ") in " << getModule();
85 void DiagnosticInfoIgnoringInvalidDebugMetadata::print(
86 DiagnosticPrinter &DP) const {
87 DP << "ignoring invalid debug info in " << getModule().getModuleIdentifier();
90 void DiagnosticInfoSampleProfile::print(DiagnosticPrinter &DP) const {
91 if (!FileName.empty()) {
92 DP << getFileName();
93 if (LineNum > 0)
94 DP << ":" << getLineNum();
95 DP << ": ";
97 DP << getMsg();
100 void DiagnosticInfoPGOProfile::print(DiagnosticPrinter &DP) const {
101 if (getFileName())
102 DP << getFileName() << ": ";
103 DP << getMsg();
106 void DiagnosticInfo::anchor() {}
107 void DiagnosticInfoStackSize::anchor() {}
108 void DiagnosticInfoWithLocationBase::anchor() {}
109 void DiagnosticInfoIROptimization::anchor() {}
111 DiagnosticLocation::DiagnosticLocation(const DebugLoc &DL) {
112 if (!DL)
113 return;
114 File = DL->getFile();
115 Line = DL->getLine();
116 Column = DL->getColumn();
119 DiagnosticLocation::DiagnosticLocation(const DISubprogram *SP) {
120 if (!SP)
121 return;
123 File = SP->getFile();
124 Line = SP->getScopeLine();
125 Column = 0;
128 StringRef DiagnosticLocation::getRelativePath() const {
129 return File->getFilename();
132 std::string DiagnosticLocation::getAbsolutePath() const {
133 StringRef Name = File->getFilename();
134 if (sys::path::is_absolute(Name))
135 return Name;
137 SmallString<128> Path;
138 sys::path::append(Path, File->getDirectory(), Name);
139 return sys::path::remove_leading_dotslash(Path).str();
142 std::string DiagnosticInfoWithLocationBase::getAbsolutePath() const {
143 return Loc.getAbsolutePath();
146 void DiagnosticInfoWithLocationBase::getLocation(StringRef &RelativePath,
147 unsigned &Line,
148 unsigned &Column) const {
149 RelativePath = Loc.getRelativePath();
150 Line = Loc.getLine();
151 Column = Loc.getColumn();
154 const std::string DiagnosticInfoWithLocationBase::getLocationStr() const {
155 StringRef Filename("<unknown>");
156 unsigned Line = 0;
157 unsigned Column = 0;
158 if (isLocationAvailable())
159 getLocation(Filename, Line, Column);
160 return (Filename + ":" + Twine(Line) + ":" + Twine(Column)).str();
163 DiagnosticInfoOptimizationBase::Argument::Argument(StringRef Key, const Value *V)
164 : Key(Key) {
165 if (auto *F = dyn_cast<Function>(V)) {
166 if (DISubprogram *SP = F->getSubprogram())
167 Loc = SP;
169 else if (auto *I = dyn_cast<Instruction>(V))
170 Loc = I->getDebugLoc();
172 // Only include names that correspond to user variables. FIXME: We should use
173 // debug info if available to get the name of the user variable.
174 if (isa<llvm::Argument>(V) || isa<GlobalValue>(V))
175 Val = GlobalValue::dropLLVMManglingEscape(V->getName());
176 else if (isa<Constant>(V)) {
177 raw_string_ostream OS(Val);
178 V->printAsOperand(OS, /*PrintType=*/false);
179 } else if (auto *I = dyn_cast<Instruction>(V))
180 Val = I->getOpcodeName();
183 DiagnosticInfoOptimizationBase::Argument::Argument(StringRef Key, const Type *T)
184 : Key(Key) {
185 raw_string_ostream OS(Val);
186 OS << *T;
189 DiagnosticInfoOptimizationBase::Argument::Argument(StringRef Key, StringRef S)
190 : Key(Key), Val(S.str()) {}
192 DiagnosticInfoOptimizationBase::Argument::Argument(StringRef Key, int N)
193 : Key(Key), Val(itostr(N)) {}
195 DiagnosticInfoOptimizationBase::Argument::Argument(StringRef Key, float N)
196 : Key(Key), Val(llvm::to_string(N)) {}
198 DiagnosticInfoOptimizationBase::Argument::Argument(StringRef Key, long N)
199 : Key(Key), Val(itostr(N)) {}
201 DiagnosticInfoOptimizationBase::Argument::Argument(StringRef Key, long long N)
202 : Key(Key), Val(itostr(N)) {}
204 DiagnosticInfoOptimizationBase::Argument::Argument(StringRef Key, unsigned N)
205 : Key(Key), Val(utostr(N)) {}
207 DiagnosticInfoOptimizationBase::Argument::Argument(StringRef Key,
208 unsigned long N)
209 : Key(Key), Val(utostr(N)) {}
211 DiagnosticInfoOptimizationBase::Argument::Argument(StringRef Key,
212 unsigned long long N)
213 : Key(Key), Val(utostr(N)) {}
215 DiagnosticInfoOptimizationBase::Argument::Argument(StringRef Key, DebugLoc Loc)
216 : Key(Key), Loc(Loc) {
217 if (Loc) {
218 Val = (Loc->getFilename() + ":" + Twine(Loc.getLine()) + ":" +
219 Twine(Loc.getCol())).str();
220 } else {
221 Val = "<UNKNOWN LOCATION>";
225 void DiagnosticInfoOptimizationBase::print(DiagnosticPrinter &DP) const {
226 DP << getLocationStr() << ": " << getMsg();
227 if (Hotness)
228 DP << " (hotness: " << *Hotness << ")";
231 OptimizationRemark::OptimizationRemark(const char *PassName,
232 StringRef RemarkName,
233 const DiagnosticLocation &Loc,
234 const Value *CodeRegion)
235 : DiagnosticInfoIROptimization(
236 DK_OptimizationRemark, DS_Remark, PassName, RemarkName,
237 *cast<BasicBlock>(CodeRegion)->getParent(), Loc, CodeRegion) {}
239 OptimizationRemark::OptimizationRemark(const char *PassName,
240 StringRef RemarkName,
241 const Instruction *Inst)
242 : DiagnosticInfoIROptimization(DK_OptimizationRemark, DS_Remark, PassName,
243 RemarkName, *Inst->getParent()->getParent(),
244 Inst->getDebugLoc(), Inst->getParent()) {}
246 // Helper to allow for an assert before attempting to return an invalid
247 // reference.
248 static const BasicBlock &getFirstFunctionBlock(const Function *Func) {
249 assert(!Func->empty() && "Function does not have a body");
250 return Func->front();
253 OptimizationRemark::OptimizationRemark(const char *PassName,
254 StringRef RemarkName,
255 const Function *Func)
256 : DiagnosticInfoIROptimization(DK_OptimizationRemark, DS_Remark, PassName,
257 RemarkName, *Func, Func->getSubprogram(),
258 &getFirstFunctionBlock(Func)) {}
260 bool OptimizationRemark::isEnabled() const {
261 const Function &Fn = getFunction();
262 LLVMContext &Ctx = Fn.getContext();
263 return Ctx.getDiagHandlerPtr()->isPassedOptRemarkEnabled(getPassName());
266 OptimizationRemarkMissed::OptimizationRemarkMissed(
267 const char *PassName, StringRef RemarkName, const DiagnosticLocation &Loc,
268 const Value *CodeRegion)
269 : DiagnosticInfoIROptimization(
270 DK_OptimizationRemarkMissed, DS_Remark, PassName, RemarkName,
271 *cast<BasicBlock>(CodeRegion)->getParent(), Loc, CodeRegion) {}
273 OptimizationRemarkMissed::OptimizationRemarkMissed(const char *PassName,
274 StringRef RemarkName,
275 const Instruction *Inst)
276 : DiagnosticInfoIROptimization(DK_OptimizationRemarkMissed, DS_Remark,
277 PassName, RemarkName,
278 *Inst->getParent()->getParent(),
279 Inst->getDebugLoc(), Inst->getParent()) {}
281 bool OptimizationRemarkMissed::isEnabled() const {
282 const Function &Fn = getFunction();
283 LLVMContext &Ctx = Fn.getContext();
284 return Ctx.getDiagHandlerPtr()->isMissedOptRemarkEnabled(getPassName());
287 OptimizationRemarkAnalysis::OptimizationRemarkAnalysis(
288 const char *PassName, StringRef RemarkName, const DiagnosticLocation &Loc,
289 const Value *CodeRegion)
290 : DiagnosticInfoIROptimization(
291 DK_OptimizationRemarkAnalysis, DS_Remark, PassName, RemarkName,
292 *cast<BasicBlock>(CodeRegion)->getParent(), Loc, CodeRegion) {}
294 OptimizationRemarkAnalysis::OptimizationRemarkAnalysis(const char *PassName,
295 StringRef RemarkName,
296 const Instruction *Inst)
297 : DiagnosticInfoIROptimization(DK_OptimizationRemarkAnalysis, DS_Remark,
298 PassName, RemarkName,
299 *Inst->getParent()->getParent(),
300 Inst->getDebugLoc(), Inst->getParent()) {}
302 OptimizationRemarkAnalysis::OptimizationRemarkAnalysis(
303 enum DiagnosticKind Kind, const char *PassName, StringRef RemarkName,
304 const DiagnosticLocation &Loc, const Value *CodeRegion)
305 : DiagnosticInfoIROptimization(Kind, DS_Remark, PassName, RemarkName,
306 *cast<BasicBlock>(CodeRegion)->getParent(),
307 Loc, CodeRegion) {}
309 bool OptimizationRemarkAnalysis::isEnabled() const {
310 const Function &Fn = getFunction();
311 LLVMContext &Ctx = Fn.getContext();
312 return Ctx.getDiagHandlerPtr()->isAnalysisRemarkEnabled(getPassName()) ||
313 shouldAlwaysPrint();
316 void DiagnosticInfoMIRParser::print(DiagnosticPrinter &DP) const {
317 DP << Diagnostic;
320 DiagnosticInfoOptimizationFailure::DiagnosticInfoOptimizationFailure(
321 const char *PassName, StringRef RemarkName, const DiagnosticLocation &Loc,
322 const Value *CodeRegion)
323 : DiagnosticInfoIROptimization(
324 DK_OptimizationFailure, DS_Warning, PassName, RemarkName,
325 *cast<BasicBlock>(CodeRegion)->getParent(), Loc, CodeRegion) {}
327 bool DiagnosticInfoOptimizationFailure::isEnabled() const {
328 // Only print warnings.
329 return getSeverity() == DS_Warning;
332 void DiagnosticInfoUnsupported::print(DiagnosticPrinter &DP) const {
333 std::string Str;
334 raw_string_ostream OS(Str);
336 OS << getLocationStr() << ": in function " << getFunction().getName() << ' '
337 << *getFunction().getFunctionType() << ": " << Msg << '\n';
338 OS.flush();
339 DP << Str;
342 void DiagnosticInfoISelFallback::print(DiagnosticPrinter &DP) const {
343 DP << "Instruction selection used fallback path for " << getFunction();
346 void DiagnosticInfoOptimizationBase::insert(StringRef S) {
347 Args.emplace_back(S);
350 void DiagnosticInfoOptimizationBase::insert(Argument A) {
351 Args.push_back(std::move(A));
354 void DiagnosticInfoOptimizationBase::insert(setIsVerbose V) {
355 IsVerbose = true;
358 void DiagnosticInfoOptimizationBase::insert(setExtraArgs EA) {
359 FirstExtraArgIndex = Args.size();
362 std::string DiagnosticInfoOptimizationBase::getMsg() const {
363 std::string Str;
364 raw_string_ostream OS(Str);
365 for (const DiagnosticInfoOptimizationBase::Argument &Arg :
366 make_range(Args.begin(), FirstExtraArgIndex == -1
367 ? Args.end()
368 : Args.begin() + FirstExtraArgIndex))
369 OS << Arg.Val;
370 return OS.str();
373 void OptimizationRemarkAnalysisFPCommute::anchor() {}
374 void OptimizationRemarkAnalysisAliasing::anchor() {}
376 namespace llvm {
377 namespace yaml {
379 void MappingTraits<DiagnosticInfoOptimizationBase *>::mapping(
380 IO &io, DiagnosticInfoOptimizationBase *&OptDiag) {
381 assert(io.outputting() && "input not yet implemented");
383 if (io.mapTag("!Passed",
384 (OptDiag->getKind() == DK_OptimizationRemark ||
385 OptDiag->getKind() == DK_MachineOptimizationRemark)))
387 else if (io.mapTag(
388 "!Missed",
389 (OptDiag->getKind() == DK_OptimizationRemarkMissed ||
390 OptDiag->getKind() == DK_MachineOptimizationRemarkMissed)))
392 else if (io.mapTag(
393 "!Analysis",
394 (OptDiag->getKind() == DK_OptimizationRemarkAnalysis ||
395 OptDiag->getKind() == DK_MachineOptimizationRemarkAnalysis)))
397 else if (io.mapTag("!AnalysisFPCommute",
398 OptDiag->getKind() ==
399 DK_OptimizationRemarkAnalysisFPCommute))
401 else if (io.mapTag("!AnalysisAliasing",
402 OptDiag->getKind() ==
403 DK_OptimizationRemarkAnalysisAliasing))
405 else if (io.mapTag("!Failure", OptDiag->getKind() == DK_OptimizationFailure))
407 else
408 llvm_unreachable("Unknown remark type");
410 // These are read-only for now.
411 DiagnosticLocation DL = OptDiag->getLocation();
412 StringRef FN =
413 GlobalValue::dropLLVMManglingEscape(OptDiag->getFunction().getName());
415 StringRef PassName(OptDiag->PassName);
416 io.mapRequired("Pass", PassName);
417 io.mapRequired("Name", OptDiag->RemarkName);
418 if (!io.outputting() || DL.isValid())
419 io.mapOptional("DebugLoc", DL);
420 io.mapRequired("Function", FN);
421 io.mapOptional("Hotness", OptDiag->Hotness);
422 io.mapOptional("Args", OptDiag->Args);
425 template <> struct MappingTraits<DiagnosticLocation> {
426 static void mapping(IO &io, DiagnosticLocation &DL) {
427 assert(io.outputting() && "input not yet implemented");
429 StringRef File = DL.getRelativePath();
430 unsigned Line = DL.getLine();
431 unsigned Col = DL.getColumn();
433 io.mapRequired("File", File);
434 io.mapRequired("Line", Line);
435 io.mapRequired("Column", Col);
438 static const bool flow = true;
441 /// Helper struct for multiline string block literals. Use this type to preserve
442 /// newlines in strings.
443 struct StringBlockVal {
444 StringRef Value;
445 StringBlockVal(const std::string &Value) : Value(Value) {}
448 template <> struct BlockScalarTraits<StringBlockVal> {
449 static void output(const StringBlockVal &S, void *Ctx, raw_ostream &OS) {
450 return ScalarTraits<StringRef>::output(S.Value, Ctx, OS);
453 static StringRef input(StringRef Scalar, void *Ctx, StringBlockVal &S) {
454 return ScalarTraits<StringRef>::input(Scalar, Ctx, S.Value);
458 // Implement this as a mapping for now to get proper quotation for the value.
459 template <> struct MappingTraits<DiagnosticInfoOptimizationBase::Argument> {
460 static void mapping(IO &io, DiagnosticInfoOptimizationBase::Argument &A) {
461 assert(io.outputting() && "input not yet implemented");
462 // Emit a string block scalar for multiline strings, to preserve newlines.
463 if (StringRef(A.Val).count('\n') > 1) {
464 StringBlockVal S(A.Val);
465 io.mapRequired(A.Key.data(), S);
466 } else
467 io.mapRequired(A.Key.data(), A.Val);
468 if (A.Loc.isValid())
469 io.mapOptional("DebugLoc", A.Loc);
473 } // end namespace yaml
474 } // end namespace llvm
476 LLVM_YAML_IS_SEQUENCE_VECTOR(DiagnosticInfoOptimizationBase::Argument)