blob: 451f1dbfee9787bd57021d1019cd740a23858aeb [file] [log] [blame]
Hal Finkel52031b72016-10-05 22:10:35 +00001//===------------------ llvm-opt-report/OptReport.cpp ---------------------===//
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/// \file
11/// \brief This file implements a tool that can parse the YAML optimization
12/// records and generate an optimization summary annotated source listing
13/// report.
14///
15//===----------------------------------------------------------------------===//
16
17#include "llvm/Support/CommandLine.h"
Hal Finkel5aa02482016-10-05 22:25:33 +000018#include "llvm/Demangle/Demangle.h"
Hal Finkel52031b72016-10-05 22:10:35 +000019#include "llvm/Support/Error.h"
20#include "llvm/Support/ErrorOr.h"
21#include "llvm/Support/FileSystem.h"
22#include "llvm/Support/Format.h"
23#include "llvm/Support/LineIterator.h"
24#include "llvm/Support/FileSystem.h"
25#include "llvm/Support/MemoryBuffer.h"
26#include "llvm/Support/Path.h"
27#include "llvm/Support/Program.h"
28#include "llvm/Support/raw_ostream.h"
29#include "llvm/Support/Signals.h"
30#include "llvm/Support/YAMLTraits.h"
Hal Finkel5aa02482016-10-05 22:25:33 +000031#include <cstdlib>
32#include <map>
33#include <set>
Hal Finkel52031b72016-10-05 22:10:35 +000034
35using namespace llvm;
36using namespace llvm::yaml;
37
38static cl::opt<bool> Help("h", cl::desc("Alias for -help"), cl::Hidden);
39
40// Mark all our options with this category, everything else (except for -version
41// and -help) will be hidden.
42static cl::OptionCategory
43 OptReportCategory("llvm-opt-report options");
44
45static cl::opt<std::string>
46 InputFileName(cl::Positional, cl::desc("<input>"), cl::init("-"),
47 cl::cat(OptReportCategory));
48
49static cl::opt<std::string>
50 OutputFileName("o", cl::desc("Output file"), cl::init("-"),
51 cl::cat(OptReportCategory));
52
53static cl::opt<std::string>
54 InputRelDir("r", cl::desc("Root for relative input paths"), cl::init(""),
55 cl::cat(OptReportCategory));
56
57static cl::opt<bool>
58 Succinct("s", cl::desc("Don't include vectorization factors, etc."),
59 cl::init(false), cl::cat(OptReportCategory));
60
Hal Finkel5aa02482016-10-05 22:25:33 +000061static cl::opt<bool>
62 Demangle("demangle", cl::desc("Demangle function names"), cl::init(true),
63 cl::cat(OptReportCategory));
64
Hal Finkel52031b72016-10-05 22:10:35 +000065namespace {
66// For each location in the source file, the common per-transformation state
67// collected.
68struct OptReportLocationItemInfo {
69 bool Analyzed = false;
70 bool Transformed = false;
71
72 OptReportLocationItemInfo &operator |= (
73 const OptReportLocationItemInfo &RHS) {
74 Analyzed |= RHS.Analyzed;
75 Transformed |= RHS.Transformed;
76
77 return *this;
78 }
Hal Finkel5aa02482016-10-05 22:25:33 +000079
80 bool operator < (const OptReportLocationItemInfo &RHS) const {
81 if (Analyzed < RHS.Analyzed)
82 return true;
83 else if (Analyzed > RHS.Analyzed)
84 return false;
85 else if (Transformed < RHS.Transformed)
86 return true;
87 return false;
88 }
Hal Finkel52031b72016-10-05 22:10:35 +000089};
90
91// The per-location information collected for producing an optimization report.
92struct OptReportLocationInfo {
93 OptReportLocationItemInfo Inlined;
94 OptReportLocationItemInfo Unrolled;
95 OptReportLocationItemInfo Vectorized;
96
97 int VectorizationFactor = 1;
98 int InterleaveCount = 1;
99 int UnrollCount = 1;
100
101 OptReportLocationInfo &operator |= (const OptReportLocationInfo &RHS) {
102 Inlined |= RHS.Inlined;
103 Unrolled |= RHS.Unrolled;
104 Vectorized |= RHS.Vectorized;
105
106 VectorizationFactor =
107 std::max(VectorizationFactor, RHS.VectorizationFactor);
108 InterleaveCount = std::max(InterleaveCount, RHS.InterleaveCount);
109 UnrollCount = std::max(UnrollCount, RHS.UnrollCount);
110
111 return *this;
112 }
Hal Finkel5aa02482016-10-05 22:25:33 +0000113
114 bool operator < (const OptReportLocationInfo &RHS) const {
115 if (Inlined < RHS.Inlined)
116 return true;
117 else if (RHS.Inlined < Inlined)
118 return false;
119 else if (Unrolled < RHS.Unrolled)
120 return true;
121 else if (RHS.Unrolled < Unrolled)
122 return false;
123 else if (Vectorized < RHS.Vectorized)
124 return true;
125 else if (RHS.Vectorized < Vectorized || Succinct)
126 return false;
127 else if (VectorizationFactor < RHS.VectorizationFactor)
128 return true;
129 else if (VectorizationFactor > RHS.VectorizationFactor)
130 return false;
131 else if (InterleaveCount < RHS.InterleaveCount)
132 return true;
133 else if (InterleaveCount > RHS.InterleaveCount)
134 return false;
135 else if (InterleaveCount < RHS.InterleaveCount)
136 return true;
137 return false;
138 }
Hal Finkel52031b72016-10-05 22:10:35 +0000139};
140
Hal Finkel5aa02482016-10-05 22:25:33 +0000141typedef std::map<std::string, std::map<int, std::map<std::string, std::map<int,
142 OptReportLocationInfo>>>> LocationInfoTy;
Hal Finkel52031b72016-10-05 22:10:35 +0000143} // anonymous namespace
144
145static void collectLocationInfo(yaml::Stream &Stream,
146 LocationInfoTy &LocationInfo) {
147 SmallVector<char, 8> Tmp;
148
149 // Note: We're using the YAML parser here directly, instead of using the
150 // YAMLTraits implementation, because the YAMLTraits implementation does not
151 // support a way to handle only a subset of the input keys (it will error out
152 // if there is an input key that you don't map to your class), and
153 // furthermore, it does not provide a way to handle the Args sequence of
154 // key/value pairs, where the order must be captured and the 'String' key
155 // might be repeated.
156 for (auto &Doc : Stream) {
157 auto *Root = dyn_cast<yaml::MappingNode>(Doc.getRoot());
158 if (!Root)
159 continue;
160
161 bool Transformed = Root->getRawTag() == "!Passed";
Hal Finkel5aa02482016-10-05 22:25:33 +0000162 std::string Pass, File, Function;
Hal Finkel52031b72016-10-05 22:10:35 +0000163 int Line = 0, Column = 1;
164
165 int VectorizationFactor = 1;
166 int InterleaveCount = 1;
167 int UnrollCount = 1;
168
169 for (auto &RootChild : *Root) {
170 auto *Key = dyn_cast<yaml::ScalarNode>(RootChild.getKey());
171 if (!Key)
172 continue;
173 StringRef KeyName = Key->getValue(Tmp);
174 if (KeyName == "Pass") {
175 auto *Value = dyn_cast<yaml::ScalarNode>(RootChild.getValue());
176 if (!Value)
177 continue;
178 Pass = Value->getValue(Tmp);
Hal Finkel5aa02482016-10-05 22:25:33 +0000179 } else if (KeyName == "Function") {
180 auto *Value = dyn_cast<yaml::ScalarNode>(RootChild.getValue());
181 if (!Value)
182 continue;
183 Function = Value->getValue(Tmp);
Hal Finkel52031b72016-10-05 22:10:35 +0000184 } else if (KeyName == "DebugLoc") {
185 auto *DebugLoc = dyn_cast<yaml::MappingNode>(RootChild.getValue());
186 if (!DebugLoc)
187 continue;
188
189 for (auto &DLChild : *DebugLoc) {
190 auto *DLKey = dyn_cast<yaml::ScalarNode>(DLChild.getKey());
191 if (!DLKey)
192 continue;
193 StringRef DLKeyName = DLKey->getValue(Tmp);
194 if (DLKeyName == "File") {
195 auto *Value = dyn_cast<yaml::ScalarNode>(DLChild.getValue());
196 if (!Value)
197 continue;
198 File = Value->getValue(Tmp);
199 } else if (DLKeyName == "Line") {
200 auto *Value = dyn_cast<yaml::ScalarNode>(DLChild.getValue());
201 if (!Value)
202 continue;
203 Value->getValue(Tmp).getAsInteger(10, Line);
204 } else if (DLKeyName == "Column") {
205 auto *Value = dyn_cast<yaml::ScalarNode>(DLChild.getValue());
206 if (!Value)
207 continue;
208 Value->getValue(Tmp).getAsInteger(10, Column);
209 }
210 }
211 } else if (KeyName == "Args") {
212 auto *Args = dyn_cast<yaml::SequenceNode>(RootChild.getValue());
213 if (!Args)
214 continue;
215 for (auto &ArgChild : *Args) {
216 auto *ArgMap = dyn_cast<yaml::MappingNode>(&ArgChild);
217 if (!ArgMap)
218 continue;
219 for (auto &ArgKV : *ArgMap) {
220 auto *ArgKey = dyn_cast<yaml::ScalarNode>(ArgKV.getKey());
221 if (!ArgKey)
222 continue;
223 StringRef ArgKeyName = ArgKey->getValue(Tmp);
224 if (ArgKeyName == "VectorizationFactor") {
225 auto *Value = dyn_cast<yaml::ScalarNode>(ArgKV.getValue());
226 if (!Value)
227 continue;
228 Value->getValue(Tmp).getAsInteger(10, VectorizationFactor);
229 } else if (ArgKeyName == "InterleaveCount") {
230 auto *Value = dyn_cast<yaml::ScalarNode>(ArgKV.getValue());
231 if (!Value)
232 continue;
233 Value->getValue(Tmp).getAsInteger(10, InterleaveCount);
234 } else if (ArgKeyName == "UnrollCount") {
235 auto *Value = dyn_cast<yaml::ScalarNode>(ArgKV.getValue());
236 if (!Value)
237 continue;
238 Value->getValue(Tmp).getAsInteger(10, UnrollCount);
239 }
240 }
241 }
242 }
243 }
244
245 if (Line < 1 || File.empty())
246 continue;
247
248 // We track information on both actual and potential transformations. This
249 // way, if there are multiple possible things on a line that are, or could
250 // have been transformed, we can indicate that explicitly in the output.
251 auto UpdateLLII = [Transformed, VectorizationFactor,
252 InterleaveCount,
253 UnrollCount](OptReportLocationInfo &LI,
254 OptReportLocationItemInfo &LLII) {
255 LLII.Analyzed = true;
256 if (Transformed) {
257 LLII.Transformed = true;
258
259 LI.VectorizationFactor = VectorizationFactor;
260 LI.InterleaveCount = InterleaveCount;
261 LI.UnrollCount = UnrollCount;
262 }
263 };
264
265 if (Pass == "inline") {
Hal Finkel5aa02482016-10-05 22:25:33 +0000266 auto &LI = LocationInfo[File][Line][Function][Column];
Hal Finkel52031b72016-10-05 22:10:35 +0000267 UpdateLLII(LI, LI.Inlined);
268 } else if (Pass == "loop-unroll") {
Hal Finkel5aa02482016-10-05 22:25:33 +0000269 auto &LI = LocationInfo[File][Line][Function][Column];
Hal Finkel52031b72016-10-05 22:10:35 +0000270 UpdateLLII(LI, LI.Unrolled);
271 } else if (Pass == "loop-vectorize") {
Hal Finkel5aa02482016-10-05 22:25:33 +0000272 auto &LI = LocationInfo[File][Line][Function][Column];
Hal Finkel52031b72016-10-05 22:10:35 +0000273 UpdateLLII(LI, LI.Vectorized);
274 }
275 }
276}
277
278static bool readLocationInfo(LocationInfoTy &LocationInfo) {
279 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf =
280 MemoryBuffer::getFileOrSTDIN(InputFileName);
281 if (std::error_code EC = Buf.getError()) {
282 errs() << "error: Can't open file " << InputFileName << ": " <<
283 EC.message() << "\n";
284 return false;
285 }
286
287 SourceMgr SM;
288 yaml::Stream Stream(Buf.get()->getBuffer(), SM);
289 collectLocationInfo(Stream, LocationInfo);
290
291 return true;
292}
293
294static bool writeReport(LocationInfoTy &LocationInfo) {
295 std::error_code EC;
296 llvm::raw_fd_ostream OS(OutputFileName, EC,
297 llvm::sys::fs::F_Text);
298 if (EC) {
299 errs() << "error: Can't open file " << OutputFileName << ": " <<
300 EC.message() << "\n";
301 return false;
302 }
303
304 bool FirstFile = true;
305 for (auto &FI : LocationInfo) {
306 SmallString<128> FileName(FI.first);
307 if (!InputRelDir.empty()) {
308 if (std::error_code EC = sys::fs::make_absolute(InputRelDir, FileName)) {
309 errs() << "error: Can't resolve file path to " << FileName << ": " <<
310 EC.message() << "\n";
311 return false;
312 }
313 }
314
315 const auto &FileInfo = FI.second;
316
317 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf =
318 MemoryBuffer::getFile(FileName);
319 if (std::error_code EC = Buf.getError()) {
320 errs() << "error: Can't open file " << FileName << ": " <<
321 EC.message() << "\n";
322 return false;
323 }
324
325 if (FirstFile)
326 FirstFile = false;
327 else
328 OS << "\n";
329
330 OS << "< " << FileName << "\n";
331
332 // Figure out how many characters we need for the vectorization factors
333 // and similar.
334 OptReportLocationInfo MaxLI;
Hal Finkel5aa02482016-10-05 22:25:33 +0000335 for (auto &FLI : FileInfo)
336 for (auto &FI : FLI.second)
337 for (auto &LI : FI.second)
338 MaxLI |= LI.second;
Hal Finkel52031b72016-10-05 22:10:35 +0000339
340 unsigned VFDigits = llvm::utostr(MaxLI.VectorizationFactor).size();
341 unsigned ICDigits = llvm::utostr(MaxLI.InterleaveCount).size();
342 unsigned UCDigits = llvm::utostr(MaxLI.UnrollCount).size();
343
344 // Figure out how many characters we need for the line numbers.
345 int64_t NumLines = 0;
346 for (line_iterator LI(*Buf.get(), false); LI != line_iterator(); ++LI)
347 ++NumLines;
348
349 unsigned LNDigits = llvm::utostr(NumLines).size();
350
351 for (line_iterator LI(*Buf.get(), false); LI != line_iterator(); ++LI) {
352 int64_t L = LI.line_number();
Hal Finkel52031b72016-10-05 22:10:35 +0000353 auto LII = FileInfo.find(L);
Hal Finkel52031b72016-10-05 22:10:35 +0000354
Hal Finkel5aa02482016-10-05 22:25:33 +0000355 auto PrintLine = [&](bool PrintFuncName,
356 const std::set<std::string> &FuncNameSet) {
357 OptReportLocationInfo LLI;
358
359 std::map<int, OptReportLocationInfo> ColsInfo;
360 unsigned InlinedCols = 0, UnrolledCols = 0, VectorizedCols = 0;
361
362 if (LII != FileInfo.end()) {
363 const auto &LineInfo = LII->second;
364
365 for (auto &CI : LineInfo.find(*FuncNameSet.begin())->second) {
366 int Col = CI.first;
367 ColsInfo[Col] = CI.second;
368 InlinedCols += CI.second.Inlined.Analyzed;
369 UnrolledCols += CI.second.Unrolled.Analyzed;
370 VectorizedCols += CI.second.Vectorized.Analyzed;
371 LLI |= CI.second;
372 }
Hal Finkel52031b72016-10-05 22:10:35 +0000373 }
Hal Finkel5aa02482016-10-05 22:25:33 +0000374
375 if (PrintFuncName) {
376 OS << " > ";
377
378 bool FirstFunc = true;
379 for (const auto &FuncName : FuncNameSet) {
380 if (FirstFunc)
381 FirstFunc = false;
382 else
383 OS << ", ";
384
385 bool Printed = false;
386 if (Demangle) {
387 int Status = 0;
388 char *Demangled =
389 itaniumDemangle(FuncName.c_str(), nullptr, nullptr, &Status);
390 if (Demangled && Status == 0) {
391 OS << Demangled;
392 Printed = true;
393 }
394
395 if (Demangled)
396 std::free(Demangled);
397 }
398
399 if (!Printed)
400 OS << FuncName;
401 }
402
403 OS << ":\n";
404 }
405
406 // We try to keep the output as concise as possible. If only one thing on
407 // a given line could have been inlined, vectorized, etc. then we can put
408 // the marker on the source line itself. If there are multiple options
409 // then we want to distinguish them by placing the marker for each
410 // transformation on a separate line following the source line. When we
411 // do this, we use a '^' character to point to the appropriate column in
412 // the source line.
413
414 std::string USpaces(Succinct ? 0 : UCDigits, ' ');
415 std::string VSpaces(Succinct ? 0 : VFDigits + ICDigits + 1, ' ');
416
417 auto UStr = [UCDigits](OptReportLocationInfo &LLI) {
418 std::string R;
419 raw_string_ostream RS(R);
420 if (!Succinct)
421 RS << llvm::format_decimal(LLI.UnrollCount, UCDigits);
422 return RS.str();
423 };
424
425 auto VStr = [VFDigits,
426 ICDigits](OptReportLocationInfo &LLI) -> std::string {
427 std::string R;
428 raw_string_ostream RS(R);
429 if (!Succinct)
430 RS << llvm::format_decimal(LLI.VectorizationFactor, VFDigits) <<
431 "," << llvm::format_decimal(LLI.InterleaveCount, ICDigits);
432 return RS.str();
433 };
434
435 OS << llvm::format_decimal(L + 1, LNDigits) << " ";
436 OS << (LLI.Inlined.Transformed && InlinedCols < 2 ? "I" : " ");
437 OS << (LLI.Unrolled.Transformed && UnrolledCols < 2 ?
438 "U" + UStr(LLI) : " " + USpaces);
439 OS << (LLI.Vectorized.Transformed && VectorizedCols < 2 ?
440 "V" + VStr(LLI) : " " + VSpaces);
441
442 OS << " | " << *LI << "\n";
443
444 for (auto &J : ColsInfo) {
445 if ((J.second.Inlined.Transformed && InlinedCols > 1) ||
446 (J.second.Unrolled.Transformed && UnrolledCols > 1) ||
447 (J.second.Vectorized.Transformed && VectorizedCols > 1)) {
448 OS << std::string(LNDigits + 1, ' ');
449 OS << (J.second.Inlined.Transformed &&
450 InlinedCols > 1 ? "I" : " ");
451 OS << (J.second.Unrolled.Transformed &&
452 UnrolledCols > 1 ? "U" + UStr(J.second) : " " + USpaces);
453 OS << (J.second.Vectorized.Transformed &&
454 VectorizedCols > 1 ? "V" + VStr(J.second) : " " + VSpaces);
455
456 OS << " | " << std::string(J.first - 1, ' ') << "^\n";
457 }
458 }
459 };
460
461 // We need to figure out if the optimizations for this line were the same
462 // in each function context. If not, then we want to group the similar
463 // function contexts together and display each group separately. If
464 // they're all the same, then we only display the line once without any
465 // additional markings.
466 std::map<std::map<int, OptReportLocationInfo>,
467 std::set<std::string>> UniqueLIs;
468
469 if (LII != FileInfo.end()) {
470 const auto &FuncLineInfo = LII->second;
471 for (const auto &FLII : FuncLineInfo)
472 UniqueLIs[FLII.second].insert(FLII.first);
Hal Finkel52031b72016-10-05 22:10:35 +0000473 }
474
Hal Finkel5aa02482016-10-05 22:25:33 +0000475 if (UniqueLIs.size() > 1) {
476 OS << " [[\n";
477 for (const auto &FSLI : UniqueLIs)
478 PrintLine(true, FSLI.second);
479 OS << " ]]\n";
480 } else if (UniqueLIs.size() == 1) {
481 PrintLine(false, UniqueLIs.begin()->second);
482 } else {
483 PrintLine(false, std::set<std::string>());
Hal Finkel52031b72016-10-05 22:10:35 +0000484 }
485 }
486 }
487
488 return true;
489}
490
491int main(int argc, const char **argv) {
492 sys::PrintStackTraceOnErrorSignal(argv[0]);
493
494 cl::HideUnrelatedOptions(OptReportCategory);
495 cl::ParseCommandLineOptions(
496 argc, argv,
497 "A tool to generate an optimization report from YAML optimization"
498 " record files.\n");
499
500 if (Help)
501 cl::PrintHelpMessage();
502
503 LocationInfoTy LocationInfo;
504 if (!readLocationInfo(LocationInfo))
505 return 1;
506 if (!writeReport(LocationInfo))
507 return 1;
508
509 return 0;
510}
511