]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/IR/DiagnosticInfo.cpp
Merge llvm, clang, compiler-rt, libc++, libunwind, lld, lldb and openmp
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / IR / DiagnosticInfo.cpp
1 //===- llvm/Support/DiagnosticInfo.cpp - Diagnostic Definitions -*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the different classes involved in low level diagnostics.
11 //
12 // Diagnostics reporting is still done as part of the LLVMContext.
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/IR/DiagnosticInfo.h"
16 #include "LLVMContextImpl.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/ADT/iterator_range.h"
20 #include "llvm/IR/BasicBlock.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DebugInfoMetadata.h"
23 #include "llvm/IR/DerivedTypes.h"
24 #include "llvm/IR/DiagnosticPrinter.h"
25 #include "llvm/IR/Function.h"
26 #include "llvm/IR/GlobalValue.h"
27 #include "llvm/IR/Instruction.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/IR/Metadata.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/Type.h"
32 #include "llvm/IR/Value.h"
33 #include "llvm/Support/Casting.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/Path.h"
37 #include "llvm/Support/Regex.h"
38 #include "llvm/Support/ScopedPrinter.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include <atomic>
41 #include <cassert>
42 #include <memory>
43 #include <string>
44
45 using namespace llvm;
46
47 int llvm::getNextAvailablePluginDiagnosticKind() {
48   static std::atomic<int> PluginKindID(DK_FirstPluginKind);
49   return ++PluginKindID;
50 }
51
52 const char *OptimizationRemarkAnalysis::AlwaysPrint = "";
53
54 DiagnosticInfoInlineAsm::DiagnosticInfoInlineAsm(const Instruction &I,
55                                                  const Twine &MsgStr,
56                                                  DiagnosticSeverity Severity)
57     : DiagnosticInfo(DK_InlineAsm, Severity), MsgStr(MsgStr), Instr(&I) {
58   if (const MDNode *SrcLoc = I.getMetadata("srcloc")) {
59     if (SrcLoc->getNumOperands() != 0)
60       if (const auto *CI =
61               mdconst::dyn_extract<ConstantInt>(SrcLoc->getOperand(0)))
62         LocCookie = CI->getZExtValue();
63   }
64 }
65
66 void DiagnosticInfoInlineAsm::print(DiagnosticPrinter &DP) const {
67   DP << getMsgStr();
68   if (getLocCookie())
69     DP << " at line " << getLocCookie();
70 }
71
72 void DiagnosticInfoResourceLimit::print(DiagnosticPrinter &DP) const {
73   DP << getResourceName() << " limit";
74
75   if (getResourceLimit() != 0)
76     DP << " of " << getResourceLimit();
77
78   DP << " exceeded (" <<  getResourceSize() << ") in " << getFunction();
79 }
80
81 void DiagnosticInfoDebugMetadataVersion::print(DiagnosticPrinter &DP) const {
82   DP << "ignoring debug info with an invalid version (" << getMetadataVersion()
83      << ") in " << getModule();
84 }
85
86 void DiagnosticInfoIgnoringInvalidDebugMetadata::print(
87     DiagnosticPrinter &DP) const {
88   DP << "ignoring invalid debug info in " << getModule().getModuleIdentifier();
89 }
90
91 void DiagnosticInfoSampleProfile::print(DiagnosticPrinter &DP) const {
92   if (!FileName.empty()) {
93     DP << getFileName();
94     if (LineNum > 0)
95       DP << ":" << getLineNum();
96     DP << ": ";
97   }
98   DP << getMsg();
99 }
100
101 void DiagnosticInfoPGOProfile::print(DiagnosticPrinter &DP) const {
102   if (getFileName())
103     DP << getFileName() << ": ";
104   DP << getMsg();
105 }
106
107 void DiagnosticInfo::anchor() {}
108 void DiagnosticInfoStackSize::anchor() {}
109 void DiagnosticInfoWithLocationBase::anchor() {}
110 void DiagnosticInfoIROptimization::anchor() {}
111
112 DiagnosticLocation::DiagnosticLocation(const DebugLoc &DL) {
113   if (!DL)
114     return;
115   File = DL->getFile();
116   Line = DL->getLine();
117   Column = DL->getColumn();
118 }
119
120 DiagnosticLocation::DiagnosticLocation(const DISubprogram *SP) {
121   if (!SP)
122     return;
123   
124   File = SP->getFile();
125   Line = SP->getScopeLine();
126   Column = 0;
127 }
128
129 StringRef DiagnosticLocation::getRelativePath() const {
130   return File->getFilename();
131 }
132
133 std::string DiagnosticLocation::getAbsolutePath() const {
134   StringRef Name = File->getFilename();
135   if (sys::path::is_absolute(Name))
136     return Name;
137
138   SmallString<128> Path;
139   sys::path::append(Path, File->getDirectory(), Name);
140   return sys::path::remove_leading_dotslash(Path).str();
141 }
142
143 std::string DiagnosticInfoWithLocationBase::getAbsolutePath() const {
144   return Loc.getAbsolutePath();
145 }
146
147 void DiagnosticInfoWithLocationBase::getLocation(StringRef &RelativePath,
148                                                  unsigned &Line,
149                                                  unsigned &Column) const {
150   RelativePath = Loc.getRelativePath();
151   Line = Loc.getLine();
152   Column = Loc.getColumn();
153 }
154
155 const std::string DiagnosticInfoWithLocationBase::getLocationStr() const {
156   StringRef Filename("<unknown>");
157   unsigned Line = 0;
158   unsigned Column = 0;
159   if (isLocationAvailable())
160     getLocation(Filename, Line, Column);
161   return (Filename + ":" + Twine(Line) + ":" + Twine(Column)).str();
162 }
163
164 DiagnosticInfoOptimizationBase::Argument::Argument(StringRef Key, const Value *V)
165     : Key(Key) {
166   if (auto *F = dyn_cast<Function>(V)) {
167     if (DISubprogram *SP = F->getSubprogram())
168       Loc = SP;
169   }
170   else if (auto *I = dyn_cast<Instruction>(V))
171     Loc = I->getDebugLoc();
172
173   // Only include names that correspond to user variables.  FIXME: We should use
174   // debug info if available to get the name of the user variable.
175   if (isa<llvm::Argument>(V) || isa<GlobalValue>(V))
176     Val = GlobalValue::dropLLVMManglingEscape(V->getName());
177   else if (isa<Constant>(V)) {
178     raw_string_ostream OS(Val);
179     V->printAsOperand(OS, /*PrintType=*/false);
180   } else if (auto *I = dyn_cast<Instruction>(V))
181     Val = I->getOpcodeName();
182 }
183
184 DiagnosticInfoOptimizationBase::Argument::Argument(StringRef Key, const Type *T)
185     : Key(Key) {
186   raw_string_ostream OS(Val);
187   OS << *T;
188 }
189
190 DiagnosticInfoOptimizationBase::Argument::Argument(StringRef Key, StringRef S)
191     : Key(Key), Val(S.str()) {}
192
193 DiagnosticInfoOptimizationBase::Argument::Argument(StringRef Key, int N)
194     : Key(Key), Val(itostr(N)) {}
195
196 DiagnosticInfoOptimizationBase::Argument::Argument(StringRef Key, float N)
197     : Key(Key), Val(llvm::to_string(N)) {}
198
199 DiagnosticInfoOptimizationBase::Argument::Argument(StringRef Key, long N)
200     : Key(Key), Val(itostr(N)) {}
201
202 DiagnosticInfoOptimizationBase::Argument::Argument(StringRef Key, long long N)
203     : Key(Key), Val(itostr(N)) {}
204
205 DiagnosticInfoOptimizationBase::Argument::Argument(StringRef Key, unsigned N)
206     : Key(Key), Val(utostr(N)) {}
207
208 DiagnosticInfoOptimizationBase::Argument::Argument(StringRef Key,
209                                                    unsigned long N)
210     : Key(Key), Val(utostr(N)) {}
211
212 DiagnosticInfoOptimizationBase::Argument::Argument(StringRef Key,
213                                                    unsigned long long N)
214     : Key(Key), Val(utostr(N)) {}
215
216 DiagnosticInfoOptimizationBase::Argument::Argument(StringRef Key, DebugLoc Loc)
217     : Key(Key), Loc(Loc) {
218   if (Loc) {
219     Val = (Loc->getFilename() + ":" + Twine(Loc.getLine()) + ":" +
220            Twine(Loc.getCol())).str();
221   } else {
222     Val = "<UNKNOWN LOCATION>";
223   }
224 }
225
226 void DiagnosticInfoOptimizationBase::print(DiagnosticPrinter &DP) const {
227   DP << getLocationStr() << ": " << getMsg();
228   if (Hotness)
229     DP << " (hotness: " << *Hotness << ")";
230 }
231
232 OptimizationRemark::OptimizationRemark(const char *PassName,
233                                        StringRef RemarkName,
234                                        const DiagnosticLocation &Loc,
235                                        const Value *CodeRegion)
236     : DiagnosticInfoIROptimization(
237           DK_OptimizationRemark, DS_Remark, PassName, RemarkName,
238           *cast<BasicBlock>(CodeRegion)->getParent(), Loc, CodeRegion) {}
239
240 OptimizationRemark::OptimizationRemark(const char *PassName,
241                                        StringRef RemarkName,
242                                        const Instruction *Inst)
243     : DiagnosticInfoIROptimization(DK_OptimizationRemark, DS_Remark, PassName,
244                                    RemarkName, *Inst->getParent()->getParent(),
245                                    Inst->getDebugLoc(), Inst->getParent()) {}
246
247 // Helper to allow for an assert before attempting to return an invalid
248 // reference.
249 static const BasicBlock &getFirstFunctionBlock(const Function *Func) {
250   assert(!Func->empty() && "Function does not have a body");
251   return Func->front();
252 }
253
254 OptimizationRemark::OptimizationRemark(const char *PassName,
255                                        StringRef RemarkName,
256                                        const Function *Func)
257     : DiagnosticInfoIROptimization(DK_OptimizationRemark, DS_Remark, PassName,
258                                    RemarkName, *Func, Func->getSubprogram(),
259                                    &getFirstFunctionBlock(Func)) {}
260
261 bool OptimizationRemark::isEnabled() const {
262   const Function &Fn = getFunction();
263   LLVMContext &Ctx = Fn.getContext();
264   return Ctx.getDiagHandlerPtr()->isPassedOptRemarkEnabled(getPassName());
265 }
266
267 OptimizationRemarkMissed::OptimizationRemarkMissed(
268     const char *PassName, StringRef RemarkName, const DiagnosticLocation &Loc,
269     const Value *CodeRegion)
270     : DiagnosticInfoIROptimization(
271           DK_OptimizationRemarkMissed, DS_Remark, PassName, RemarkName,
272           *cast<BasicBlock>(CodeRegion)->getParent(), Loc, CodeRegion) {}
273
274 OptimizationRemarkMissed::OptimizationRemarkMissed(const char *PassName,
275                                                    StringRef RemarkName,
276                                                    const Instruction *Inst)
277     : DiagnosticInfoIROptimization(DK_OptimizationRemarkMissed, DS_Remark,
278                                    PassName, RemarkName,
279                                    *Inst->getParent()->getParent(),
280                                    Inst->getDebugLoc(), Inst->getParent()) {}
281
282 bool OptimizationRemarkMissed::isEnabled() const {
283   const Function &Fn = getFunction();
284   LLVMContext &Ctx = Fn.getContext();
285   return Ctx.getDiagHandlerPtr()->isMissedOptRemarkEnabled(getPassName());
286 }
287
288 OptimizationRemarkAnalysis::OptimizationRemarkAnalysis(
289     const char *PassName, StringRef RemarkName, const DiagnosticLocation &Loc,
290     const Value *CodeRegion)
291     : DiagnosticInfoIROptimization(
292           DK_OptimizationRemarkAnalysis, DS_Remark, PassName, RemarkName,
293           *cast<BasicBlock>(CodeRegion)->getParent(), Loc, CodeRegion) {}
294
295 OptimizationRemarkAnalysis::OptimizationRemarkAnalysis(const char *PassName,
296                                                        StringRef RemarkName,
297                                                        const Instruction *Inst)
298     : DiagnosticInfoIROptimization(DK_OptimizationRemarkAnalysis, DS_Remark,
299                                    PassName, RemarkName,
300                                    *Inst->getParent()->getParent(),
301                                    Inst->getDebugLoc(), Inst->getParent()) {}
302
303 OptimizationRemarkAnalysis::OptimizationRemarkAnalysis(
304     enum DiagnosticKind Kind, const char *PassName, StringRef RemarkName,
305     const DiagnosticLocation &Loc, const Value *CodeRegion)
306     : DiagnosticInfoIROptimization(Kind, DS_Remark, PassName, RemarkName,
307                                    *cast<BasicBlock>(CodeRegion)->getParent(),
308                                    Loc, CodeRegion) {}
309
310 bool OptimizationRemarkAnalysis::isEnabled() const {
311   const Function &Fn = getFunction();
312   LLVMContext &Ctx = Fn.getContext();
313   return Ctx.getDiagHandlerPtr()->isAnalysisRemarkEnabled(getPassName()) ||
314          shouldAlwaysPrint();
315 }
316
317 void DiagnosticInfoMIRParser::print(DiagnosticPrinter &DP) const {
318   DP << Diagnostic;
319 }
320
321 DiagnosticInfoOptimizationFailure::DiagnosticInfoOptimizationFailure(
322     const char *PassName, StringRef RemarkName, const DiagnosticLocation &Loc,
323     const Value *CodeRegion)
324     : DiagnosticInfoIROptimization(
325           DK_OptimizationFailure, DS_Warning, PassName, RemarkName,
326           *cast<BasicBlock>(CodeRegion)->getParent(), Loc, CodeRegion) {}
327
328 bool DiagnosticInfoOptimizationFailure::isEnabled() const {
329   // Only print warnings.
330   return getSeverity() == DS_Warning;
331 }
332
333 void DiagnosticInfoUnsupported::print(DiagnosticPrinter &DP) const {
334   std::string Str;
335   raw_string_ostream OS(Str);
336
337   OS << getLocationStr() << ": in function " << getFunction().getName() << ' '
338      << *getFunction().getFunctionType() << ": " << Msg << '\n';
339   OS.flush();
340   DP << Str;
341 }
342
343 void DiagnosticInfoISelFallback::print(DiagnosticPrinter &DP) const {
344   DP << "Instruction selection used fallback path for " << getFunction();
345 }
346
347 void DiagnosticInfoOptimizationBase::insert(StringRef S) {
348   Args.emplace_back(S);
349 }
350
351 void DiagnosticInfoOptimizationBase::insert(Argument A) {
352   Args.push_back(std::move(A));
353 }
354
355 void DiagnosticInfoOptimizationBase::insert(setIsVerbose V) {
356   IsVerbose = true;
357 }
358
359 void DiagnosticInfoOptimizationBase::insert(setExtraArgs EA) {
360   FirstExtraArgIndex = Args.size();
361 }
362
363 std::string DiagnosticInfoOptimizationBase::getMsg() const {
364   std::string Str;
365   raw_string_ostream OS(Str);
366   for (const DiagnosticInfoOptimizationBase::Argument &Arg :
367        make_range(Args.begin(), FirstExtraArgIndex == -1
368                                     ? Args.end()
369                                     : Args.begin() + FirstExtraArgIndex))
370     OS << Arg.Val;
371   return OS.str();
372 }
373
374 void OptimizationRemarkAnalysisFPCommute::anchor() {}
375 void OptimizationRemarkAnalysisAliasing::anchor() {}
376
377 namespace llvm {
378 namespace yaml {
379
380 void MappingTraits<DiagnosticInfoOptimizationBase *>::mapping(
381     IO &io, DiagnosticInfoOptimizationBase *&OptDiag) {
382   assert(io.outputting() && "input not yet implemented");
383
384   if (io.mapTag("!Passed",
385                 (OptDiag->getKind() == DK_OptimizationRemark ||
386                  OptDiag->getKind() == DK_MachineOptimizationRemark)))
387     ;
388   else if (io.mapTag(
389                "!Missed",
390                (OptDiag->getKind() == DK_OptimizationRemarkMissed ||
391                 OptDiag->getKind() == DK_MachineOptimizationRemarkMissed)))
392     ;
393   else if (io.mapTag(
394                "!Analysis",
395                (OptDiag->getKind() == DK_OptimizationRemarkAnalysis ||
396                 OptDiag->getKind() == DK_MachineOptimizationRemarkAnalysis)))
397     ;
398   else if (io.mapTag("!AnalysisFPCommute",
399                      OptDiag->getKind() ==
400                          DK_OptimizationRemarkAnalysisFPCommute))
401     ;
402   else if (io.mapTag("!AnalysisAliasing",
403                      OptDiag->getKind() ==
404                          DK_OptimizationRemarkAnalysisAliasing))
405     ;
406   else if (io.mapTag("!Failure", OptDiag->getKind() == DK_OptimizationFailure))
407     ;
408   else
409     llvm_unreachable("Unknown remark type");
410
411   // These are read-only for now.
412   DiagnosticLocation DL = OptDiag->getLocation();
413   StringRef FN =
414       GlobalValue::dropLLVMManglingEscape(OptDiag->getFunction().getName());
415
416   StringRef PassName(OptDiag->PassName);
417   io.mapRequired("Pass", PassName);
418   io.mapRequired("Name", OptDiag->RemarkName);
419   if (!io.outputting() || DL.isValid())
420     io.mapOptional("DebugLoc", DL);
421   io.mapRequired("Function", FN);
422   io.mapOptional("Hotness", OptDiag->Hotness);
423   io.mapOptional("Args", OptDiag->Args);
424 }
425
426 template <> struct MappingTraits<DiagnosticLocation> {
427   static void mapping(IO &io, DiagnosticLocation &DL) {
428     assert(io.outputting() && "input not yet implemented");
429
430     StringRef File = DL.getRelativePath();
431     unsigned Line = DL.getLine();
432     unsigned Col = DL.getColumn();
433
434     io.mapRequired("File", File);
435     io.mapRequired("Line", Line);
436     io.mapRequired("Column", Col);
437   }
438
439   static const bool flow = true;
440 };
441
442 // Implement this as a mapping for now to get proper quotation for the value.
443 template <> struct MappingTraits<DiagnosticInfoOptimizationBase::Argument> {
444   static void mapping(IO &io, DiagnosticInfoOptimizationBase::Argument &A) {
445     assert(io.outputting() && "input not yet implemented");
446     io.mapRequired(A.Key.data(), A.Val);
447     if (A.Loc.isValid())
448       io.mapOptional("DebugLoc", A.Loc);
449   }
450 };
451
452 } // end namespace yaml
453 } // end namespace llvm
454
455 LLVM_YAML_IS_SEQUENCE_VECTOR(DiagnosticInfoOptimizationBase::Argument)