1 //===------------------ llvm-opt-report/OptReport.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 /// \file
10 /// This file implements a tool that can parse the YAML optimization
11 /// records and generate an optimization summary annotated source listing
12 /// report.
13 ///
14 //===----------------------------------------------------------------------===//
15 
16 #include "llvm-c/Remarks.h"
17 #include "llvm/Demangle/Demangle.h"
18 #include "llvm/Remarks/RemarkFormat.h"
19 #include "llvm/Remarks/RemarkParser.h"
20 #include "llvm/Support/CommandLine.h"
21 #include "llvm/Support/Error.h"
22 #include "llvm/Support/ErrorOr.h"
23 #include "llvm/Support/FileSystem.h"
24 #include "llvm/Support/Format.h"
25 #include "llvm/Support/InitLLVM.h"
26 #include "llvm/Support/LineIterator.h"
27 #include "llvm/Support/MemoryBuffer.h"
28 #include "llvm/Support/Path.h"
29 #include "llvm/Support/Program.h"
30 #include "llvm/Support/WithColor.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include <cstdlib>
33 #include <map>
34 #include <set>
35 
36 using namespace llvm;
37 
38 // Mark all our options with this category, everything else (except for -version
39 // and -help) will be hidden.
40 static cl::OptionCategory
41     OptReportCategory("llvm-opt-report options");
42 
43 static cl::opt<std::string>
44   InputFileName(cl::Positional, cl::desc("<input>"), cl::init("-"),
45                 cl::cat(OptReportCategory));
46 
47 static cl::opt<std::string>
48   OutputFileName("o", cl::desc("Output file"), cl::init("-"),
49                  cl::cat(OptReportCategory));
50 
51 static cl::opt<std::string>
52   InputRelDir("r", cl::desc("Root for relative input paths"), cl::init(""),
53               cl::cat(OptReportCategory));
54 
55 static cl::opt<bool>
56   Succinct("s", cl::desc("Don't include vectorization factors, etc."),
57            cl::init(false), cl::cat(OptReportCategory));
58 
59 static cl::opt<bool>
60   NoDemangle("no-demangle", cl::desc("Don't demangle function names"),
61              cl::init(false), cl::cat(OptReportCategory));
62 
63 static cl::opt<std::string> ParserFormat("format",
64                                          cl::desc("The format of the remarks."),
65                                          cl::init("yaml"),
66                                          cl::cat(OptReportCategory));
67 
68 namespace {
69 // For each location in the source file, the common per-transformation state
70 // collected.
71 struct OptReportLocationItemInfo {
72   bool Analyzed = false;
73   bool Transformed = false;
74 
75   OptReportLocationItemInfo &operator |= (
76     const OptReportLocationItemInfo &RHS) {
77     Analyzed |= RHS.Analyzed;
78     Transformed |= RHS.Transformed;
79 
80     return *this;
81   }
82 
83   bool operator < (const OptReportLocationItemInfo &RHS) const {
84     if (Analyzed < RHS.Analyzed)
85       return true;
86     else if (Analyzed > RHS.Analyzed)
87       return false;
88     else if (Transformed < RHS.Transformed)
89       return true;
90     return false;
91   }
92 };
93 
94 // The per-location information collected for producing an optimization report.
95 struct OptReportLocationInfo {
96   OptReportLocationItemInfo Inlined;
97   OptReportLocationItemInfo Unrolled;
98   OptReportLocationItemInfo Vectorized;
99 
100   int VectorizationFactor = 1;
101   int InterleaveCount = 1;
102   int UnrollCount = 1;
103 
104   OptReportLocationInfo &operator |= (const OptReportLocationInfo &RHS) {
105     Inlined |= RHS.Inlined;
106     Unrolled |= RHS.Unrolled;
107     Vectorized |= RHS.Vectorized;
108 
109     VectorizationFactor =
110       std::max(VectorizationFactor, RHS.VectorizationFactor);
111     InterleaveCount = std::max(InterleaveCount, RHS.InterleaveCount);
112     UnrollCount = std::max(UnrollCount, RHS.UnrollCount);
113 
114     return *this;
115   }
116 
117   bool operator < (const OptReportLocationInfo &RHS) const {
118     if (Inlined < RHS.Inlined)
119       return true;
120     else if (RHS.Inlined < Inlined)
121       return false;
122     else if (Unrolled < RHS.Unrolled)
123       return true;
124     else if (RHS.Unrolled < Unrolled)
125       return false;
126     else if (Vectorized < RHS.Vectorized)
127       return true;
128     else if (RHS.Vectorized < Vectorized || Succinct)
129       return false;
130     else if (VectorizationFactor < RHS.VectorizationFactor)
131       return true;
132     else if (VectorizationFactor > RHS.VectorizationFactor)
133       return false;
134     else if (InterleaveCount < RHS.InterleaveCount)
135       return true;
136     else if (InterleaveCount > RHS.InterleaveCount)
137       return false;
138     else if (UnrollCount < RHS.UnrollCount)
139       return true;
140     return false;
141   }
142 };
143 
144 typedef std::map<std::string, std::map<int, std::map<std::string, std::map<int,
145           OptReportLocationInfo>>>> LocationInfoTy;
146 } // anonymous namespace
147 
148 static bool readLocationInfo(LocationInfoTy &LocationInfo) {
149   ErrorOr<std::unique_ptr<MemoryBuffer>> Buf =
150       MemoryBuffer::getFile(InputFileName.c_str());
151   if (std::error_code EC = Buf.getError()) {
152     WithColor::error() << "Can't open file " << InputFileName << ": "
153                        << EC.message() << "\n";
154     return false;
155   }
156 
157   Expected<remarks::Format> Format = remarks::parseFormat(ParserFormat);
158   if (!Format) {
159     handleAllErrors(Format.takeError(), [&](const ErrorInfoBase &PE) {
160       PE.log(WithColor::error());
161       WithColor::error() << '\n';
162     });
163     return false;
164   }
165 
166   Expected<std::unique_ptr<remarks::RemarkParser>> MaybeParser =
167       remarks::createRemarkParser(*Format, (*Buf)->getBuffer());
168   if (!MaybeParser) {
169     handleAllErrors(MaybeParser.takeError(), [&](const ErrorInfoBase &PE) {
170       PE.log(WithColor::error());
171     });
172     return false;
173   }
174   remarks::RemarkParser &Parser = **MaybeParser;
175 
176   while (true) {
177     Expected<std::unique_ptr<remarks::Remark>> MaybeRemark = Parser.next();
178     if (!MaybeRemark) {
179       Error E = MaybeRemark.takeError();
180       if (E.isA<remarks::EndOfFileError>()) {
181         // EOF.
182         consumeError(std::move(E));
183         break;
184       }
185       handleAllErrors(MaybeRemark.takeError(), [&](const ErrorInfoBase &PE) {
186         PE.log(WithColor::error());
187       });
188       return false;
189     }
190 
191     const remarks::Remark &Remark = **MaybeRemark;
192 
193     bool Transformed = Remark.RemarkType == remarks::Type::Passed;
194 
195     int VectorizationFactor = 1;
196     int InterleaveCount = 1;
197     int UnrollCount = 1;
198 
199     for (const remarks::Argument &Arg : Remark.Args) {
200       if (Arg.Key == "VectorizationFactor")
201         Arg.Val.getAsInteger(10, VectorizationFactor);
202       else if (Arg.Key == "InterleaveCount")
203         Arg.Val.getAsInteger(10, InterleaveCount);
204       else if (Arg.Key == "UnrollCount")
205         Arg.Val.getAsInteger(10, UnrollCount);
206     }
207 
208     const Optional<remarks::RemarkLocation> &Loc = Remark.Loc;
209     if (!Loc)
210       continue;
211 
212     StringRef File = Loc->SourceFilePath;
213     unsigned Line = Loc->SourceLine;
214     unsigned Column = Loc->SourceColumn;
215 
216     // We track information on both actual and potential transformations. This
217     // way, if there are multiple possible things on a line that are, or could
218     // have been transformed, we can indicate that explicitly in the output.
219     auto UpdateLLII = [Transformed](OptReportLocationItemInfo &LLII) {
220       LLII.Analyzed = true;
221       if (Transformed)
222         LLII.Transformed = true;
223     };
224 
225     if (Remark.PassName == "inline") {
226       auto &LI = LocationInfo[File][Line][Remark.FunctionName][Column];
227       UpdateLLII(LI.Inlined);
228     } else if (Remark.PassName == "loop-unroll") {
229       auto &LI = LocationInfo[File][Line][Remark.FunctionName][Column];
230       LI.UnrollCount = UnrollCount;
231       UpdateLLII(LI.Unrolled);
232     } else if (Remark.PassName == "loop-vectorize") {
233       auto &LI = LocationInfo[File][Line][Remark.FunctionName][Column];
234       LI.VectorizationFactor = VectorizationFactor;
235       LI.InterleaveCount = InterleaveCount;
236       UpdateLLII(LI.Vectorized);
237     }
238   }
239 
240   return true;
241 }
242 
243 static bool writeReport(LocationInfoTy &LocationInfo) {
244   std::error_code EC;
245   llvm::raw_fd_ostream OS(OutputFileName, EC,
246               llvm::sys::fs::F_Text);
247   if (EC) {
248     WithColor::error() << "Can't open file " << OutputFileName << ": "
249                        << EC.message() << "\n";
250     return false;
251   }
252 
253   bool FirstFile = true;
254   for (auto &FI : LocationInfo) {
255     SmallString<128> FileName(FI.first);
256     if (!InputRelDir.empty())
257       sys::fs::make_absolute(InputRelDir, FileName);
258 
259     const auto &FileInfo = FI.second;
260 
261     ErrorOr<std::unique_ptr<MemoryBuffer>> Buf =
262         MemoryBuffer::getFile(FileName);
263     if (std::error_code EC = Buf.getError()) {
264       WithColor::error() << "Can't open file " << FileName << ": "
265                          << EC.message() << "\n";
266       return false;
267     }
268 
269     if (FirstFile)
270       FirstFile = false;
271     else
272       OS << "\n";
273 
274     OS << "< " << FileName << "\n";
275 
276     // Figure out how many characters we need for the vectorization factors
277     // and similar.
278     OptReportLocationInfo MaxLI;
279     for (auto &FLI : FileInfo)
280       for (auto &FI : FLI.second)
281         for (auto &LI : FI.second)
282           MaxLI |= LI.second;
283 
284     bool NothingInlined = !MaxLI.Inlined.Transformed;
285     bool NothingUnrolled = !MaxLI.Unrolled.Transformed;
286     bool NothingVectorized = !MaxLI.Vectorized.Transformed;
287 
288     unsigned VFDigits = llvm::utostr(MaxLI.VectorizationFactor).size();
289     unsigned ICDigits = llvm::utostr(MaxLI.InterleaveCount).size();
290     unsigned UCDigits = llvm::utostr(MaxLI.UnrollCount).size();
291 
292     // Figure out how many characters we need for the line numbers.
293     int64_t NumLines = 0;
294     for (line_iterator LI(*Buf.get(), false); LI != line_iterator(); ++LI)
295       ++NumLines;
296 
297     unsigned LNDigits = llvm::utostr(NumLines).size();
298 
299     for (line_iterator LI(*Buf.get(), false); LI != line_iterator(); ++LI) {
300       int64_t L = LI.line_number();
301       auto LII = FileInfo.find(L);
302 
303       auto PrintLine = [&](bool PrintFuncName,
304                            const std::set<std::string> &FuncNameSet) {
305         OptReportLocationInfo LLI;
306 
307         std::map<int, OptReportLocationInfo> ColsInfo;
308         unsigned InlinedCols = 0, UnrolledCols = 0, VectorizedCols = 0;
309 
310         if (LII != FileInfo.end() && !FuncNameSet.empty()) {
311           const auto &LineInfo = LII->second;
312 
313           for (auto &CI : LineInfo.find(*FuncNameSet.begin())->second) {
314             int Col = CI.first;
315             ColsInfo[Col] = CI.second;
316             InlinedCols += CI.second.Inlined.Analyzed;
317             UnrolledCols += CI.second.Unrolled.Analyzed;
318             VectorizedCols += CI.second.Vectorized.Analyzed;
319             LLI |= CI.second;
320           }
321         }
322 
323         if (PrintFuncName) {
324           OS << "  > ";
325 
326           bool FirstFunc = true;
327           for (const auto &FuncName : FuncNameSet) {
328             if (FirstFunc)
329               FirstFunc = false;
330             else
331               OS << ", ";
332 
333             bool Printed = false;
334             if (!NoDemangle) {
335               int Status = 0;
336               char *Demangled =
337                 itaniumDemangle(FuncName.c_str(), nullptr, nullptr, &Status);
338               if (Demangled && Status == 0) {
339                 OS << Demangled;
340                 Printed = true;
341               }
342 
343               if (Demangled)
344                 std::free(Demangled);
345             }
346 
347             if (!Printed)
348               OS << FuncName;
349           }
350 
351           OS << ":\n";
352         }
353 
354         // We try to keep the output as concise as possible. If only one thing on
355         // a given line could have been inlined, vectorized, etc. then we can put
356         // the marker on the source line itself. If there are multiple options
357         // then we want to distinguish them by placing the marker for each
358         // transformation on a separate line following the source line. When we
359         // do this, we use a '^' character to point to the appropriate column in
360         // the source line.
361 
362         std::string USpaces(Succinct ? 0 : UCDigits, ' ');
363         std::string VSpaces(Succinct ? 0 : VFDigits + ICDigits + 1, ' ');
364 
365         auto UStr = [UCDigits](OptReportLocationInfo &LLI) {
366           std::string R;
367           raw_string_ostream RS(R);
368 
369           if (!Succinct) {
370             RS << LLI.UnrollCount;
371             RS << std::string(UCDigits - RS.str().size(), ' ');
372           }
373 
374           return RS.str();
375         };
376 
377         auto VStr = [VFDigits,
378                      ICDigits](OptReportLocationInfo &LLI) -> std::string {
379           std::string R;
380           raw_string_ostream RS(R);
381 
382           if (!Succinct) {
383             RS << LLI.VectorizationFactor << "," << LLI.InterleaveCount;
384             RS << std::string(VFDigits + ICDigits + 1 - RS.str().size(), ' ');
385           }
386 
387           return RS.str();
388         };
389 
390         OS << llvm::format_decimal(L, LNDigits) << " ";
391         OS << (LLI.Inlined.Transformed && InlinedCols < 2 ? "I" :
392                 (NothingInlined ? "" : " "));
393         OS << (LLI.Unrolled.Transformed && UnrolledCols < 2 ?
394                 "U" + UStr(LLI) : (NothingUnrolled ? "" : " " + USpaces));
395         OS << (LLI.Vectorized.Transformed && VectorizedCols < 2 ?
396                 "V" + VStr(LLI) : (NothingVectorized ? "" : " " + VSpaces));
397 
398         OS << " | " << *LI << "\n";
399 
400         for (auto &J : ColsInfo) {
401           if ((J.second.Inlined.Transformed && InlinedCols > 1) ||
402               (J.second.Unrolled.Transformed && UnrolledCols > 1) ||
403               (J.second.Vectorized.Transformed && VectorizedCols > 1)) {
404             OS << std::string(LNDigits + 1, ' ');
405             OS << (J.second.Inlined.Transformed &&
406                    InlinedCols > 1 ? "I" : (NothingInlined ? "" : " "));
407             OS << (J.second.Unrolled.Transformed &&
408                    UnrolledCols > 1 ? "U" + UStr(J.second) :
409                      (NothingUnrolled ? "" : " " + USpaces));
410             OS << (J.second.Vectorized.Transformed &&
411                    VectorizedCols > 1 ? "V" + VStr(J.second) :
412                      (NothingVectorized ? "" : " " + VSpaces));
413 
414             OS << " | " << std::string(J.first - 1, ' ') << "^\n";
415           }
416         }
417       };
418 
419       // We need to figure out if the optimizations for this line were the same
420       // in each function context. If not, then we want to group the similar
421       // function contexts together and display each group separately. If
422       // they're all the same, then we only display the line once without any
423       // additional markings.
424       std::map<std::map<int, OptReportLocationInfo>,
425                std::set<std::string>> UniqueLIs;
426 
427       OptReportLocationInfo AllLI;
428       if (LII != FileInfo.end()) {
429         const auto &FuncLineInfo = LII->second;
430         for (const auto &FLII : FuncLineInfo) {
431           UniqueLIs[FLII.second].insert(FLII.first);
432 
433           for (const auto &OI : FLII.second)
434             AllLI |= OI.second;
435         }
436       }
437 
438       bool NothingHappened = !AllLI.Inlined.Transformed &&
439                              !AllLI.Unrolled.Transformed &&
440                              !AllLI.Vectorized.Transformed;
441       if (UniqueLIs.size() > 1 && !NothingHappened) {
442         OS << " [[\n";
443         for (const auto &FSLI : UniqueLIs)
444           PrintLine(true, FSLI.second);
445         OS << " ]]\n";
446       } else if (UniqueLIs.size() == 1) {
447         PrintLine(false, UniqueLIs.begin()->second);
448       } else {
449         PrintLine(false, std::set<std::string>());
450       }
451     }
452   }
453 
454   return true;
455 }
456 
457 int main(int argc, const char **argv) {
458   InitLLVM X(argc, argv);
459 
460   cl::HideUnrelatedOptions(OptReportCategory);
461   cl::ParseCommandLineOptions(
462       argc, argv,
463       "A tool to generate an optimization report from YAML optimization"
464       " record files.\n");
465 
466   LocationInfoTy LocationInfo;
467   if (!readLocationInfo(LocationInfo))
468     return 1;
469   if (!writeReport(LocationInfo))
470     return 1;
471 
472   return 0;
473 }
474