OptReport.cpp 16 KB

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