StandardInstrumentations.cpp 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147
  1. //===- Standard pass instrumentations handling ----------------*- C++ -*--===//
  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. /// \file
  9. ///
  10. /// This file defines IR-printing pass instrumentation callbacks as well as
  11. /// StandardInstrumentations class that manages standard pass instrumentations.
  12. ///
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/Passes/StandardInstrumentations.h"
  15. #include "llvm/ADT/Any.h"
  16. #include "llvm/ADT/Optional.h"
  17. #include "llvm/ADT/StringRef.h"
  18. #include "llvm/Analysis/CallGraphSCCPass.h"
  19. #include "llvm/Analysis/LazyCallGraph.h"
  20. #include "llvm/Analysis/LoopInfo.h"
  21. #include "llvm/IR/Function.h"
  22. #include "llvm/IR/LegacyPassManager.h"
  23. #include "llvm/IR/Module.h"
  24. #include "llvm/IR/PassInstrumentation.h"
  25. #include "llvm/IR/PassManager.h"
  26. #include "llvm/IR/PrintPasses.h"
  27. #include "llvm/IR/Verifier.h"
  28. #include "llvm/Support/CommandLine.h"
  29. #include "llvm/Support/Debug.h"
  30. #include "llvm/Support/FormatVariadic.h"
  31. #include "llvm/Support/GraphWriter.h"
  32. #include "llvm/Support/MemoryBuffer.h"
  33. #include "llvm/Support/Program.h"
  34. #include "llvm/Support/Regex.h"
  35. #include "llvm/Support/raw_ostream.h"
  36. #include <unordered_map>
  37. #include <unordered_set>
  38. #include <utility>
  39. #include <vector>
  40. using namespace llvm;
  41. cl::opt<bool> PreservedCFGCheckerInstrumentation::VerifyPreservedCFG(
  42. "verify-cfg-preserved", cl::Hidden,
  43. #ifdef NDEBUG
  44. cl::init(false)
  45. #else
  46. cl::init(true)
  47. #endif
  48. );
  49. // An option that prints out the IR after passes, similar to
  50. // -print-after-all except that it only prints the IR after passes that
  51. // change the IR. Those passes that do not make changes to the IR are
  52. // reported as not making any changes. In addition, the initial IR is
  53. // also reported. Other hidden options affect the output from this
  54. // option. -filter-passes will limit the output to the named passes
  55. // that actually change the IR and other passes are reported as filtered out.
  56. // The specified passes will either be reported as making no changes (with
  57. // no IR reported) or the changed IR will be reported. Also, the
  58. // -filter-print-funcs and -print-module-scope options will do similar
  59. // filtering based on function name, reporting changed IRs as functions(or
  60. // modules if -print-module-scope is specified) for a particular function
  61. // or indicating that the IR has been filtered out. The extra options
  62. // can be combined, allowing only changed IRs for certain passes on certain
  63. // functions to be reported in different formats, with the rest being
  64. // reported as filtered out. The -print-before-changed option will print
  65. // the IR as it was before each pass that changed it. The optional
  66. // value of quiet will only report when the IR changes, suppressing
  67. // all other messages, including the initial IR. The values "diff" and
  68. // "diff-quiet" will present the changes in a form similar to a patch, in
  69. // either verbose or quiet mode, respectively. The lines that are removed
  70. // and added are prefixed with '-' and '+', respectively. The
  71. // -filter-print-funcs and -filter-passes can be used to filter the output.
  72. // This reporter relies on the linux diff utility to do comparisons and
  73. // insert the prefixes. For systems that do not have the necessary
  74. // facilities, the error message will be shown in place of the expected output.
  75. //
  76. enum class ChangePrinter {
  77. NoChangePrinter,
  78. PrintChangedVerbose,
  79. PrintChangedQuiet,
  80. PrintChangedDiffVerbose,
  81. PrintChangedDiffQuiet,
  82. PrintChangedColourDiffVerbose,
  83. PrintChangedColourDiffQuiet,
  84. PrintChangedDotCfgVerbose,
  85. PrintChangedDotCfgQuiet
  86. };
  87. static cl::opt<ChangePrinter> PrintChanged(
  88. "print-changed", cl::desc("Print changed IRs"), cl::Hidden,
  89. cl::ValueOptional, cl::init(ChangePrinter::NoChangePrinter),
  90. cl::values(
  91. clEnumValN(ChangePrinter::PrintChangedQuiet, "quiet",
  92. "Run in quiet mode"),
  93. clEnumValN(ChangePrinter::PrintChangedDiffVerbose, "diff",
  94. "Display patch-like changes"),
  95. clEnumValN(ChangePrinter::PrintChangedDiffQuiet, "diff-quiet",
  96. "Display patch-like changes in quiet mode"),
  97. clEnumValN(ChangePrinter::PrintChangedColourDiffVerbose, "cdiff",
  98. "Display patch-like changes with color"),
  99. clEnumValN(ChangePrinter::PrintChangedColourDiffQuiet, "cdiff-quiet",
  100. "Display patch-like changes in quiet mode with color"),
  101. clEnumValN(ChangePrinter::PrintChangedDotCfgVerbose, "dot-cfg",
  102. "Create a website with graphical changes"),
  103. clEnumValN(ChangePrinter::PrintChangedDotCfgQuiet, "dot-cfg-quiet",
  104. "Create a website with graphical changes in quiet mode"),
  105. // Sentinel value for unspecified option.
  106. clEnumValN(ChangePrinter::PrintChangedVerbose, "", "")));
  107. // An option that supports the -print-changed option. See
  108. // the description for -print-changed for an explanation of the use
  109. // of this option. Note that this option has no effect without -print-changed.
  110. static cl::list<std::string>
  111. PrintPassesList("filter-passes", cl::value_desc("pass names"),
  112. cl::desc("Only consider IR changes for passes whose names "
  113. "match for the print-changed option"),
  114. cl::CommaSeparated, cl::Hidden);
  115. // An option that supports the -print-changed option. See
  116. // the description for -print-changed for an explanation of the use
  117. // of this option. Note that this option has no effect without -print-changed.
  118. static cl::opt<bool>
  119. PrintChangedBefore("print-before-changed",
  120. cl::desc("Print before passes that change them"),
  121. cl::init(false), cl::Hidden);
  122. // An option for specifying the diff used by print-changed=[diff | diff-quiet]
  123. static cl::opt<std::string>
  124. DiffBinary("print-changed-diff-path", cl::Hidden, cl::init("diff"),
  125. cl::desc("system diff used by change reporters"));
  126. // An option for specifying the dot used by
  127. // print-changed=[dot-cfg | dot-cfg-quiet]
  128. static cl::opt<std::string>
  129. DotBinary("print-changed-dot-path", cl::Hidden, cl::init("dot"),
  130. cl::desc("system dot used by change reporters"));
  131. // An option that determines the colour used for elements that are only
  132. // in the before part. Must be a colour named in appendix J of
  133. // https://graphviz.org/pdf/dotguide.pdf
  134. cl::opt<std::string>
  135. BeforeColour("dot-cfg-before-color",
  136. cl::desc("Color for dot-cfg before elements."), cl::Hidden,
  137. cl::init("red"));
  138. // An option that determines the colour used for elements that are only
  139. // in the after part. Must be a colour named in appendix J of
  140. // https://graphviz.org/pdf/dotguide.pdf
  141. cl::opt<std::string> AfterColour("dot-cfg-after-color",
  142. cl::desc("Color for dot-cfg after elements."),
  143. cl::Hidden, cl::init("forestgreen"));
  144. // An option that determines the colour used for elements that are in both
  145. // the before and after parts. Must be a colour named in appendix J of
  146. // https://graphviz.org/pdf/dotguide.pdf
  147. cl::opt<std::string>
  148. CommonColour("dot-cfg-common-color",
  149. cl::desc("Color for dot-cfg common elements."), cl::Hidden,
  150. cl::init("black"));
  151. // An option that determines where the generated website file (named
  152. // passes.html) and the associated pdf files (named diff_*.pdf) are saved.
  153. static cl::opt<std::string> DotCfgDir(
  154. "dot-cfg-dir",
  155. cl::desc("Generate dot files into specified directory for changed IRs"),
  156. cl::Hidden, cl::init("./"));
  157. namespace {
  158. // Perform a system based diff between \p Before and \p After, using
  159. // \p OldLineFormat, \p NewLineFormat, and \p UnchangedLineFormat
  160. // to control the formatting of the output. Return an error message
  161. // for any failures instead of the diff.
  162. std::string doSystemDiff(StringRef Before, StringRef After,
  163. StringRef OldLineFormat, StringRef NewLineFormat,
  164. StringRef UnchangedLineFormat) {
  165. StringRef SR[2]{Before, After};
  166. // Store the 2 bodies into temporary files and call diff on them
  167. // to get the body of the node.
  168. const unsigned NumFiles = 3;
  169. static std::string FileName[NumFiles];
  170. static int FD[NumFiles]{-1, -1, -1};
  171. for (unsigned I = 0; I < NumFiles; ++I) {
  172. if (FD[I] == -1) {
  173. SmallVector<char, 200> SV;
  174. std::error_code EC =
  175. sys::fs::createTemporaryFile("tmpdiff", "txt", FD[I], SV);
  176. if (EC)
  177. return "Unable to create temporary file.";
  178. FileName[I] = Twine(SV).str();
  179. }
  180. // The third file is used as the result of the diff.
  181. if (I == NumFiles - 1)
  182. break;
  183. std::error_code EC = sys::fs::openFileForWrite(FileName[I], FD[I]);
  184. if (EC)
  185. return "Unable to open temporary file for writing.";
  186. raw_fd_ostream OutStream(FD[I], /*shouldClose=*/true);
  187. if (FD[I] == -1)
  188. return "Error opening file for writing.";
  189. OutStream << SR[I];
  190. }
  191. static ErrorOr<std::string> DiffExe = sys::findProgramByName(DiffBinary);
  192. if (!DiffExe)
  193. return "Unable to find diff executable.";
  194. SmallString<128> OLF = formatv("--old-line-format={0}", OldLineFormat);
  195. SmallString<128> NLF = formatv("--new-line-format={0}", NewLineFormat);
  196. SmallString<128> ULF =
  197. formatv("--unchanged-line-format={0}", UnchangedLineFormat);
  198. StringRef Args[] = {DiffBinary, "-w", "-d", OLF,
  199. NLF, ULF, FileName[0], FileName[1]};
  200. Optional<StringRef> Redirects[] = {None, StringRef(FileName[2]), None};
  201. int Result = sys::ExecuteAndWait(*DiffExe, Args, None, Redirects);
  202. if (Result < 0)
  203. return "Error executing system diff.";
  204. std::string Diff;
  205. auto B = MemoryBuffer::getFile(FileName[2]);
  206. if (B && *B)
  207. Diff = (*B)->getBuffer().str();
  208. else
  209. return "Unable to read result.";
  210. // Clean up.
  211. for (const std::string &I : FileName) {
  212. std::error_code EC = sys::fs::remove(I);
  213. if (EC)
  214. return "Unable to remove temporary file.";
  215. }
  216. return Diff;
  217. }
  218. /// Extract Module out of \p IR unit. May return nullptr if \p IR does not match
  219. /// certain global filters. Will never return nullptr if \p Force is true.
  220. const Module *unwrapModule(Any IR, bool Force = false) {
  221. if (any_isa<const Module *>(IR))
  222. return any_cast<const Module *>(IR);
  223. if (any_isa<const Function *>(IR)) {
  224. const Function *F = any_cast<const Function *>(IR);
  225. if (!Force && !isFunctionInPrintList(F->getName()))
  226. return nullptr;
  227. return F->getParent();
  228. }
  229. if (any_isa<const LazyCallGraph::SCC *>(IR)) {
  230. const LazyCallGraph::SCC *C = any_cast<const LazyCallGraph::SCC *>(IR);
  231. for (const LazyCallGraph::Node &N : *C) {
  232. const Function &F = N.getFunction();
  233. if (Force || (!F.isDeclaration() && isFunctionInPrintList(F.getName()))) {
  234. return F.getParent();
  235. }
  236. }
  237. assert(!Force && "Expected a module");
  238. return nullptr;
  239. }
  240. if (any_isa<const Loop *>(IR)) {
  241. const Loop *L = any_cast<const Loop *>(IR);
  242. const Function *F = L->getHeader()->getParent();
  243. if (!Force && !isFunctionInPrintList(F->getName()))
  244. return nullptr;
  245. return F->getParent();
  246. }
  247. llvm_unreachable("Unknown IR unit");
  248. }
  249. void printIR(raw_ostream &OS, const Function *F) {
  250. if (!isFunctionInPrintList(F->getName()))
  251. return;
  252. OS << *F;
  253. }
  254. void printIR(raw_ostream &OS, const Module *M) {
  255. if (isFunctionInPrintList("*") || forcePrintModuleIR()) {
  256. M->print(OS, nullptr);
  257. } else {
  258. for (const auto &F : M->functions()) {
  259. printIR(OS, &F);
  260. }
  261. }
  262. }
  263. void printIR(raw_ostream &OS, const LazyCallGraph::SCC *C) {
  264. for (const LazyCallGraph::Node &N : *C) {
  265. const Function &F = N.getFunction();
  266. if (!F.isDeclaration() && isFunctionInPrintList(F.getName())) {
  267. F.print(OS);
  268. }
  269. }
  270. }
  271. void printIR(raw_ostream &OS, const Loop *L) {
  272. const Function *F = L->getHeader()->getParent();
  273. if (!isFunctionInPrintList(F->getName()))
  274. return;
  275. printLoop(const_cast<Loop &>(*L), OS);
  276. }
  277. std::string getIRName(Any IR) {
  278. if (any_isa<const Module *>(IR))
  279. return "[module]";
  280. if (any_isa<const Function *>(IR)) {
  281. const Function *F = any_cast<const Function *>(IR);
  282. return F->getName().str();
  283. }
  284. if (any_isa<const LazyCallGraph::SCC *>(IR)) {
  285. const LazyCallGraph::SCC *C = any_cast<const LazyCallGraph::SCC *>(IR);
  286. return C->getName();
  287. }
  288. if (any_isa<const Loop *>(IR)) {
  289. const Loop *L = any_cast<const Loop *>(IR);
  290. std::string S;
  291. raw_string_ostream OS(S);
  292. L->print(OS, /*Verbose*/ false, /*PrintNested*/ false);
  293. return OS.str();
  294. }
  295. llvm_unreachable("Unknown wrapped IR type");
  296. }
  297. bool moduleContainsFilterPrintFunc(const Module &M) {
  298. return any_of(M.functions(),
  299. [](const Function &F) {
  300. return isFunctionInPrintList(F.getName());
  301. }) ||
  302. isFunctionInPrintList("*");
  303. }
  304. bool sccContainsFilterPrintFunc(const LazyCallGraph::SCC &C) {
  305. return any_of(C,
  306. [](const LazyCallGraph::Node &N) {
  307. return isFunctionInPrintList(N.getName());
  308. }) ||
  309. isFunctionInPrintList("*");
  310. }
  311. bool shouldPrintIR(Any IR) {
  312. if (any_isa<const Module *>(IR)) {
  313. const Module *M = any_cast<const Module *>(IR);
  314. return moduleContainsFilterPrintFunc(*M);
  315. }
  316. if (any_isa<const Function *>(IR)) {
  317. const Function *F = any_cast<const Function *>(IR);
  318. return isFunctionInPrintList(F->getName());
  319. }
  320. if (any_isa<const LazyCallGraph::SCC *>(IR)) {
  321. const LazyCallGraph::SCC *C = any_cast<const LazyCallGraph::SCC *>(IR);
  322. return sccContainsFilterPrintFunc(*C);
  323. }
  324. if (any_isa<const Loop *>(IR)) {
  325. const Loop *L = any_cast<const Loop *>(IR);
  326. return isFunctionInPrintList(L->getHeader()->getParent()->getName());
  327. }
  328. llvm_unreachable("Unknown wrapped IR type");
  329. }
  330. /// Generic IR-printing helper that unpacks a pointer to IRUnit wrapped into
  331. /// llvm::Any and does actual print job.
  332. void unwrapAndPrint(raw_ostream &OS, Any IR) {
  333. if (!shouldPrintIR(IR))
  334. return;
  335. if (forcePrintModuleIR()) {
  336. auto *M = unwrapModule(IR);
  337. assert(M && "should have unwrapped module");
  338. printIR(OS, M);
  339. return;
  340. }
  341. if (any_isa<const Module *>(IR)) {
  342. const Module *M = any_cast<const Module *>(IR);
  343. printIR(OS, M);
  344. return;
  345. }
  346. if (any_isa<const Function *>(IR)) {
  347. const Function *F = any_cast<const Function *>(IR);
  348. printIR(OS, F);
  349. return;
  350. }
  351. if (any_isa<const LazyCallGraph::SCC *>(IR)) {
  352. const LazyCallGraph::SCC *C = any_cast<const LazyCallGraph::SCC *>(IR);
  353. printIR(OS, C);
  354. return;
  355. }
  356. if (any_isa<const Loop *>(IR)) {
  357. const Loop *L = any_cast<const Loop *>(IR);
  358. printIR(OS, L);
  359. return;
  360. }
  361. llvm_unreachable("Unknown wrapped IR type");
  362. }
  363. // Return true when this is a pass for which changes should be ignored
  364. bool isIgnored(StringRef PassID) {
  365. return isSpecialPass(PassID,
  366. {"PassManager", "PassAdaptor", "AnalysisManagerProxy",
  367. "DevirtSCCRepeatedPass", "ModuleInlinerWrapperPass"});
  368. }
  369. std::string makeHTMLReady(StringRef SR) {
  370. std::string S;
  371. while (true) {
  372. StringRef Clean =
  373. SR.take_until([](char C) { return C == '<' || C == '>'; });
  374. S.append(Clean.str());
  375. SR = SR.drop_front(Clean.size());
  376. if (SR.size() == 0)
  377. return S;
  378. S.append(SR[0] == '<' ? "&lt;" : "&gt;");
  379. SR = SR.drop_front();
  380. }
  381. llvm_unreachable("problems converting string to HTML");
  382. }
  383. // Return the module when that is the appropriate level of comparison for \p IR.
  384. const Module *getModuleForComparison(Any IR) {
  385. if (any_isa<const Module *>(IR))
  386. return any_cast<const Module *>(IR);
  387. if (any_isa<const LazyCallGraph::SCC *>(IR))
  388. return any_cast<const LazyCallGraph::SCC *>(IR)
  389. ->begin()
  390. ->getFunction()
  391. .getParent();
  392. return nullptr;
  393. }
  394. } // namespace
  395. template <typename T> ChangeReporter<T>::~ChangeReporter() {
  396. assert(BeforeStack.empty() && "Problem with Change Printer stack.");
  397. }
  398. template <typename T>
  399. bool ChangeReporter<T>::isInterestingFunction(const Function &F) {
  400. return isFunctionInPrintList(F.getName());
  401. }
  402. template <typename T>
  403. bool ChangeReporter<T>::isInterestingPass(StringRef PassID) {
  404. if (isIgnored(PassID))
  405. return false;
  406. static std::unordered_set<std::string> PrintPassNames(PrintPassesList.begin(),
  407. PrintPassesList.end());
  408. return PrintPassNames.empty() || PrintPassNames.count(PassID.str());
  409. }
  410. // Return true when this is a pass on IR for which printing
  411. // of changes is desired.
  412. template <typename T>
  413. bool ChangeReporter<T>::isInteresting(Any IR, StringRef PassID) {
  414. if (!isInterestingPass(PassID))
  415. return false;
  416. if (any_isa<const Function *>(IR))
  417. return isInterestingFunction(*any_cast<const Function *>(IR));
  418. return true;
  419. }
  420. template <typename T>
  421. void ChangeReporter<T>::saveIRBeforePass(Any IR, StringRef PassID) {
  422. // Always need to place something on the stack because invalidated passes
  423. // are not given the IR so it cannot be determined whether the pass was for
  424. // something that was filtered out.
  425. BeforeStack.emplace_back();
  426. if (!isInteresting(IR, PassID))
  427. return;
  428. // Is this the initial IR?
  429. if (InitialIR) {
  430. InitialIR = false;
  431. if (VerboseMode)
  432. handleInitialIR(IR);
  433. }
  434. // Save the IR representation on the stack.
  435. T &Data = BeforeStack.back();
  436. generateIRRepresentation(IR, PassID, Data);
  437. }
  438. template <typename T>
  439. void ChangeReporter<T>::handleIRAfterPass(Any IR, StringRef PassID) {
  440. assert(!BeforeStack.empty() && "Unexpected empty stack encountered.");
  441. std::string Name = getIRName(IR);
  442. if (isIgnored(PassID)) {
  443. if (VerboseMode)
  444. handleIgnored(PassID, Name);
  445. } else if (!isInteresting(IR, PassID)) {
  446. if (VerboseMode)
  447. handleFiltered(PassID, Name);
  448. } else {
  449. // Get the before rep from the stack
  450. T &Before = BeforeStack.back();
  451. // Create the after rep
  452. T After;
  453. generateIRRepresentation(IR, PassID, After);
  454. // Was there a change in IR?
  455. if (Before == After) {
  456. if (VerboseMode)
  457. omitAfter(PassID, Name);
  458. } else
  459. handleAfter(PassID, Name, Before, After, IR);
  460. }
  461. BeforeStack.pop_back();
  462. }
  463. template <typename T>
  464. void ChangeReporter<T>::handleInvalidatedPass(StringRef PassID) {
  465. assert(!BeforeStack.empty() && "Unexpected empty stack encountered.");
  466. // Always flag it as invalidated as we cannot determine when
  467. // a pass for a filtered function is invalidated since we do not
  468. // get the IR in the call. Also, the output is just alternate
  469. // forms of the banner anyway.
  470. if (VerboseMode)
  471. handleInvalidated(PassID);
  472. BeforeStack.pop_back();
  473. }
  474. template <typename T>
  475. void ChangeReporter<T>::registerRequiredCallbacks(
  476. PassInstrumentationCallbacks &PIC) {
  477. PIC.registerBeforeNonSkippedPassCallback(
  478. [this](StringRef P, Any IR) { saveIRBeforePass(IR, P); });
  479. PIC.registerAfterPassCallback(
  480. [this](StringRef P, Any IR, const PreservedAnalyses &) {
  481. handleIRAfterPass(IR, P);
  482. });
  483. PIC.registerAfterPassInvalidatedCallback(
  484. [this](StringRef P, const PreservedAnalyses &) {
  485. handleInvalidatedPass(P);
  486. });
  487. }
  488. template <typename T>
  489. TextChangeReporter<T>::TextChangeReporter(bool Verbose)
  490. : ChangeReporter<T>(Verbose), Out(dbgs()) {}
  491. template <typename T> void TextChangeReporter<T>::handleInitialIR(Any IR) {
  492. // Always print the module.
  493. // Unwrap and print directly to avoid filtering problems in general routines.
  494. auto *M = unwrapModule(IR, /*Force=*/true);
  495. assert(M && "Expected module to be unwrapped when forced.");
  496. Out << "*** IR Dump At Start ***\n";
  497. M->print(Out, nullptr);
  498. }
  499. template <typename T>
  500. void TextChangeReporter<T>::omitAfter(StringRef PassID, std::string &Name) {
  501. Out << formatv("*** IR Dump After {0} on {1} omitted because no change ***\n",
  502. PassID, Name);
  503. }
  504. template <typename T>
  505. void TextChangeReporter<T>::handleInvalidated(StringRef PassID) {
  506. Out << formatv("*** IR Pass {0} invalidated ***\n", PassID);
  507. }
  508. template <typename T>
  509. void TextChangeReporter<T>::handleFiltered(StringRef PassID,
  510. std::string &Name) {
  511. SmallString<20> Banner =
  512. formatv("*** IR Dump After {0} on {1} filtered out ***\n", PassID, Name);
  513. Out << Banner;
  514. }
  515. template <typename T>
  516. void TextChangeReporter<T>::handleIgnored(StringRef PassID, std::string &Name) {
  517. Out << formatv("*** IR Pass {0} on {1} ignored ***\n", PassID, Name);
  518. }
  519. IRChangedPrinter::~IRChangedPrinter() {}
  520. void IRChangedPrinter::registerCallbacks(PassInstrumentationCallbacks &PIC) {
  521. if (PrintChanged == ChangePrinter::PrintChangedVerbose ||
  522. PrintChanged == ChangePrinter::PrintChangedQuiet)
  523. TextChangeReporter<std::string>::registerRequiredCallbacks(PIC);
  524. }
  525. void IRChangedPrinter::generateIRRepresentation(Any IR, StringRef PassID,
  526. std::string &Output) {
  527. raw_string_ostream OS(Output);
  528. unwrapAndPrint(OS, IR);
  529. OS.str();
  530. }
  531. void IRChangedPrinter::handleAfter(StringRef PassID, std::string &Name,
  532. const std::string &Before,
  533. const std::string &After, Any) {
  534. // Report the IR before the changes when requested.
  535. if (PrintChangedBefore)
  536. Out << "*** IR Dump Before " << PassID << " on " << Name << " ***\n"
  537. << Before;
  538. // We might not get anything to print if we only want to print a specific
  539. // function but it gets deleted.
  540. if (After.empty()) {
  541. Out << "*** IR Deleted After " << PassID << " on " << Name << " ***\n";
  542. return;
  543. }
  544. Out << "*** IR Dump After " << PassID << " on " << Name << " ***\n" << After;
  545. }
  546. template <typename T>
  547. void OrderedChangedData<T>::report(
  548. const OrderedChangedData &Before, const OrderedChangedData &After,
  549. function_ref<void(const T *, const T *)> HandlePair) {
  550. const auto &BFD = Before.getData();
  551. const auto &AFD = After.getData();
  552. std::vector<std::string>::const_iterator BI = Before.getOrder().begin();
  553. std::vector<std::string>::const_iterator BE = Before.getOrder().end();
  554. std::vector<std::string>::const_iterator AI = After.getOrder().begin();
  555. std::vector<std::string>::const_iterator AE = After.getOrder().end();
  556. auto HandlePotentiallyRemovedData = [&](std::string S) {
  557. // The order in LLVM may have changed so check if still exists.
  558. if (!AFD.count(S)) {
  559. // This has been removed.
  560. HandlePair(&BFD.find(*BI)->getValue(), nullptr);
  561. }
  562. };
  563. auto HandleNewData = [&](std::vector<const T *> &Q) {
  564. // Print out any queued up new sections
  565. for (const T *NBI : Q)
  566. HandlePair(nullptr, NBI);
  567. Q.clear();
  568. };
  569. // Print out the data in the after order, with before ones interspersed
  570. // appropriately (ie, somewhere near where they were in the before list).
  571. // Start at the beginning of both lists. Loop through the
  572. // after list. If an element is common, then advance in the before list
  573. // reporting the removed ones until the common one is reached. Report any
  574. // queued up new ones and then report the common one. If an element is not
  575. // common, then enqueue it for reporting. When the after list is exhausted,
  576. // loop through the before list, reporting any removed ones. Finally,
  577. // report the rest of the enqueued new ones.
  578. std::vector<const T *> NewDataQueue;
  579. while (AI != AE) {
  580. if (!BFD.count(*AI)) {
  581. // This section is new so place it in the queue. This will cause it
  582. // to be reported after deleted sections.
  583. NewDataQueue.emplace_back(&AFD.find(*AI)->getValue());
  584. ++AI;
  585. continue;
  586. }
  587. // This section is in both; advance and print out any before-only
  588. // until we get to it.
  589. while (*BI != *AI) {
  590. HandlePotentiallyRemovedData(*BI);
  591. ++BI;
  592. }
  593. // Report any new sections that were queued up and waiting.
  594. HandleNewData(NewDataQueue);
  595. const T &AData = AFD.find(*AI)->getValue();
  596. const T &BData = BFD.find(*AI)->getValue();
  597. HandlePair(&BData, &AData);
  598. ++BI;
  599. ++AI;
  600. }
  601. // Check any remaining before sections to see if they have been removed
  602. while (BI != BE) {
  603. HandlePotentiallyRemovedData(*BI);
  604. ++BI;
  605. }
  606. HandleNewData(NewDataQueue);
  607. }
  608. template <typename T>
  609. void IRComparer<T>::compare(
  610. bool CompareModule,
  611. std::function<void(bool InModule, unsigned Minor,
  612. const FuncDataT<T> &Before, const FuncDataT<T> &After)>
  613. CompareFunc) {
  614. if (!CompareModule) {
  615. // Just handle the single function.
  616. assert(Before.getData().size() == 1 && After.getData().size() == 1 &&
  617. "Expected only one function.");
  618. CompareFunc(false, 0, Before.getData().begin()->getValue(),
  619. After.getData().begin()->getValue());
  620. return;
  621. }
  622. unsigned Minor = 0;
  623. FuncDataT<T> Missing("");
  624. IRDataT<T>::report(Before, After,
  625. [&](const FuncDataT<T> *B, const FuncDataT<T> *A) {
  626. assert((B || A) && "Both functions cannot be missing.");
  627. if (!B)
  628. B = &Missing;
  629. else if (!A)
  630. A = &Missing;
  631. CompareFunc(true, Minor++, *B, *A);
  632. });
  633. }
  634. template <typename T> void IRComparer<T>::analyzeIR(Any IR, IRDataT<T> &Data) {
  635. if (const Module *M = getModuleForComparison(IR)) {
  636. // Create data for each existing/interesting function in the module.
  637. for (const Function &F : *M)
  638. generateFunctionData(Data, F);
  639. return;
  640. }
  641. const Function *F = nullptr;
  642. if (any_isa<const Function *>(IR))
  643. F = any_cast<const Function *>(IR);
  644. else {
  645. assert(any_isa<const Loop *>(IR) && "Unknown IR unit.");
  646. const Loop *L = any_cast<const Loop *>(IR);
  647. F = L->getHeader()->getParent();
  648. }
  649. assert(F && "Unknown IR unit.");
  650. generateFunctionData(Data, *F);
  651. }
  652. template <typename T>
  653. bool IRComparer<T>::generateFunctionData(IRDataT<T> &Data, const Function &F) {
  654. if (!F.isDeclaration() && isFunctionInPrintList(F.getName())) {
  655. FuncDataT<T> FD(F.getEntryBlock().getName().str());
  656. for (const auto &B : F) {
  657. FD.getOrder().emplace_back(B.getName());
  658. FD.getData().insert({B.getName(), B});
  659. }
  660. Data.getOrder().emplace_back(F.getName());
  661. Data.getData().insert({F.getName(), FD});
  662. return true;
  663. }
  664. return false;
  665. }
  666. PrintIRInstrumentation::~PrintIRInstrumentation() {
  667. assert(ModuleDescStack.empty() && "ModuleDescStack is not empty at exit");
  668. }
  669. void PrintIRInstrumentation::pushModuleDesc(StringRef PassID, Any IR) {
  670. const Module *M = unwrapModule(IR);
  671. ModuleDescStack.emplace_back(M, getIRName(IR), PassID);
  672. }
  673. PrintIRInstrumentation::PrintModuleDesc
  674. PrintIRInstrumentation::popModuleDesc(StringRef PassID) {
  675. assert(!ModuleDescStack.empty() && "empty ModuleDescStack");
  676. PrintModuleDesc ModuleDesc = ModuleDescStack.pop_back_val();
  677. assert(std::get<2>(ModuleDesc).equals(PassID) && "malformed ModuleDescStack");
  678. return ModuleDesc;
  679. }
  680. void PrintIRInstrumentation::printBeforePass(StringRef PassID, Any IR) {
  681. if (isIgnored(PassID))
  682. return;
  683. // Saving Module for AfterPassInvalidated operations.
  684. // Note: here we rely on a fact that we do not change modules while
  685. // traversing the pipeline, so the latest captured module is good
  686. // for all print operations that has not happen yet.
  687. if (shouldPrintAfterPass(PassID))
  688. pushModuleDesc(PassID, IR);
  689. if (!shouldPrintBeforePass(PassID))
  690. return;
  691. if (!shouldPrintIR(IR))
  692. return;
  693. dbgs() << "*** IR Dump Before " << PassID << " on " << getIRName(IR)
  694. << " ***\n";
  695. unwrapAndPrint(dbgs(), IR);
  696. }
  697. void PrintIRInstrumentation::printAfterPass(StringRef PassID, Any IR) {
  698. if (isIgnored(PassID))
  699. return;
  700. if (!shouldPrintAfterPass(PassID))
  701. return;
  702. const Module *M;
  703. std::string IRName;
  704. StringRef StoredPassID;
  705. std::tie(M, IRName, StoredPassID) = popModuleDesc(PassID);
  706. assert(StoredPassID == PassID && "mismatched PassID");
  707. if (!shouldPrintIR(IR))
  708. return;
  709. dbgs() << "*** IR Dump After " << PassID << " on " << IRName << " ***\n";
  710. unwrapAndPrint(dbgs(), IR);
  711. }
  712. void PrintIRInstrumentation::printAfterPassInvalidated(StringRef PassID) {
  713. StringRef PassName = PIC->getPassNameForClassName(PassID);
  714. if (!shouldPrintAfterPass(PassName))
  715. return;
  716. if (isIgnored(PassID))
  717. return;
  718. const Module *M;
  719. std::string IRName;
  720. StringRef StoredPassID;
  721. std::tie(M, IRName, StoredPassID) = popModuleDesc(PassID);
  722. assert(StoredPassID == PassID && "mismatched PassID");
  723. // Additional filtering (e.g. -filter-print-func) can lead to module
  724. // printing being skipped.
  725. if (!M)
  726. return;
  727. SmallString<20> Banner =
  728. formatv("*** IR Dump After {0} on {1} (invalidated) ***", PassID, IRName);
  729. dbgs() << Banner << "\n";
  730. printIR(dbgs(), M);
  731. }
  732. bool PrintIRInstrumentation::shouldPrintBeforePass(StringRef PassID) {
  733. if (shouldPrintBeforeAll())
  734. return true;
  735. StringRef PassName = PIC->getPassNameForClassName(PassID);
  736. return is_contained(printBeforePasses(), PassName);
  737. }
  738. bool PrintIRInstrumentation::shouldPrintAfterPass(StringRef PassID) {
  739. if (shouldPrintAfterAll())
  740. return true;
  741. StringRef PassName = PIC->getPassNameForClassName(PassID);
  742. return is_contained(printAfterPasses(), PassName);
  743. }
  744. void PrintIRInstrumentation::registerCallbacks(
  745. PassInstrumentationCallbacks &PIC) {
  746. this->PIC = &PIC;
  747. // BeforePass callback is not just for printing, it also saves a Module
  748. // for later use in AfterPassInvalidated.
  749. if (shouldPrintBeforeSomePass() || shouldPrintAfterSomePass())
  750. PIC.registerBeforeNonSkippedPassCallback(
  751. [this](StringRef P, Any IR) { this->printBeforePass(P, IR); });
  752. if (shouldPrintAfterSomePass()) {
  753. PIC.registerAfterPassCallback(
  754. [this](StringRef P, Any IR, const PreservedAnalyses &) {
  755. this->printAfterPass(P, IR);
  756. });
  757. PIC.registerAfterPassInvalidatedCallback(
  758. [this](StringRef P, const PreservedAnalyses &) {
  759. this->printAfterPassInvalidated(P);
  760. });
  761. }
  762. }
  763. void OptNoneInstrumentation::registerCallbacks(
  764. PassInstrumentationCallbacks &PIC) {
  765. PIC.registerShouldRunOptionalPassCallback(
  766. [this](StringRef P, Any IR) { return this->shouldRun(P, IR); });
  767. }
  768. bool OptNoneInstrumentation::shouldRun(StringRef PassID, Any IR) {
  769. const Function *F = nullptr;
  770. if (any_isa<const Function *>(IR)) {
  771. F = any_cast<const Function *>(IR);
  772. } else if (any_isa<const Loop *>(IR)) {
  773. F = any_cast<const Loop *>(IR)->getHeader()->getParent();
  774. }
  775. bool ShouldRun = !(F && F->hasOptNone());
  776. if (!ShouldRun && DebugLogging) {
  777. errs() << "Skipping pass " << PassID << " on " << F->getName()
  778. << " due to optnone attribute\n";
  779. }
  780. return ShouldRun;
  781. }
  782. void OptBisectInstrumentation::registerCallbacks(
  783. PassInstrumentationCallbacks &PIC) {
  784. if (!OptBisector->isEnabled())
  785. return;
  786. PIC.registerShouldRunOptionalPassCallback([](StringRef PassID, Any IR) {
  787. return isIgnored(PassID) || OptBisector->checkPass(PassID, getIRName(IR));
  788. });
  789. }
  790. raw_ostream &PrintPassInstrumentation::print() {
  791. if (Opts.Indent) {
  792. assert(Indent >= 0);
  793. dbgs().indent(Indent);
  794. }
  795. return dbgs();
  796. }
  797. void PrintPassInstrumentation::registerCallbacks(
  798. PassInstrumentationCallbacks &PIC) {
  799. if (!Enabled)
  800. return;
  801. std::vector<StringRef> SpecialPasses;
  802. if (!Opts.Verbose) {
  803. SpecialPasses.emplace_back("PassManager");
  804. SpecialPasses.emplace_back("PassAdaptor");
  805. }
  806. PIC.registerBeforeSkippedPassCallback([this, SpecialPasses](StringRef PassID,
  807. Any IR) {
  808. assert(!isSpecialPass(PassID, SpecialPasses) &&
  809. "Unexpectedly skipping special pass");
  810. print() << "Skipping pass: " << PassID << " on " << getIRName(IR) << "\n";
  811. });
  812. PIC.registerBeforeNonSkippedPassCallback([this, SpecialPasses](
  813. StringRef PassID, Any IR) {
  814. if (isSpecialPass(PassID, SpecialPasses))
  815. return;
  816. print() << "Running pass: " << PassID << " on " << getIRName(IR) << "\n";
  817. Indent += 2;
  818. });
  819. PIC.registerAfterPassCallback(
  820. [this, SpecialPasses](StringRef PassID, Any IR,
  821. const PreservedAnalyses &) {
  822. if (isSpecialPass(PassID, SpecialPasses))
  823. return;
  824. Indent -= 2;
  825. });
  826. PIC.registerAfterPassInvalidatedCallback(
  827. [this, SpecialPasses](StringRef PassID, Any IR) {
  828. if (isSpecialPass(PassID, SpecialPasses))
  829. return;
  830. Indent -= 2;
  831. });
  832. if (!Opts.SkipAnalyses) {
  833. PIC.registerBeforeAnalysisCallback([this](StringRef PassID, Any IR) {
  834. print() << "Running analysis: " << PassID << " on " << getIRName(IR)
  835. << "\n";
  836. Indent += 2;
  837. });
  838. PIC.registerAfterAnalysisCallback(
  839. [this](StringRef PassID, Any IR) { Indent -= 2; });
  840. PIC.registerAnalysisInvalidatedCallback([this](StringRef PassID, Any IR) {
  841. print() << "Invalidating analysis: " << PassID << " on " << getIRName(IR)
  842. << "\n";
  843. });
  844. PIC.registerAnalysesClearedCallback([this](StringRef IRName) {
  845. print() << "Clearing all analysis results for: " << IRName << "\n";
  846. });
  847. }
  848. }
  849. PreservedCFGCheckerInstrumentation::CFG::CFG(const Function *F,
  850. bool TrackBBLifetime) {
  851. if (TrackBBLifetime)
  852. BBGuards = DenseMap<intptr_t, BBGuard>(F->size());
  853. for (const auto &BB : *F) {
  854. if (BBGuards)
  855. BBGuards->try_emplace(intptr_t(&BB), &BB);
  856. for (auto *Succ : successors(&BB)) {
  857. Graph[&BB][Succ]++;
  858. if (BBGuards)
  859. BBGuards->try_emplace(intptr_t(Succ), Succ);
  860. }
  861. }
  862. }
  863. static void printBBName(raw_ostream &out, const BasicBlock *BB) {
  864. if (BB->hasName()) {
  865. out << BB->getName() << "<" << BB << ">";
  866. return;
  867. }
  868. if (!BB->getParent()) {
  869. out << "unnamed_removed<" << BB << ">";
  870. return;
  871. }
  872. if (BB->isEntryBlock()) {
  873. out << "entry"
  874. << "<" << BB << ">";
  875. return;
  876. }
  877. unsigned FuncOrderBlockNum = 0;
  878. for (auto &FuncBB : *BB->getParent()) {
  879. if (&FuncBB == BB)
  880. break;
  881. FuncOrderBlockNum++;
  882. }
  883. out << "unnamed_" << FuncOrderBlockNum << "<" << BB << ">";
  884. }
  885. void PreservedCFGCheckerInstrumentation::CFG::printDiff(raw_ostream &out,
  886. const CFG &Before,
  887. const CFG &After) {
  888. assert(!After.isPoisoned());
  889. if (Before.isPoisoned()) {
  890. out << "Some blocks were deleted\n";
  891. return;
  892. }
  893. // Find and print graph differences.
  894. if (Before.Graph.size() != After.Graph.size())
  895. out << "Different number of non-leaf basic blocks: before="
  896. << Before.Graph.size() << ", after=" << After.Graph.size() << "\n";
  897. for (auto &BB : Before.Graph) {
  898. auto BA = After.Graph.find(BB.first);
  899. if (BA == After.Graph.end()) {
  900. out << "Non-leaf block ";
  901. printBBName(out, BB.first);
  902. out << " is removed (" << BB.second.size() << " successors)\n";
  903. }
  904. }
  905. for (auto &BA : After.Graph) {
  906. auto BB = Before.Graph.find(BA.first);
  907. if (BB == Before.Graph.end()) {
  908. out << "Non-leaf block ";
  909. printBBName(out, BA.first);
  910. out << " is added (" << BA.second.size() << " successors)\n";
  911. continue;
  912. }
  913. if (BB->second == BA.second)
  914. continue;
  915. out << "Different successors of block ";
  916. printBBName(out, BA.first);
  917. out << " (unordered):\n";
  918. out << "- before (" << BB->second.size() << "): ";
  919. for (auto &SuccB : BB->second) {
  920. printBBName(out, SuccB.first);
  921. if (SuccB.second != 1)
  922. out << "(" << SuccB.second << "), ";
  923. else
  924. out << ", ";
  925. }
  926. out << "\n";
  927. out << "- after (" << BA.second.size() << "): ";
  928. for (auto &SuccA : BA.second) {
  929. printBBName(out, SuccA.first);
  930. if (SuccA.second != 1)
  931. out << "(" << SuccA.second << "), ";
  932. else
  933. out << ", ";
  934. }
  935. out << "\n";
  936. }
  937. }
  938. // PreservedCFGCheckerInstrumentation uses PreservedCFGCheckerAnalysis to check
  939. // passes, that reported they kept CFG analyses up-to-date, did not actually
  940. // change CFG. This check is done as follows. Before every functional pass in
  941. // BeforeNonSkippedPassCallback a CFG snapshot (an instance of
  942. // PreservedCFGCheckerInstrumentation::CFG) is requested from
  943. // FunctionAnalysisManager as a result of PreservedCFGCheckerAnalysis. When the
  944. // functional pass finishes and reports that CFGAnalyses or AllAnalyses are
  945. // up-to-date then the cached result of PreservedCFGCheckerAnalysis (if
  946. // available) is checked to be equal to a freshly created CFG snapshot.
  947. struct PreservedCFGCheckerAnalysis
  948. : public AnalysisInfoMixin<PreservedCFGCheckerAnalysis> {
  949. friend AnalysisInfoMixin<PreservedCFGCheckerAnalysis>;
  950. static AnalysisKey Key;
  951. public:
  952. /// Provide the result type for this analysis pass.
  953. using Result = PreservedCFGCheckerInstrumentation::CFG;
  954. /// Run the analysis pass over a function and produce CFG.
  955. Result run(Function &F, FunctionAnalysisManager &FAM) {
  956. return Result(&F, /* TrackBBLifetime */ true);
  957. }
  958. };
  959. AnalysisKey PreservedCFGCheckerAnalysis::Key;
  960. bool PreservedCFGCheckerInstrumentation::CFG::invalidate(
  961. Function &F, const PreservedAnalyses &PA,
  962. FunctionAnalysisManager::Invalidator &) {
  963. auto PAC = PA.getChecker<PreservedCFGCheckerAnalysis>();
  964. return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>() ||
  965. PAC.preservedSet<CFGAnalyses>());
  966. }
  967. void PreservedCFGCheckerInstrumentation::registerCallbacks(
  968. PassInstrumentationCallbacks &PIC, FunctionAnalysisManager &FAM) {
  969. if (!VerifyPreservedCFG)
  970. return;
  971. FAM.registerPass([&] { return PreservedCFGCheckerAnalysis(); });
  972. auto checkCFG = [](StringRef Pass, StringRef FuncName, const CFG &GraphBefore,
  973. const CFG &GraphAfter) {
  974. if (GraphAfter == GraphBefore)
  975. return;
  976. dbgs() << "Error: " << Pass
  977. << " does not invalidate CFG analyses but CFG changes detected in "
  978. "function @"
  979. << FuncName << ":\n";
  980. CFG::printDiff(dbgs(), GraphBefore, GraphAfter);
  981. report_fatal_error(Twine("CFG unexpectedly changed by ", Pass));
  982. };
  983. PIC.registerBeforeNonSkippedPassCallback([this, &FAM](StringRef P, Any IR) {
  984. #ifdef LLVM_ENABLE_ABI_BREAKING_CHECKS
  985. assert(&PassStack.emplace_back(P));
  986. #endif
  987. (void)this;
  988. if (!any_isa<const Function *>(IR))
  989. return;
  990. const auto *F = any_cast<const Function *>(IR);
  991. // Make sure a fresh CFG snapshot is available before the pass.
  992. FAM.getResult<PreservedCFGCheckerAnalysis>(*const_cast<Function *>(F));
  993. });
  994. PIC.registerAfterPassInvalidatedCallback(
  995. [this](StringRef P, const PreservedAnalyses &PassPA) {
  996. #ifdef LLVM_ENABLE_ABI_BREAKING_CHECKS
  997. assert(PassStack.pop_back_val() == P &&
  998. "Before and After callbacks must correspond");
  999. #endif
  1000. (void)this;
  1001. });
  1002. PIC.registerAfterPassCallback([this, &FAM,
  1003. checkCFG](StringRef P, Any IR,
  1004. const PreservedAnalyses &PassPA) {
  1005. #ifdef LLVM_ENABLE_ABI_BREAKING_CHECKS
  1006. assert(PassStack.pop_back_val() == P &&
  1007. "Before and After callbacks must correspond");
  1008. #endif
  1009. (void)this;
  1010. if (!any_isa<const Function *>(IR))
  1011. return;
  1012. if (!PassPA.allAnalysesInSetPreserved<CFGAnalyses>() &&
  1013. !PassPA.allAnalysesInSetPreserved<AllAnalysesOn<Function>>())
  1014. return;
  1015. const auto *F = any_cast<const Function *>(IR);
  1016. if (auto *GraphBefore = FAM.getCachedResult<PreservedCFGCheckerAnalysis>(
  1017. *const_cast<Function *>(F)))
  1018. checkCFG(P, F->getName(), *GraphBefore,
  1019. CFG(F, /* TrackBBLifetime */ false));
  1020. });
  1021. }
  1022. void VerifyInstrumentation::registerCallbacks(
  1023. PassInstrumentationCallbacks &PIC) {
  1024. PIC.registerAfterPassCallback(
  1025. [this](StringRef P, Any IR, const PreservedAnalyses &PassPA) {
  1026. if (isIgnored(P) || P == "VerifierPass")
  1027. return;
  1028. if (any_isa<const Function *>(IR) || any_isa<const Loop *>(IR)) {
  1029. const Function *F;
  1030. if (any_isa<const Loop *>(IR))
  1031. F = any_cast<const Loop *>(IR)->getHeader()->getParent();
  1032. else
  1033. F = any_cast<const Function *>(IR);
  1034. if (DebugLogging)
  1035. dbgs() << "Verifying function " << F->getName() << "\n";
  1036. if (verifyFunction(*F))
  1037. report_fatal_error("Broken function found, compilation aborted!");
  1038. } else if (any_isa<const Module *>(IR) ||
  1039. any_isa<const LazyCallGraph::SCC *>(IR)) {
  1040. const Module *M;
  1041. if (any_isa<const LazyCallGraph::SCC *>(IR))
  1042. M = any_cast<const LazyCallGraph::SCC *>(IR)
  1043. ->begin()
  1044. ->getFunction()
  1045. .getParent();
  1046. else
  1047. M = any_cast<const Module *>(IR);
  1048. if (DebugLogging)
  1049. dbgs() << "Verifying module " << M->getName() << "\n";
  1050. if (verifyModule(*M))
  1051. report_fatal_error("Broken module found, compilation aborted!");
  1052. }
  1053. });
  1054. }
  1055. InLineChangePrinter::~InLineChangePrinter() {}
  1056. void InLineChangePrinter::generateIRRepresentation(Any IR, StringRef PassID,
  1057. IRDataT<EmptyData> &D) {
  1058. IRComparer<EmptyData>::analyzeIR(IR, D);
  1059. }
  1060. void InLineChangePrinter::handleAfter(StringRef PassID, std::string &Name,
  1061. const IRDataT<EmptyData> &Before,
  1062. const IRDataT<EmptyData> &After, Any IR) {
  1063. SmallString<20> Banner =
  1064. formatv("*** IR Dump After {0} on {1} ***\n", PassID, Name);
  1065. Out << Banner;
  1066. IRComparer<EmptyData>(Before, After)
  1067. .compare(getModuleForComparison(IR),
  1068. [&](bool InModule, unsigned Minor,
  1069. const FuncDataT<EmptyData> &Before,
  1070. const FuncDataT<EmptyData> &After) -> void {
  1071. handleFunctionCompare(Name, "", PassID, " on ", InModule,
  1072. Minor, Before, After);
  1073. });
  1074. Out << "\n";
  1075. }
  1076. void InLineChangePrinter::handleFunctionCompare(
  1077. StringRef Name, StringRef Prefix, StringRef PassID, StringRef Divider,
  1078. bool InModule, unsigned Minor, const FuncDataT<EmptyData> &Before,
  1079. const FuncDataT<EmptyData> &After) {
  1080. // Print a banner when this is being shown in the context of a module
  1081. if (InModule)
  1082. Out << "\n*** IR for function " << Name << " ***\n";
  1083. FuncDataT<EmptyData>::report(
  1084. Before, After,
  1085. [&](const BlockDataT<EmptyData> *B, const BlockDataT<EmptyData> *A) {
  1086. StringRef BStr = B ? B->getBody() : "\n";
  1087. StringRef AStr = A ? A->getBody() : "\n";
  1088. const std::string Removed =
  1089. UseColour ? "\033[31m-%l\033[0m\n" : "-%l\n";
  1090. const std::string Added = UseColour ? "\033[32m+%l\033[0m\n" : "+%l\n";
  1091. const std::string NoChange = " %l\n";
  1092. Out << doSystemDiff(BStr, AStr, Removed, Added, NoChange);
  1093. });
  1094. }
  1095. void InLineChangePrinter::registerCallbacks(PassInstrumentationCallbacks &PIC) {
  1096. if (PrintChanged == ChangePrinter::PrintChangedDiffVerbose ||
  1097. PrintChanged == ChangePrinter::PrintChangedDiffQuiet ||
  1098. PrintChanged == ChangePrinter::PrintChangedColourDiffVerbose ||
  1099. PrintChanged == ChangePrinter::PrintChangedColourDiffQuiet)
  1100. TextChangeReporter<IRDataT<EmptyData>>::registerRequiredCallbacks(PIC);
  1101. }
  1102. namespace {
  1103. class DisplayNode;
  1104. class DotCfgDiffDisplayGraph;
  1105. // Base class for a node or edge in the dot-cfg-changes graph.
  1106. class DisplayElement {
  1107. public:
  1108. // Is this in before, after, or both?
  1109. StringRef getColour() const { return Colour; }
  1110. protected:
  1111. DisplayElement(StringRef Colour) : Colour(Colour) {}
  1112. const StringRef Colour;
  1113. };
  1114. // An edge representing a transition between basic blocks in the
  1115. // dot-cfg-changes graph.
  1116. class DisplayEdge : public DisplayElement {
  1117. public:
  1118. DisplayEdge(std::string Value, DisplayNode &Node, StringRef Colour)
  1119. : DisplayElement(Colour), Value(Value), Node(Node) {}
  1120. // The value on which the transition is made.
  1121. std::string getValue() const { return Value; }
  1122. // The node (representing a basic block) reached by this transition.
  1123. const DisplayNode &getDestinationNode() const { return Node; }
  1124. protected:
  1125. std::string Value;
  1126. const DisplayNode &Node;
  1127. };
  1128. // A node in the dot-cfg-changes graph which represents a basic block.
  1129. class DisplayNode : public DisplayElement {
  1130. public:
  1131. // \p C is the content for the node, \p T indicates the colour for the
  1132. // outline of the node
  1133. DisplayNode(std::string Content, StringRef Colour)
  1134. : DisplayElement(Colour), Content(Content) {}
  1135. // Iterator to the child nodes. Required by GraphWriter.
  1136. using ChildIterator = std::unordered_set<DisplayNode *>::const_iterator;
  1137. ChildIterator children_begin() const { return Children.cbegin(); }
  1138. ChildIterator children_end() const { return Children.cend(); }
  1139. // Iterator for the edges. Required by GraphWriter.
  1140. using EdgeIterator = std::vector<DisplayEdge *>::const_iterator;
  1141. EdgeIterator edges_begin() const { return EdgePtrs.cbegin(); }
  1142. EdgeIterator edges_end() const { return EdgePtrs.cend(); }
  1143. // Create an edge to \p Node on value \p Value, with colour \p Colour.
  1144. void createEdge(StringRef Value, DisplayNode &Node, StringRef Colour);
  1145. // Return the content of this node.
  1146. std::string getContent() const { return Content; }
  1147. // Return the edge to node \p S.
  1148. const DisplayEdge &getEdge(const DisplayNode &To) const {
  1149. assert(EdgeMap.find(&To) != EdgeMap.end() && "Expected to find edge.");
  1150. return *EdgeMap.find(&To)->second;
  1151. }
  1152. // Return the value for the transition to basic block \p S.
  1153. // Required by GraphWriter.
  1154. std::string getEdgeSourceLabel(const DisplayNode &Sink) const {
  1155. return getEdge(Sink).getValue();
  1156. }
  1157. void createEdgeMap();
  1158. protected:
  1159. const std::string Content;
  1160. // Place to collect all of the edges. Once they are all in the vector,
  1161. // the vector will not reallocate so then we can use pointers to them,
  1162. // which are required by the graph writing routines.
  1163. std::vector<DisplayEdge> Edges;
  1164. std::vector<DisplayEdge *> EdgePtrs;
  1165. std::unordered_set<DisplayNode *> Children;
  1166. std::unordered_map<const DisplayNode *, const DisplayEdge *> EdgeMap;
  1167. // Safeguard adding of edges.
  1168. bool AllEdgesCreated = false;
  1169. };
  1170. // Class representing a difference display (corresponds to a pdf file).
  1171. class DotCfgDiffDisplayGraph {
  1172. public:
  1173. DotCfgDiffDisplayGraph(std::string Name) : GraphName(Name) {}
  1174. // Generate the file into \p DotFile.
  1175. void generateDotFile(StringRef DotFile);
  1176. // Iterator to the nodes. Required by GraphWriter.
  1177. using NodeIterator = std::vector<DisplayNode *>::const_iterator;
  1178. NodeIterator nodes_begin() const {
  1179. assert(NodeGenerationComplete && "Unexpected children iterator creation");
  1180. return NodePtrs.cbegin();
  1181. }
  1182. NodeIterator nodes_end() const {
  1183. assert(NodeGenerationComplete && "Unexpected children iterator creation");
  1184. return NodePtrs.cend();
  1185. }
  1186. // Record the index of the entry node. At this point, we can build up
  1187. // vectors of pointers that are required by the graph routines.
  1188. void setEntryNode(unsigned N) {
  1189. // At this point, there will be no new nodes.
  1190. assert(!NodeGenerationComplete && "Unexpected node creation");
  1191. NodeGenerationComplete = true;
  1192. for (auto &N : Nodes)
  1193. NodePtrs.emplace_back(&N);
  1194. EntryNode = NodePtrs[N];
  1195. }
  1196. // Create a node.
  1197. void createNode(std::string C, StringRef Colour) {
  1198. assert(!NodeGenerationComplete && "Unexpected node creation");
  1199. Nodes.emplace_back(C, Colour);
  1200. }
  1201. // Return the node at index \p N to avoid problems with vectors reallocating.
  1202. DisplayNode &getNode(unsigned N) {
  1203. assert(N < Nodes.size() && "Node is out of bounds");
  1204. return Nodes[N];
  1205. }
  1206. unsigned size() const {
  1207. assert(NodeGenerationComplete && "Unexpected children iterator creation");
  1208. return Nodes.size();
  1209. }
  1210. // Return the name of the graph. Required by GraphWriter.
  1211. std::string getGraphName() const { return GraphName; }
  1212. // Return the string representing the differences for basic block \p Node.
  1213. // Required by GraphWriter.
  1214. std::string getNodeLabel(const DisplayNode &Node) const {
  1215. return Node.getContent();
  1216. }
  1217. // Return a string with colour information for Dot. Required by GraphWriter.
  1218. std::string getNodeAttributes(const DisplayNode &Node) const {
  1219. return attribute(Node.getColour());
  1220. }
  1221. // Return a string with colour information for Dot. Required by GraphWriter.
  1222. std::string getEdgeColorAttr(const DisplayNode &From,
  1223. const DisplayNode &To) const {
  1224. return attribute(From.getEdge(To).getColour());
  1225. }
  1226. // Get the starting basic block. Required by GraphWriter.
  1227. DisplayNode *getEntryNode() const {
  1228. assert(NodeGenerationComplete && "Unexpected children iterator creation");
  1229. return EntryNode;
  1230. }
  1231. protected:
  1232. // Return the string containing the colour to use as a Dot attribute.
  1233. std::string attribute(StringRef Colour) const {
  1234. return "color=" + Colour.str();
  1235. }
  1236. bool NodeGenerationComplete = false;
  1237. const std::string GraphName;
  1238. std::vector<DisplayNode> Nodes;
  1239. std::vector<DisplayNode *> NodePtrs;
  1240. DisplayNode *EntryNode = nullptr;
  1241. };
  1242. void DisplayNode::createEdge(StringRef Value, DisplayNode &Node,
  1243. StringRef Colour) {
  1244. assert(!AllEdgesCreated && "Expected to be able to still create edges.");
  1245. Edges.emplace_back(Value.str(), Node, Colour);
  1246. Children.insert(&Node);
  1247. }
  1248. void DisplayNode::createEdgeMap() {
  1249. // No more edges will be added so we can now use pointers to the edges
  1250. // as the vector will not grow and reallocate.
  1251. AllEdgesCreated = true;
  1252. for (auto &E : Edges)
  1253. EdgeMap.insert({&E.getDestinationNode(), &E});
  1254. }
  1255. class DotCfgDiffNode;
  1256. class DotCfgDiff;
  1257. // A class representing a basic block in the Dot difference graph.
  1258. class DotCfgDiffNode {
  1259. public:
  1260. DotCfgDiffNode() = delete;
  1261. // Create a node in Dot difference graph \p G representing the basic block
  1262. // represented by \p BD with colour \p Colour (where it exists).
  1263. DotCfgDiffNode(DotCfgDiff &G, unsigned N, const BlockDataT<DCData> &BD,
  1264. StringRef Colour)
  1265. : Graph(G), N(N), Data{&BD, nullptr}, Colour(Colour) {}
  1266. DotCfgDiffNode(const DotCfgDiffNode &DN)
  1267. : Graph(DN.Graph), N(DN.N), Data{DN.Data[0], DN.Data[1]},
  1268. Colour(DN.Colour), EdgesMap(DN.EdgesMap), Children(DN.Children),
  1269. Edges(DN.Edges) {}
  1270. unsigned getIndex() const { return N; }
  1271. // The label of the basic block
  1272. StringRef getLabel() const {
  1273. assert(Data[0] && "Expected Data[0] to be set.");
  1274. return Data[0]->getLabel();
  1275. }
  1276. // Return the colour for this block
  1277. StringRef getColour() const { return Colour; }
  1278. // Change this basic block from being only in before to being common.
  1279. // Save the pointer to \p Other.
  1280. void setCommon(const BlockDataT<DCData> &Other) {
  1281. assert(!Data[1] && "Expected only one block datum");
  1282. Data[1] = &Other;
  1283. Colour = CommonColour;
  1284. }
  1285. // Add an edge to \p E of colour {\p Value, \p Colour}.
  1286. void addEdge(unsigned E, StringRef Value, StringRef Colour) {
  1287. // This is a new edge or it is an edge being made common.
  1288. assert((EdgesMap.count(E) == 0 || Colour == CommonColour) &&
  1289. "Unexpected edge count and color.");
  1290. EdgesMap[E] = {Value.str(), Colour};
  1291. }
  1292. // Record the children and create edges.
  1293. void finalize(DotCfgDiff &G);
  1294. // Return the colour of the edge to node \p S.
  1295. StringRef getEdgeColour(const unsigned S) const {
  1296. assert(EdgesMap.count(S) == 1 && "Expected to find edge.");
  1297. return EdgesMap.at(S).second;
  1298. }
  1299. // Return the string representing the basic block.
  1300. std::string getBodyContent() const;
  1301. void createDisplayEdges(DotCfgDiffDisplayGraph &Graph, unsigned DisplayNode,
  1302. std::map<const unsigned, unsigned> &NodeMap) const;
  1303. protected:
  1304. DotCfgDiff &Graph;
  1305. const unsigned N;
  1306. const BlockDataT<DCData> *Data[2];
  1307. StringRef Colour;
  1308. std::map<const unsigned, std::pair<std::string, StringRef>> EdgesMap;
  1309. std::vector<unsigned> Children;
  1310. std::vector<unsigned> Edges;
  1311. };
  1312. // Class representing the difference graph between two functions.
  1313. class DotCfgDiff {
  1314. public:
  1315. // \p Title is the title given to the graph. \p EntryNodeName is the
  1316. // entry node for the function. \p Before and \p After are the before
  1317. // after versions of the function, respectively. \p Dir is the directory
  1318. // in which to store the results.
  1319. DotCfgDiff(StringRef Title, const FuncDataT<DCData> &Before,
  1320. const FuncDataT<DCData> &After);
  1321. DotCfgDiff(const DotCfgDiff &) = delete;
  1322. DotCfgDiff &operator=(const DotCfgDiff &) = delete;
  1323. DotCfgDiffDisplayGraph createDisplayGraph(StringRef Title,
  1324. StringRef EntryNodeName);
  1325. // Return a string consisting of the labels for the \p Source and \p Sink.
  1326. // The combination allows distinguishing changing transitions on the
  1327. // same value (ie, a transition went to X before and goes to Y after).
  1328. // Required by GraphWriter.
  1329. StringRef getEdgeSourceLabel(const unsigned &Source,
  1330. const unsigned &Sink) const {
  1331. std::string S =
  1332. getNode(Source).getLabel().str() + " " + getNode(Sink).getLabel().str();
  1333. assert(EdgeLabels.count(S) == 1 && "Expected to find edge label.");
  1334. return EdgeLabels.find(S)->getValue();
  1335. }
  1336. // Return the number of basic blocks (nodes). Required by GraphWriter.
  1337. unsigned size() const { return Nodes.size(); }
  1338. const DotCfgDiffNode &getNode(unsigned N) const {
  1339. assert(N < Nodes.size() && "Unexpected index for node reference");
  1340. return Nodes[N];
  1341. }
  1342. protected:
  1343. // Return the string surrounded by HTML to make it the appropriate colour.
  1344. std::string colourize(std::string S, StringRef Colour) const;
  1345. void createNode(StringRef Label, const BlockDataT<DCData> &BD, StringRef C) {
  1346. unsigned Pos = Nodes.size();
  1347. Nodes.emplace_back(*this, Pos, BD, C);
  1348. NodePosition.insert({Label, Pos});
  1349. }
  1350. // TODO Nodes should probably be a StringMap<DotCfgDiffNode> after the
  1351. // display graph is separated out, which would remove the need for
  1352. // NodePosition.
  1353. std::vector<DotCfgDiffNode> Nodes;
  1354. StringMap<unsigned> NodePosition;
  1355. const std::string GraphName;
  1356. StringMap<std::string> EdgeLabels;
  1357. };
  1358. std::string DotCfgDiffNode::getBodyContent() const {
  1359. if (Colour == CommonColour) {
  1360. assert(Data[1] && "Expected Data[1] to be set.");
  1361. StringRef SR[2];
  1362. for (unsigned I = 0; I < 2; ++I) {
  1363. SR[I] = Data[I]->getBody();
  1364. // drop initial '\n' if present
  1365. if (SR[I][0] == '\n')
  1366. SR[I] = SR[I].drop_front();
  1367. // drop predecessors as they can be big and are redundant
  1368. SR[I] = SR[I].drop_until([](char C) { return C == '\n'; }).drop_front();
  1369. }
  1370. SmallString<80> OldLineFormat = formatv(
  1371. "<FONT COLOR=\"{0}\">%l</FONT><BR align=\"left\"/>", BeforeColour);
  1372. SmallString<80> NewLineFormat = formatv(
  1373. "<FONT COLOR=\"{0}\">%l</FONT><BR align=\"left\"/>", AfterColour);
  1374. SmallString<80> UnchangedLineFormat = formatv(
  1375. "<FONT COLOR=\"{0}\">%l</FONT><BR align=\"left\"/>", CommonColour);
  1376. std::string Diff = Data[0]->getLabel().str();
  1377. Diff += ":\n<BR align=\"left\"/>" +
  1378. doSystemDiff(makeHTMLReady(SR[0]), makeHTMLReady(SR[1]),
  1379. OldLineFormat, NewLineFormat, UnchangedLineFormat);
  1380. // Diff adds in some empty colour changes which are not valid HTML
  1381. // so remove them. Colours are all lowercase alpha characters (as
  1382. // listed in https://graphviz.org/pdf/dotguide.pdf).
  1383. Regex R("<FONT COLOR=\"\\w+\"></FONT>");
  1384. while (true) {
  1385. std::string Error;
  1386. std::string S = R.sub("", Diff, &Error);
  1387. if (Error != "")
  1388. return Error;
  1389. if (S == Diff)
  1390. return Diff;
  1391. Diff = S;
  1392. }
  1393. llvm_unreachable("Should not get here");
  1394. }
  1395. // Put node out in the appropriate colour.
  1396. assert(!Data[1] && "Data[1] is set unexpectedly.");
  1397. std::string Body = makeHTMLReady(Data[0]->getBody());
  1398. const StringRef BS = Body;
  1399. StringRef BS1 = BS;
  1400. // Drop leading newline, if present.
  1401. if (BS.front() == '\n')
  1402. BS1 = BS1.drop_front(1);
  1403. // Get label.
  1404. StringRef Label = BS1.take_until([](char C) { return C == ':'; });
  1405. // drop predecessors as they can be big and are redundant
  1406. BS1 = BS1.drop_until([](char C) { return C == '\n'; }).drop_front();
  1407. std::string S = "<FONT COLOR=\"" + Colour.str() + "\">" + Label.str() + ":";
  1408. // align each line to the left.
  1409. while (BS1.size()) {
  1410. S.append("<BR align=\"left\"/>");
  1411. StringRef Line = BS1.take_until([](char C) { return C == '\n'; });
  1412. S.append(Line.str());
  1413. BS1 = BS1.drop_front(Line.size() + 1);
  1414. }
  1415. S.append("<BR align=\"left\"/></FONT>");
  1416. return S;
  1417. }
  1418. std::string DotCfgDiff::colourize(std::string S, StringRef Colour) const {
  1419. if (S.length() == 0)
  1420. return S;
  1421. return "<FONT COLOR=\"" + Colour.str() + "\">" + S + "</FONT>";
  1422. }
  1423. DotCfgDiff::DotCfgDiff(StringRef Title, const FuncDataT<DCData> &Before,
  1424. const FuncDataT<DCData> &After)
  1425. : GraphName(Title.str()) {
  1426. StringMap<StringRef> EdgesMap;
  1427. // Handle each basic block in the before IR.
  1428. for (auto &B : Before.getData()) {
  1429. StringRef Label = B.getKey();
  1430. const BlockDataT<DCData> &BD = B.getValue();
  1431. createNode(Label, BD, BeforeColour);
  1432. // Create transitions with names made up of the from block label, the value
  1433. // on which the transition is made and the to block label.
  1434. for (StringMap<std::string>::const_iterator Sink = BD.getData().begin(),
  1435. E = BD.getData().end();
  1436. Sink != E; ++Sink) {
  1437. std::string Key = (Label + " " + Sink->getKey().str()).str() + " " +
  1438. BD.getData().getSuccessorLabel(Sink->getKey()).str();
  1439. EdgesMap.insert({Key, BeforeColour});
  1440. }
  1441. }
  1442. // Handle each basic block in the after IR
  1443. for (auto &A : After.getData()) {
  1444. StringRef Label = A.getKey();
  1445. const BlockDataT<DCData> &BD = A.getValue();
  1446. unsigned C = NodePosition.count(Label);
  1447. if (C == 0)
  1448. // This only exists in the after IR. Create the node.
  1449. createNode(Label, BD, AfterColour);
  1450. else {
  1451. assert(C == 1 && "Unexpected multiple nodes.");
  1452. Nodes[NodePosition[Label]].setCommon(BD);
  1453. }
  1454. // Add in the edges between the nodes (as common or only in after).
  1455. for (StringMap<std::string>::const_iterator Sink = BD.getData().begin(),
  1456. E = BD.getData().end();
  1457. Sink != E; ++Sink) {
  1458. std::string Key = (Label + " " + Sink->getKey().str()).str() + " " +
  1459. BD.getData().getSuccessorLabel(Sink->getKey()).str();
  1460. unsigned C = EdgesMap.count(Key);
  1461. if (C == 0)
  1462. EdgesMap.insert({Key, AfterColour});
  1463. else {
  1464. EdgesMap[Key] = CommonColour;
  1465. }
  1466. }
  1467. }
  1468. // Now go through the map of edges and add them to the node.
  1469. for (auto &E : EdgesMap) {
  1470. // Extract the source, sink and value from the edge key.
  1471. StringRef S = E.getKey();
  1472. auto SP1 = S.rsplit(' ');
  1473. auto &SourceSink = SP1.first;
  1474. auto SP2 = SourceSink.split(' ');
  1475. StringRef Source = SP2.first;
  1476. StringRef Sink = SP2.second;
  1477. StringRef Value = SP1.second;
  1478. assert(NodePosition.count(Source) == 1 && "Expected to find node.");
  1479. DotCfgDiffNode &SourceNode = Nodes[NodePosition[Source]];
  1480. assert(NodePosition.count(Sink) == 1 && "Expected to find node.");
  1481. unsigned SinkNode = NodePosition[Sink];
  1482. StringRef Colour = E.second;
  1483. // Look for an edge from Source to Sink
  1484. if (EdgeLabels.count(SourceSink) == 0)
  1485. EdgeLabels.insert({SourceSink, colourize(Value.str(), Colour)});
  1486. else {
  1487. StringRef V = EdgeLabels.find(SourceSink)->getValue();
  1488. std::string NV = colourize(V.str() + " " + Value.str(), Colour);
  1489. Colour = CommonColour;
  1490. EdgeLabels[SourceSink] = NV;
  1491. }
  1492. SourceNode.addEdge(SinkNode, Value, Colour);
  1493. }
  1494. for (auto &I : Nodes)
  1495. I.finalize(*this);
  1496. }
  1497. DotCfgDiffDisplayGraph DotCfgDiff::createDisplayGraph(StringRef Title,
  1498. StringRef EntryNodeName) {
  1499. assert(NodePosition.count(EntryNodeName) == 1 &&
  1500. "Expected to find entry block in map.");
  1501. unsigned Entry = NodePosition[EntryNodeName];
  1502. assert(Entry < Nodes.size() && "Expected to find entry node");
  1503. DotCfgDiffDisplayGraph G(Title.str());
  1504. std::map<const unsigned, unsigned> NodeMap;
  1505. int EntryIndex = -1;
  1506. unsigned Index = 0;
  1507. for (auto &I : Nodes) {
  1508. if (I.getIndex() == Entry)
  1509. EntryIndex = Index;
  1510. G.createNode(I.getBodyContent(), I.getColour());
  1511. NodeMap.insert({I.getIndex(), Index++});
  1512. }
  1513. assert(EntryIndex >= 0 && "Expected entry node index to be set.");
  1514. G.setEntryNode(EntryIndex);
  1515. for (auto &I : NodeMap) {
  1516. unsigned SourceNode = I.first;
  1517. unsigned DisplayNode = I.second;
  1518. getNode(SourceNode).createDisplayEdges(G, DisplayNode, NodeMap);
  1519. }
  1520. return G;
  1521. }
  1522. void DotCfgDiffNode::createDisplayEdges(
  1523. DotCfgDiffDisplayGraph &DisplayGraph, unsigned DisplayNodeIndex,
  1524. std::map<const unsigned, unsigned> &NodeMap) const {
  1525. DisplayNode &SourceDisplayNode = DisplayGraph.getNode(DisplayNodeIndex);
  1526. for (auto I : Edges) {
  1527. unsigned SinkNodeIndex = I;
  1528. StringRef Colour = getEdgeColour(SinkNodeIndex);
  1529. const DotCfgDiffNode *SinkNode = &Graph.getNode(SinkNodeIndex);
  1530. StringRef Label = Graph.getEdgeSourceLabel(getIndex(), SinkNodeIndex);
  1531. DisplayNode &SinkDisplayNode = DisplayGraph.getNode(SinkNode->getIndex());
  1532. SourceDisplayNode.createEdge(Label, SinkDisplayNode, Colour);
  1533. }
  1534. SourceDisplayNode.createEdgeMap();
  1535. }
  1536. void DotCfgDiffNode::finalize(DotCfgDiff &G) {
  1537. for (auto E : EdgesMap) {
  1538. Children.emplace_back(E.first);
  1539. Edges.emplace_back(E.first);
  1540. }
  1541. }
  1542. } // namespace
  1543. namespace llvm {
  1544. template <> struct GraphTraits<DotCfgDiffDisplayGraph *> {
  1545. using NodeRef = const DisplayNode *;
  1546. using ChildIteratorType = DisplayNode::ChildIterator;
  1547. using nodes_iterator = DotCfgDiffDisplayGraph::NodeIterator;
  1548. using EdgeRef = const DisplayEdge *;
  1549. using ChildEdgeIterator = DisplayNode::EdgeIterator;
  1550. static NodeRef getEntryNode(const DotCfgDiffDisplayGraph *G) {
  1551. return G->getEntryNode();
  1552. }
  1553. static ChildIteratorType child_begin(NodeRef N) {
  1554. return N->children_begin();
  1555. }
  1556. static ChildIteratorType child_end(NodeRef N) { return N->children_end(); }
  1557. static nodes_iterator nodes_begin(const DotCfgDiffDisplayGraph *G) {
  1558. return G->nodes_begin();
  1559. }
  1560. static nodes_iterator nodes_end(const DotCfgDiffDisplayGraph *G) {
  1561. return G->nodes_end();
  1562. }
  1563. static ChildEdgeIterator child_edge_begin(NodeRef N) {
  1564. return N->edges_begin();
  1565. }
  1566. static ChildEdgeIterator child_edge_end(NodeRef N) { return N->edges_end(); }
  1567. static NodeRef edge_dest(EdgeRef E) { return &E->getDestinationNode(); }
  1568. static unsigned size(const DotCfgDiffDisplayGraph *G) { return G->size(); }
  1569. };
  1570. template <>
  1571. struct DOTGraphTraits<DotCfgDiffDisplayGraph *> : public DefaultDOTGraphTraits {
  1572. explicit DOTGraphTraits(bool Simple = false)
  1573. : DefaultDOTGraphTraits(Simple) {}
  1574. static bool renderNodesUsingHTML() { return true; }
  1575. static std::string getGraphName(const DotCfgDiffDisplayGraph *DiffData) {
  1576. return DiffData->getGraphName();
  1577. }
  1578. static std::string
  1579. getGraphProperties(const DotCfgDiffDisplayGraph *DiffData) {
  1580. return "\tsize=\"190, 190\";\n";
  1581. }
  1582. static std::string getNodeLabel(const DisplayNode *Node,
  1583. const DotCfgDiffDisplayGraph *DiffData) {
  1584. return DiffData->getNodeLabel(*Node);
  1585. }
  1586. static std::string getNodeAttributes(const DisplayNode *Node,
  1587. const DotCfgDiffDisplayGraph *DiffData) {
  1588. return DiffData->getNodeAttributes(*Node);
  1589. }
  1590. static std::string getEdgeSourceLabel(const DisplayNode *From,
  1591. DisplayNode::ChildIterator &To) {
  1592. return From->getEdgeSourceLabel(**To);
  1593. }
  1594. static std::string getEdgeAttributes(const DisplayNode *From,
  1595. DisplayNode::ChildIterator &To,
  1596. const DotCfgDiffDisplayGraph *DiffData) {
  1597. return DiffData->getEdgeColorAttr(*From, **To);
  1598. }
  1599. };
  1600. } // namespace llvm
  1601. namespace {
  1602. void DotCfgDiffDisplayGraph::generateDotFile(StringRef DotFile) {
  1603. std::error_code EC;
  1604. raw_fd_ostream OutStream(DotFile, EC);
  1605. if (EC) {
  1606. errs() << "Error: " << EC.message() << "\n";
  1607. return;
  1608. }
  1609. WriteGraph(OutStream, this, false);
  1610. OutStream.flush();
  1611. OutStream.close();
  1612. }
  1613. } // namespace
  1614. namespace llvm {
  1615. DCData::DCData(const BasicBlock &B) {
  1616. // Build up transition labels.
  1617. const Instruction *Term = B.getTerminator();
  1618. if (const BranchInst *Br = dyn_cast<const BranchInst>(Term))
  1619. if (Br->isUnconditional())
  1620. addSuccessorLabel(Br->getSuccessor(0)->getName().str(), "");
  1621. else {
  1622. addSuccessorLabel(Br->getSuccessor(0)->getName().str(), "true");
  1623. addSuccessorLabel(Br->getSuccessor(1)->getName().str(), "false");
  1624. }
  1625. else if (const SwitchInst *Sw = dyn_cast<const SwitchInst>(Term)) {
  1626. addSuccessorLabel(Sw->case_default()->getCaseSuccessor()->getName().str(),
  1627. "default");
  1628. for (auto &C : Sw->cases()) {
  1629. assert(C.getCaseValue() && "Expected to find case value.");
  1630. SmallString<20> Value = formatv("{0}", C.getCaseValue()->getSExtValue());
  1631. addSuccessorLabel(C.getCaseSuccessor()->getName().str(), Value);
  1632. }
  1633. } else
  1634. for (const_succ_iterator I = succ_begin(&B), E = succ_end(&B); I != E; ++I)
  1635. addSuccessorLabel((*I)->getName().str(), "");
  1636. }
  1637. DotCfgChangeReporter::DotCfgChangeReporter(bool Verbose)
  1638. : ChangeReporter<IRDataT<DCData>>(Verbose) {}
  1639. void DotCfgChangeReporter::handleFunctionCompare(
  1640. StringRef Name, StringRef Prefix, StringRef PassID, StringRef Divider,
  1641. bool InModule, unsigned Minor, const FuncDataT<DCData> &Before,
  1642. const FuncDataT<DCData> &After) {
  1643. assert(HTML && "Expected outstream to be set");
  1644. SmallString<8> Extender;
  1645. SmallString<8> Number;
  1646. // Handle numbering and file names.
  1647. if (InModule) {
  1648. Extender = formatv("{0}_{1}", N, Minor);
  1649. Number = formatv("{0}.{1}", N, Minor);
  1650. } else {
  1651. Extender = formatv("{0}", N);
  1652. Number = formatv("{0}", N);
  1653. }
  1654. // Create a temporary file name for the dot file.
  1655. SmallVector<char, 128> SV;
  1656. sys::fs::createUniquePath("cfgdot-%%%%%%.dot", SV, true);
  1657. std::string DotFile = Twine(SV).str();
  1658. SmallString<20> PDFFileName = formatv("diff_{0}.pdf", Extender);
  1659. SmallString<200> Text;
  1660. Text = formatv("{0}.{1}{2}{3}{4}", Number, Prefix, makeHTMLReady(PassID),
  1661. Divider, Name);
  1662. DotCfgDiff Diff(Text, Before, After);
  1663. std::string EntryBlockName = After.getEntryBlockName();
  1664. // Use the before entry block if the after entry block was removed.
  1665. if (EntryBlockName == "")
  1666. EntryBlockName = Before.getEntryBlockName();
  1667. assert(EntryBlockName != "" && "Expected to find entry block");
  1668. DotCfgDiffDisplayGraph DG = Diff.createDisplayGraph(Text, EntryBlockName);
  1669. DG.generateDotFile(DotFile);
  1670. *HTML << genHTML(Text, DotFile, PDFFileName);
  1671. std::error_code EC = sys::fs::remove(DotFile);
  1672. if (EC)
  1673. errs() << "Error: " << EC.message() << "\n";
  1674. }
  1675. std::string DotCfgChangeReporter::genHTML(StringRef Text, StringRef DotFile,
  1676. StringRef PDFFileName) {
  1677. SmallString<20> PDFFile = formatv("{0}/{1}", DotCfgDir, PDFFileName);
  1678. // Create the PDF file.
  1679. static ErrorOr<std::string> DotExe = sys::findProgramByName(DotBinary);
  1680. if (!DotExe)
  1681. return "Unable to find dot executable.";
  1682. StringRef Args[] = {DotBinary, "-Tpdf", "-o", PDFFile, DotFile};
  1683. int Result = sys::ExecuteAndWait(*DotExe, Args, None);
  1684. if (Result < 0)
  1685. return "Error executing system dot.";
  1686. // Create the HTML tag refering to the PDF file.
  1687. SmallString<200> S = formatv(
  1688. " <a href=\"{0}\" target=\"_blank\">{1}</a><br/>\n", PDFFileName, Text);
  1689. return S.c_str();
  1690. }
  1691. void DotCfgChangeReporter::handleInitialIR(Any IR) {
  1692. assert(HTML && "Expected outstream to be set");
  1693. *HTML << "<button type=\"button\" class=\"collapsible\">0. "
  1694. << "Initial IR (by function)</button>\n"
  1695. << "<div class=\"content\">\n"
  1696. << " <p>\n";
  1697. // Create representation of IR
  1698. IRDataT<DCData> Data;
  1699. IRComparer<DCData>::analyzeIR(IR, Data);
  1700. // Now compare it against itself, which will have everything the
  1701. // same and will generate the files.
  1702. IRComparer<DCData>(Data, Data)
  1703. .compare(getModuleForComparison(IR),
  1704. [&](bool InModule, unsigned Minor,
  1705. const FuncDataT<DCData> &Before,
  1706. const FuncDataT<DCData> &After) -> void {
  1707. handleFunctionCompare("", " ", "Initial IR", "", InModule,
  1708. Minor, Before, After);
  1709. });
  1710. *HTML << " </p>\n"
  1711. << "</div><br/>\n";
  1712. ++N;
  1713. }
  1714. void DotCfgChangeReporter::generateIRRepresentation(Any IR, StringRef PassID,
  1715. IRDataT<DCData> &Data) {
  1716. IRComparer<DCData>::analyzeIR(IR, Data);
  1717. }
  1718. void DotCfgChangeReporter::omitAfter(StringRef PassID, std::string &Name) {
  1719. assert(HTML && "Expected outstream to be set");
  1720. SmallString<20> Banner =
  1721. formatv(" <a>{0}. Pass {1} on {2} omitted because no change</a><br/>\n",
  1722. N, makeHTMLReady(PassID), Name);
  1723. *HTML << Banner;
  1724. ++N;
  1725. }
  1726. void DotCfgChangeReporter::handleAfter(StringRef PassID, std::string &Name,
  1727. const IRDataT<DCData> &Before,
  1728. const IRDataT<DCData> &After, Any IR) {
  1729. assert(HTML && "Expected outstream to be set");
  1730. IRComparer<DCData>(Before, After)
  1731. .compare(getModuleForComparison(IR),
  1732. [&](bool InModule, unsigned Minor,
  1733. const FuncDataT<DCData> &Before,
  1734. const FuncDataT<DCData> &After) -> void {
  1735. handleFunctionCompare(Name, " Pass ", PassID, " on ", InModule,
  1736. Minor, Before, After);
  1737. });
  1738. *HTML << " </p></div>\n";
  1739. ++N;
  1740. }
  1741. void DotCfgChangeReporter::handleInvalidated(StringRef PassID) {
  1742. assert(HTML && "Expected outstream to be set");
  1743. SmallString<20> Banner =
  1744. formatv(" <a>{0}. {1} invalidated</a><br/>\n", N, makeHTMLReady(PassID));
  1745. *HTML << Banner;
  1746. ++N;
  1747. }
  1748. void DotCfgChangeReporter::handleFiltered(StringRef PassID, std::string &Name) {
  1749. assert(HTML && "Expected outstream to be set");
  1750. SmallString<20> Banner =
  1751. formatv(" <a>{0}. Pass {1} on {2} filtered out</a><br/>\n", N,
  1752. makeHTMLReady(PassID), Name);
  1753. *HTML << Banner;
  1754. ++N;
  1755. }
  1756. void DotCfgChangeReporter::handleIgnored(StringRef PassID, std::string &Name) {
  1757. assert(HTML && "Expected outstream to be set");
  1758. SmallString<20> Banner = formatv(" <a>{0}. {1} on {2} ignored</a><br/>\n", N,
  1759. makeHTMLReady(PassID), Name);
  1760. *HTML << Banner;
  1761. ++N;
  1762. }
  1763. bool DotCfgChangeReporter::initializeHTML() {
  1764. std::error_code EC;
  1765. HTML = std::make_unique<raw_fd_ostream>(DotCfgDir + "/passes.html", EC);
  1766. if (EC) {
  1767. HTML = nullptr;
  1768. return false;
  1769. }
  1770. *HTML << "<!doctype html>"
  1771. << "<html>"
  1772. << "<head>"
  1773. << "<style>.collapsible { "
  1774. << "background-color: #777;"
  1775. << " color: white;"
  1776. << " cursor: pointer;"
  1777. << " padding: 18px;"
  1778. << " width: 100%;"
  1779. << " border: none;"
  1780. << " text-align: left;"
  1781. << " outline: none;"
  1782. << " font-size: 15px;"
  1783. << "} .active, .collapsible:hover {"
  1784. << " background-color: #555;"
  1785. << "} .content {"
  1786. << " padding: 0 18px;"
  1787. << " display: none;"
  1788. << " overflow: hidden;"
  1789. << " background-color: #f1f1f1;"
  1790. << "}"
  1791. << "</style>"
  1792. << "<title>passes.html</title>"
  1793. << "</head>\n"
  1794. << "<body>";
  1795. return true;
  1796. }
  1797. DotCfgChangeReporter::~DotCfgChangeReporter() {
  1798. if (!HTML)
  1799. return;
  1800. *HTML
  1801. << "<script>var coll = document.getElementsByClassName(\"collapsible\");"
  1802. << "var i;"
  1803. << "for (i = 0; i < coll.length; i++) {"
  1804. << "coll[i].addEventListener(\"click\", function() {"
  1805. << " this.classList.toggle(\"active\");"
  1806. << " var content = this.nextElementSibling;"
  1807. << " if (content.style.display === \"block\"){"
  1808. << " content.style.display = \"none\";"
  1809. << " }"
  1810. << " else {"
  1811. << " content.style.display= \"block\";"
  1812. << " }"
  1813. << " });"
  1814. << " }"
  1815. << "</script>"
  1816. << "</body>"
  1817. << "</html>\n";
  1818. HTML->flush();
  1819. HTML->close();
  1820. }
  1821. void DotCfgChangeReporter::registerCallbacks(
  1822. PassInstrumentationCallbacks &PIC) {
  1823. if ((PrintChanged == ChangePrinter::PrintChangedDotCfgVerbose ||
  1824. PrintChanged == ChangePrinter::PrintChangedDotCfgQuiet)) {
  1825. SmallString<128> OutputDir;
  1826. sys::fs::expand_tilde(DotCfgDir, OutputDir);
  1827. sys::fs::make_absolute(OutputDir);
  1828. assert(!OutputDir.empty() && "expected output dir to be non-empty");
  1829. DotCfgDir = OutputDir.c_str();
  1830. if (initializeHTML()) {
  1831. ChangeReporter<IRDataT<DCData>>::registerRequiredCallbacks(PIC);
  1832. return;
  1833. }
  1834. dbgs() << "Unable to open output stream for -cfg-dot-changed\n";
  1835. }
  1836. }
  1837. StandardInstrumentations::StandardInstrumentations(
  1838. bool DebugLogging, bool VerifyEach, PrintPassOptions PrintPassOpts)
  1839. : PrintPass(DebugLogging, PrintPassOpts), OptNone(DebugLogging),
  1840. PrintChangedIR(PrintChanged == ChangePrinter::PrintChangedVerbose),
  1841. PrintChangedDiff(
  1842. PrintChanged == ChangePrinter::PrintChangedDiffVerbose ||
  1843. PrintChanged == ChangePrinter::PrintChangedColourDiffVerbose,
  1844. PrintChanged == ChangePrinter::PrintChangedColourDiffVerbose ||
  1845. PrintChanged == ChangePrinter::PrintChangedColourDiffQuiet),
  1846. WebsiteChangeReporter(PrintChanged ==
  1847. ChangePrinter::PrintChangedDotCfgVerbose),
  1848. Verify(DebugLogging), VerifyEach(VerifyEach) {}
  1849. void StandardInstrumentations::registerCallbacks(
  1850. PassInstrumentationCallbacks &PIC, FunctionAnalysisManager *FAM) {
  1851. PrintIR.registerCallbacks(PIC);
  1852. PrintPass.registerCallbacks(PIC);
  1853. TimePasses.registerCallbacks(PIC);
  1854. OptNone.registerCallbacks(PIC);
  1855. OptBisect.registerCallbacks(PIC);
  1856. if (FAM)
  1857. PreservedCFGChecker.registerCallbacks(PIC, *FAM);
  1858. PrintChangedIR.registerCallbacks(PIC);
  1859. PseudoProbeVerification.registerCallbacks(PIC);
  1860. if (VerifyEach)
  1861. Verify.registerCallbacks(PIC);
  1862. PrintChangedDiff.registerCallbacks(PIC);
  1863. WebsiteChangeReporter.registerCallbacks(PIC);
  1864. }
  1865. template class ChangeReporter<std::string>;
  1866. template class TextChangeReporter<std::string>;
  1867. template class BlockDataT<EmptyData>;
  1868. template class FuncDataT<EmptyData>;
  1869. template class IRDataT<EmptyData>;
  1870. template class ChangeReporter<IRDataT<EmptyData>>;
  1871. template class TextChangeReporter<IRDataT<EmptyData>>;
  1872. template class IRComparer<EmptyData>;
  1873. } // namespace llvm