OptReport.cpp 16 KB

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