blob: 0c3acb5e5f40764d3cfee339d235854713aae957 [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"
18#include "llvm/Support/Error.h"
19#include "llvm/Support/ErrorOr.h"
20#include "llvm/Support/FileSystem.h"
21#include "llvm/Support/Format.h"
22#include "llvm/Support/LineIterator.h"
23#include "llvm/Support/FileSystem.h"
24#include "llvm/Support/MemoryBuffer.h"
25#include "llvm/Support/Path.h"
26#include "llvm/Support/Program.h"
27#include "llvm/Support/raw_ostream.h"
28#include "llvm/Support/Signals.h"
29#include "llvm/Support/YAMLTraits.h"
30
31using namespace llvm;
32using namespace llvm::yaml;
33
34static cl::opt<bool> Help("h", cl::desc("Alias for -help"), cl::Hidden);
35
36// Mark all our options with this category, everything else (except for -version
37// and -help) will be hidden.
38static cl::OptionCategory
39 OptReportCategory("llvm-opt-report options");
40
41static cl::opt<std::string>
42 InputFileName(cl::Positional, cl::desc("<input>"), cl::init("-"),
43 cl::cat(OptReportCategory));
44
45static cl::opt<std::string>
46 OutputFileName("o", cl::desc("Output file"), cl::init("-"),
47 cl::cat(OptReportCategory));
48
49static cl::opt<std::string>
50 InputRelDir("r", cl::desc("Root for relative input paths"), cl::init(""),
51 cl::cat(OptReportCategory));
52
53static cl::opt<bool>
54 Succinct("s", cl::desc("Don't include vectorization factors, etc."),
55 cl::init(false), cl::cat(OptReportCategory));
56
57namespace {
58// For each location in the source file, the common per-transformation state
59// collected.
60struct OptReportLocationItemInfo {
61 bool Analyzed = false;
62 bool Transformed = false;
63
64 OptReportLocationItemInfo &operator |= (
65 const OptReportLocationItemInfo &RHS) {
66 Analyzed |= RHS.Analyzed;
67 Transformed |= RHS.Transformed;
68
69 return *this;
70 }
71};
72
73// The per-location information collected for producing an optimization report.
74struct OptReportLocationInfo {
75 OptReportLocationItemInfo Inlined;
76 OptReportLocationItemInfo Unrolled;
77 OptReportLocationItemInfo Vectorized;
78
79 int VectorizationFactor = 1;
80 int InterleaveCount = 1;
81 int UnrollCount = 1;
82
83 OptReportLocationInfo &operator |= (const OptReportLocationInfo &RHS) {
84 Inlined |= RHS.Inlined;
85 Unrolled |= RHS.Unrolled;
86 Vectorized |= RHS.Vectorized;
87
88 VectorizationFactor =
89 std::max(VectorizationFactor, RHS.VectorizationFactor);
90 InterleaveCount = std::max(InterleaveCount, RHS.InterleaveCount);
91 UnrollCount = std::max(UnrollCount, RHS.UnrollCount);
92
93 return *this;
94 }
95};
96
97typedef std::map<std::string, std::map<int, std::map<int,
98 OptReportLocationInfo>>> LocationInfoTy;
99} // anonymous namespace
100
101static void collectLocationInfo(yaml::Stream &Stream,
102 LocationInfoTy &LocationInfo) {
103 SmallVector<char, 8> Tmp;
104
105 // Note: We're using the YAML parser here directly, instead of using the
106 // YAMLTraits implementation, because the YAMLTraits implementation does not
107 // support a way to handle only a subset of the input keys (it will error out
108 // if there is an input key that you don't map to your class), and
109 // furthermore, it does not provide a way to handle the Args sequence of
110 // key/value pairs, where the order must be captured and the 'String' key
111 // might be repeated.
112 for (auto &Doc : Stream) {
113 auto *Root = dyn_cast<yaml::MappingNode>(Doc.getRoot());
114 if (!Root)
115 continue;
116
117 bool Transformed = Root->getRawTag() == "!Passed";
118 std::string Pass, File;
119 int Line = 0, Column = 1;
120
121 int VectorizationFactor = 1;
122 int InterleaveCount = 1;
123 int UnrollCount = 1;
124
125 for (auto &RootChild : *Root) {
126 auto *Key = dyn_cast<yaml::ScalarNode>(RootChild.getKey());
127 if (!Key)
128 continue;
129 StringRef KeyName = Key->getValue(Tmp);
130 if (KeyName == "Pass") {
131 auto *Value = dyn_cast<yaml::ScalarNode>(RootChild.getValue());
132 if (!Value)
133 continue;
134 Pass = Value->getValue(Tmp);
135 } else if (KeyName == "DebugLoc") {
136 auto *DebugLoc = dyn_cast<yaml::MappingNode>(RootChild.getValue());
137 if (!DebugLoc)
138 continue;
139
140 for (auto &DLChild : *DebugLoc) {
141 auto *DLKey = dyn_cast<yaml::ScalarNode>(DLChild.getKey());
142 if (!DLKey)
143 continue;
144 StringRef DLKeyName = DLKey->getValue(Tmp);
145 if (DLKeyName == "File") {
146 auto *Value = dyn_cast<yaml::ScalarNode>(DLChild.getValue());
147 if (!Value)
148 continue;
149 File = Value->getValue(Tmp);
150 } else if (DLKeyName == "Line") {
151 auto *Value = dyn_cast<yaml::ScalarNode>(DLChild.getValue());
152 if (!Value)
153 continue;
154 Value->getValue(Tmp).getAsInteger(10, Line);
155 } else if (DLKeyName == "Column") {
156 auto *Value = dyn_cast<yaml::ScalarNode>(DLChild.getValue());
157 if (!Value)
158 continue;
159 Value->getValue(Tmp).getAsInteger(10, Column);
160 }
161 }
162 } else if (KeyName == "Args") {
163 auto *Args = dyn_cast<yaml::SequenceNode>(RootChild.getValue());
164 if (!Args)
165 continue;
166 for (auto &ArgChild : *Args) {
167 auto *ArgMap = dyn_cast<yaml::MappingNode>(&ArgChild);
168 if (!ArgMap)
169 continue;
170 for (auto &ArgKV : *ArgMap) {
171 auto *ArgKey = dyn_cast<yaml::ScalarNode>(ArgKV.getKey());
172 if (!ArgKey)
173 continue;
174 StringRef ArgKeyName = ArgKey->getValue(Tmp);
175 if (ArgKeyName == "VectorizationFactor") {
176 auto *Value = dyn_cast<yaml::ScalarNode>(ArgKV.getValue());
177 if (!Value)
178 continue;
179 Value->getValue(Tmp).getAsInteger(10, VectorizationFactor);
180 } else if (ArgKeyName == "InterleaveCount") {
181 auto *Value = dyn_cast<yaml::ScalarNode>(ArgKV.getValue());
182 if (!Value)
183 continue;
184 Value->getValue(Tmp).getAsInteger(10, InterleaveCount);
185 } else if (ArgKeyName == "UnrollCount") {
186 auto *Value = dyn_cast<yaml::ScalarNode>(ArgKV.getValue());
187 if (!Value)
188 continue;
189 Value->getValue(Tmp).getAsInteger(10, UnrollCount);
190 }
191 }
192 }
193 }
194 }
195
196 if (Line < 1 || File.empty())
197 continue;
198
199 // We track information on both actual and potential transformations. This
200 // way, if there are multiple possible things on a line that are, or could
201 // have been transformed, we can indicate that explicitly in the output.
202 auto UpdateLLII = [Transformed, VectorizationFactor,
203 InterleaveCount,
204 UnrollCount](OptReportLocationInfo &LI,
205 OptReportLocationItemInfo &LLII) {
206 LLII.Analyzed = true;
207 if (Transformed) {
208 LLII.Transformed = true;
209
210 LI.VectorizationFactor = VectorizationFactor;
211 LI.InterleaveCount = InterleaveCount;
212 LI.UnrollCount = UnrollCount;
213 }
214 };
215
216 if (Pass == "inline") {
217 auto &LI = LocationInfo[File][Line][Column];
218 UpdateLLII(LI, LI.Inlined);
219 } else if (Pass == "loop-unroll") {
220 auto &LI = LocationInfo[File][Line][Column];
221 UpdateLLII(LI, LI.Unrolled);
222 } else if (Pass == "loop-vectorize") {
223 auto &LI = LocationInfo[File][Line][Column];
224 UpdateLLII(LI, LI.Vectorized);
225 }
226 }
227}
228
229static bool readLocationInfo(LocationInfoTy &LocationInfo) {
230 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf =
231 MemoryBuffer::getFileOrSTDIN(InputFileName);
232 if (std::error_code EC = Buf.getError()) {
233 errs() << "error: Can't open file " << InputFileName << ": " <<
234 EC.message() << "\n";
235 return false;
236 }
237
238 SourceMgr SM;
239 yaml::Stream Stream(Buf.get()->getBuffer(), SM);
240 collectLocationInfo(Stream, LocationInfo);
241
242 return true;
243}
244
245static bool writeReport(LocationInfoTy &LocationInfo) {
246 std::error_code EC;
247 llvm::raw_fd_ostream OS(OutputFileName, EC,
248 llvm::sys::fs::F_Text);
249 if (EC) {
250 errs() << "error: Can't open file " << OutputFileName << ": " <<
251 EC.message() << "\n";
252 return false;
253 }
254
255 bool FirstFile = true;
256 for (auto &FI : LocationInfo) {
257 SmallString<128> FileName(FI.first);
258 if (!InputRelDir.empty()) {
259 if (std::error_code EC = sys::fs::make_absolute(InputRelDir, FileName)) {
260 errs() << "error: Can't resolve file path to " << FileName << ": " <<
261 EC.message() << "\n";
262 return false;
263 }
264 }
265
266 const auto &FileInfo = FI.second;
267
268 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf =
269 MemoryBuffer::getFile(FileName);
270 if (std::error_code EC = Buf.getError()) {
271 errs() << "error: Can't open file " << FileName << ": " <<
272 EC.message() << "\n";
273 return false;
274 }
275
276 if (FirstFile)
277 FirstFile = false;
278 else
279 OS << "\n";
280
281 OS << "< " << FileName << "\n";
282
283 // Figure out how many characters we need for the vectorization factors
284 // and similar.
285 OptReportLocationInfo MaxLI;
286 for (auto &FI : FileInfo)
287 for (auto &LI : FI.second)
288 MaxLI |= LI.second;
289
290 unsigned VFDigits = llvm::utostr(MaxLI.VectorizationFactor).size();
291 unsigned ICDigits = llvm::utostr(MaxLI.InterleaveCount).size();
292 unsigned UCDigits = llvm::utostr(MaxLI.UnrollCount).size();
293
294 // Figure out how many characters we need for the line numbers.
295 int64_t NumLines = 0;
296 for (line_iterator LI(*Buf.get(), false); LI != line_iterator(); ++LI)
297 ++NumLines;
298
299 unsigned LNDigits = llvm::utostr(NumLines).size();
300
301 for (line_iterator LI(*Buf.get(), false); LI != line_iterator(); ++LI) {
302 int64_t L = LI.line_number();
303 OptReportLocationInfo LLI;
304
305 std::map<int, OptReportLocationInfo> ColsInfo;
306 unsigned InlinedCols = 0, UnrolledCols = 0, VectorizedCols = 0;
307
308 auto LII = FileInfo.find(L);
309 if (LII != FileInfo.end()) {
310 const auto &LineInfo = LII->second;
311
312 for (auto &CI : LineInfo) {
313 int Col = CI.first;
314 ColsInfo[Col] = CI.second;
315 InlinedCols += CI.second.Inlined.Analyzed;
316 UnrolledCols += CI.second.Unrolled.Analyzed;
317 VectorizedCols += CI.second.Vectorized.Analyzed;
318 LLI |= CI.second;
319 }
320 }
321
322 // We try to keep the output as concise as possible. If only one thing on
323 // a given line could have been inlined, vectorized, etc. then we can put
324 // the marker on the source line itself. If there are multiple options
325 // then we want to distinguish them by placing the marker for each
326 // transformation on a separate line following the source line. When we
327 // do this, we use a '^' character to point to the appropriate column in
328 // the source line.
329
330 std::string USpaces(Succinct ? 0 : UCDigits, ' ');
331 std::string VSpaces(Succinct ? 0 : VFDigits + ICDigits + 1, ' ');
332
333 auto UStr = [UCDigits](OptReportLocationInfo &LLI) {
334 std::string R;
335 raw_string_ostream RS(R);
336 if (!Succinct)
337 RS << llvm::format_decimal(LLI.UnrollCount, UCDigits);
338 return RS.str();
339 };
340
341 auto VStr = [VFDigits,
342 ICDigits](OptReportLocationInfo &LLI) -> std::string {
343 std::string R;
344 raw_string_ostream RS(R);
345 if (!Succinct)
346 RS << llvm::format_decimal(LLI.VectorizationFactor, VFDigits) <<
347 "," << llvm::format_decimal(LLI.InterleaveCount, ICDigits);
348 return RS.str();
349 };
350
351 OS << llvm::format_decimal(L + 1, LNDigits) << " ";
352 OS << (LLI.Inlined.Transformed && InlinedCols < 2 ? "I" : " ");
353 OS << (LLI.Unrolled.Transformed && UnrolledCols < 2 ?
354 "U" + UStr(LLI) : " " + USpaces);
355 OS << (LLI.Vectorized.Transformed && VectorizedCols < 2 ?
356 "V" + VStr(LLI) : " " + VSpaces);
357
358 OS << " | " << *LI << "\n";
359
360 for (auto &J : ColsInfo) {
361 if ((J.second.Inlined.Transformed && InlinedCols > 1) ||
362 (J.second.Unrolled.Transformed && UnrolledCols > 1) ||
363 (J.second.Vectorized.Transformed && VectorizedCols > 1)) {
364 OS << std::string(LNDigits + 1, ' ');
365 OS << (J.second.Inlined.Transformed &&
366 InlinedCols > 1 ? "I" : " ");
367 OS << (J.second.Unrolled.Transformed &&
368 UnrolledCols > 1 ? "U" + UStr(J.second) : " " + USpaces);
369 OS << (J.second.Vectorized.Transformed &&
370 VectorizedCols > 1 ? "V" + VStr(J.second) : " " + VSpaces);
371
372 OS << " | " << std::string(J.first - 1, ' ') << "^\n";
373 }
374 }
375 }
376 }
377
378 return true;
379}
380
381int main(int argc, const char **argv) {
382 sys::PrintStackTraceOnErrorSignal(argv[0]);
383
384 cl::HideUnrelatedOptions(OptReportCategory);
385 cl::ParseCommandLineOptions(
386 argc, argv,
387 "A tool to generate an optimization report from YAML optimization"
388 " record files.\n");
389
390 if (Help)
391 cl::PrintHelpMessage();
392
393 LocationInfoTy LocationInfo;
394 if (!readLocationInfo(LocationInfo))
395 return 1;
396 if (!writeReport(LocationInfo))
397 return 1;
398
399 return 0;
400}
401