1 //===- Standard pass instrumentations handling ----------------*- C++ -*--===//
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
7 //===----------------------------------------------------------------------===//
10 /// This file defines IR-printing pass instrumentation callbacks as well as
11 /// StandardInstrumentations class that manages standard pass instrumentations.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Passes/StandardInstrumentations.h"
16 #include "llvm/ADT/Any.h"
17 #include "llvm/ADT/Optional.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/Analysis/CallGraphSCCPass.h"
20 #include "llvm/Analysis/LazyCallGraph.h"
21 #include "llvm/Analysis/LoopInfo.h"
22 #include "llvm/IR/Function.h"
23 #include "llvm/IR/LegacyPassManager.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/IR/PassInstrumentation.h"
26 #include "llvm/IR/PassManager.h"
27 #include "llvm/IR/PrintPasses.h"
28 #include "llvm/IR/Verifier.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/FormatVariadic.h"
32 #include "llvm/Support/GraphWriter.h"
33 #include "llvm/Support/MemoryBuffer.h"
34 #include "llvm/Support/Program.h"
35 #include "llvm/Support/Regex.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include <unordered_map>
38 #include <unordered_set>
44 cl::opt
<bool> PreservedCFGCheckerInstrumentation::VerifyPreservedCFG(
45 "verify-cfg-preserved", cl::Hidden
,
53 // An option that prints out the IR after passes, similar to
54 // -print-after-all except that it only prints the IR after passes that
55 // change the IR. Those passes that do not make changes to the IR are
56 // reported as not making any changes. In addition, the initial IR is
57 // also reported. Other hidden options affect the output from this
58 // option. -filter-passes will limit the output to the named passes
59 // that actually change the IR and other passes are reported as filtered out.
60 // The specified passes will either be reported as making no changes (with
61 // no IR reported) or the changed IR will be reported. Also, the
62 // -filter-print-funcs and -print-module-scope options will do similar
63 // filtering based on function name, reporting changed IRs as functions(or
64 // modules if -print-module-scope is specified) for a particular function
65 // or indicating that the IR has been filtered out. The extra options
66 // can be combined, allowing only changed IRs for certain passes on certain
67 // functions to be reported in different formats, with the rest being
68 // reported as filtered out. The -print-before-changed option will print
69 // the IR as it was before each pass that changed it. The optional
70 // value of quiet will only report when the IR changes, suppressing
71 // all other messages, including the initial IR. The values "diff" and
72 // "diff-quiet" will present the changes in a form similar to a patch, in
73 // either verbose or quiet mode, respectively. The lines that are removed
74 // and added are prefixed with '-' and '+', respectively. The
75 // -filter-print-funcs and -filter-passes can be used to filter the output.
76 // This reporter relies on the linux diff utility to do comparisons and
77 // insert the prefixes. For systems that do not have the necessary
78 // facilities, the error message will be shown in place of the expected output.
80 enum class ChangePrinter
{
84 PrintChangedDiffVerbose
,
85 PrintChangedDiffQuiet
,
86 PrintChangedColourDiffVerbose
,
87 PrintChangedColourDiffQuiet
,
88 PrintChangedDotCfgVerbose
,
89 PrintChangedDotCfgQuiet
91 static cl::opt
<ChangePrinter
> PrintChanged(
92 "print-changed", cl::desc("Print changed IRs"), cl::Hidden
,
93 cl::ValueOptional
, cl::init(ChangePrinter::NoChangePrinter
),
95 clEnumValN(ChangePrinter::PrintChangedQuiet
, "quiet",
97 clEnumValN(ChangePrinter::PrintChangedDiffVerbose
, "diff",
98 "Display patch-like changes"),
99 clEnumValN(ChangePrinter::PrintChangedDiffQuiet
, "diff-quiet",
100 "Display patch-like changes in quiet mode"),
101 clEnumValN(ChangePrinter::PrintChangedColourDiffVerbose
, "cdiff",
102 "Display patch-like changes with color"),
103 clEnumValN(ChangePrinter::PrintChangedColourDiffQuiet
, "cdiff-quiet",
104 "Display patch-like changes in quiet mode with color"),
105 clEnumValN(ChangePrinter::PrintChangedDotCfgVerbose
, "dot-cfg",
106 "Create a website with graphical changes"),
107 clEnumValN(ChangePrinter::PrintChangedDotCfgQuiet
, "dot-cfg-quiet",
108 "Create a website with graphical changes in quiet mode"),
109 // Sentinel value for unspecified option.
110 clEnumValN(ChangePrinter::PrintChangedVerbose
, "", "")));
112 // An option that supports the -print-changed option. See
113 // the description for -print-changed for an explanation of the use
114 // of this option. Note that this option has no effect without -print-changed.
115 static cl::list
<std::string
>
116 PrintPassesList("filter-passes", cl::value_desc("pass names"),
117 cl::desc("Only consider IR changes for passes whose names "
118 "match for the print-changed option"),
119 cl::CommaSeparated
, cl::Hidden
);
120 // An option that supports the -print-changed option. See
121 // the description for -print-changed for an explanation of the use
122 // of this option. Note that this option has no effect without -print-changed.
124 PrintChangedBefore("print-before-changed",
125 cl::desc("Print before passes that change them"),
126 cl::init(false), cl::Hidden
);
128 // An option for specifying the diff used by print-changed=[diff | diff-quiet]
129 static cl::opt
<std::string
>
130 DiffBinary("print-changed-diff-path", cl::Hidden
, cl::init("diff"),
131 cl::desc("system diff used by change reporters"));
133 // An option for specifying the dot used by
134 // print-changed=[dot-cfg | dot-cfg-quiet]
135 static cl::opt
<std::string
>
136 DotBinary("print-changed-dot-path", cl::Hidden
, cl::init("dot"),
137 cl::desc("system dot used by change reporters"));
139 // An option that determines the colour used for elements that are only
140 // in the before part. Must be a colour named in appendix J of
141 // https://graphviz.org/pdf/dotguide.pdf
143 BeforeColour("dot-cfg-before-color",
144 cl::desc("Color for dot-cfg before elements."), cl::Hidden
,
146 // An option that determines the colour used for elements that are only
147 // in the after part. Must be a colour named in appendix J of
148 // https://graphviz.org/pdf/dotguide.pdf
149 cl::opt
<std::string
> AfterColour("dot-cfg-after-color",
150 cl::desc("Color for dot-cfg after elements."),
151 cl::Hidden
, cl::init("forestgreen"));
152 // An option that determines the colour used for elements that are in both
153 // the before and after parts. Must be a colour named in appendix J of
154 // https://graphviz.org/pdf/dotguide.pdf
156 CommonColour("dot-cfg-common-color",
157 cl::desc("Color for dot-cfg common elements."), cl::Hidden
,
160 // An option that determines where the generated website file (named
161 // passes.html) and the associated pdf files (named diff_*.pdf) are saved.
162 static cl::opt
<std::string
> DotCfgDir(
164 cl::desc("Generate dot files into specified directory for changed IRs"),
165 cl::Hidden
, cl::init("./"));
169 // Perform a system based diff between \p Before and \p After, using
170 // \p OldLineFormat, \p NewLineFormat, and \p UnchangedLineFormat
171 // to control the formatting of the output. Return an error message
172 // for any failures instead of the diff.
173 std::string
doSystemDiff(StringRef Before
, StringRef After
,
174 StringRef OldLineFormat
, StringRef NewLineFormat
,
175 StringRef UnchangedLineFormat
) {
176 StringRef SR
[2]{Before
, After
};
177 // Store the 2 bodies into temporary files and call diff on them
178 // to get the body of the node.
179 const unsigned NumFiles
= 3;
180 static std::string FileName
[NumFiles
];
181 static int FD
[NumFiles
]{-1, -1, -1};
182 for (unsigned I
= 0; I
< NumFiles
; ++I
) {
184 SmallVector
<char, 200> SV
;
186 sys::fs::createTemporaryFile("tmpdiff", "txt", FD
[I
], SV
);
188 return "Unable to create temporary file.";
189 FileName
[I
] = Twine(SV
).str();
191 // The third file is used as the result of the diff.
192 if (I
== NumFiles
- 1)
195 std::error_code EC
= sys::fs::openFileForWrite(FileName
[I
], FD
[I
]);
197 return "Unable to open temporary file for writing.";
199 raw_fd_ostream
OutStream(FD
[I
], /*shouldClose=*/true);
201 return "Error opening file for writing.";
205 static ErrorOr
<std::string
> DiffExe
= sys::findProgramByName(DiffBinary
);
207 return "Unable to find diff executable.";
209 SmallString
<128> OLF
= formatv("--old-line-format={0}", OldLineFormat
);
210 SmallString
<128> NLF
= formatv("--new-line-format={0}", NewLineFormat
);
211 SmallString
<128> ULF
=
212 formatv("--unchanged-line-format={0}", UnchangedLineFormat
);
214 StringRef Args
[] = {DiffBinary
, "-w", "-d", OLF
,
215 NLF
, ULF
, FileName
[0], FileName
[1]};
216 Optional
<StringRef
> Redirects
[] = {None
, StringRef(FileName
[2]), None
};
217 int Result
= sys::ExecuteAndWait(*DiffExe
, Args
, None
, Redirects
);
219 return "Error executing system diff.";
221 auto B
= MemoryBuffer::getFile(FileName
[2]);
223 Diff
= (*B
)->getBuffer().str();
225 return "Unable to read result.";
228 for (const std::string
&I
: FileName
) {
229 std::error_code EC
= sys::fs::remove(I
);
231 return "Unable to remove temporary file.";
236 /// Extract Module out of \p IR unit. May return nullptr if \p IR does not match
237 /// certain global filters. Will never return nullptr if \p Force is true.
238 const Module
*unwrapModule(Any IR
, bool Force
= false) {
239 if (any_isa
<const Module
*>(IR
))
240 return any_cast
<const Module
*>(IR
);
242 if (any_isa
<const Function
*>(IR
)) {
243 const Function
*F
= any_cast
<const Function
*>(IR
);
244 if (!Force
&& !isFunctionInPrintList(F
->getName()))
247 return F
->getParent();
250 if (any_isa
<const LazyCallGraph::SCC
*>(IR
)) {
251 const LazyCallGraph::SCC
*C
= any_cast
<const LazyCallGraph::SCC
*>(IR
);
252 for (const LazyCallGraph::Node
&N
: *C
) {
253 const Function
&F
= N
.getFunction();
254 if (Force
|| (!F
.isDeclaration() && isFunctionInPrintList(F
.getName()))) {
255 return F
.getParent();
258 assert(!Force
&& "Expected a module");
262 if (any_isa
<const Loop
*>(IR
)) {
263 const Loop
*L
= any_cast
<const Loop
*>(IR
);
264 const Function
*F
= L
->getHeader()->getParent();
265 if (!Force
&& !isFunctionInPrintList(F
->getName()))
267 return F
->getParent();
270 llvm_unreachable("Unknown IR unit");
273 void printIR(raw_ostream
&OS
, const Function
*F
) {
274 if (!isFunctionInPrintList(F
->getName()))
279 void printIR(raw_ostream
&OS
, const Module
*M
) {
280 if (isFunctionInPrintList("*") || forcePrintModuleIR()) {
281 M
->print(OS
, nullptr);
283 for (const auto &F
: M
->functions()) {
289 void printIR(raw_ostream
&OS
, const LazyCallGraph::SCC
*C
) {
290 for (const LazyCallGraph::Node
&N
: *C
) {
291 const Function
&F
= N
.getFunction();
292 if (!F
.isDeclaration() && isFunctionInPrintList(F
.getName())) {
298 void printIR(raw_ostream
&OS
, const Loop
*L
) {
299 const Function
*F
= L
->getHeader()->getParent();
300 if (!isFunctionInPrintList(F
->getName()))
302 printLoop(const_cast<Loop
&>(*L
), OS
);
305 std::string
getIRName(Any IR
) {
306 if (any_isa
<const Module
*>(IR
))
309 if (any_isa
<const Function
*>(IR
)) {
310 const Function
*F
= any_cast
<const Function
*>(IR
);
311 return F
->getName().str();
314 if (any_isa
<const LazyCallGraph::SCC
*>(IR
)) {
315 const LazyCallGraph::SCC
*C
= any_cast
<const LazyCallGraph::SCC
*>(IR
);
319 if (any_isa
<const Loop
*>(IR
)) {
320 const Loop
*L
= any_cast
<const Loop
*>(IR
);
322 raw_string_ostream
OS(S
);
323 L
->print(OS
, /*Verbose*/ false, /*PrintNested*/ false);
327 llvm_unreachable("Unknown wrapped IR type");
330 bool moduleContainsFilterPrintFunc(const Module
&M
) {
331 return any_of(M
.functions(),
332 [](const Function
&F
) {
333 return isFunctionInPrintList(F
.getName());
335 isFunctionInPrintList("*");
338 bool sccContainsFilterPrintFunc(const LazyCallGraph::SCC
&C
) {
340 [](const LazyCallGraph::Node
&N
) {
341 return isFunctionInPrintList(N
.getName());
343 isFunctionInPrintList("*");
346 bool shouldPrintIR(Any IR
) {
347 if (any_isa
<const Module
*>(IR
)) {
348 const Module
*M
= any_cast
<const Module
*>(IR
);
349 return moduleContainsFilterPrintFunc(*M
);
352 if (any_isa
<const Function
*>(IR
)) {
353 const Function
*F
= any_cast
<const Function
*>(IR
);
354 return isFunctionInPrintList(F
->getName());
357 if (any_isa
<const LazyCallGraph::SCC
*>(IR
)) {
358 const LazyCallGraph::SCC
*C
= any_cast
<const LazyCallGraph::SCC
*>(IR
);
359 return sccContainsFilterPrintFunc(*C
);
362 if (any_isa
<const Loop
*>(IR
)) {
363 const Loop
*L
= any_cast
<const Loop
*>(IR
);
364 return isFunctionInPrintList(L
->getHeader()->getParent()->getName());
366 llvm_unreachable("Unknown wrapped IR type");
369 /// Generic IR-printing helper that unpacks a pointer to IRUnit wrapped into
370 /// llvm::Any and does actual print job.
371 void unwrapAndPrint(raw_ostream
&OS
, Any IR
) {
372 if (!shouldPrintIR(IR
))
375 if (forcePrintModuleIR()) {
376 auto *M
= unwrapModule(IR
);
377 assert(M
&& "should have unwrapped module");
382 if (any_isa
<const Module
*>(IR
)) {
383 const Module
*M
= any_cast
<const Module
*>(IR
);
388 if (any_isa
<const Function
*>(IR
)) {
389 const Function
*F
= any_cast
<const Function
*>(IR
);
394 if (any_isa
<const LazyCallGraph::SCC
*>(IR
)) {
395 const LazyCallGraph::SCC
*C
= any_cast
<const LazyCallGraph::SCC
*>(IR
);
400 if (any_isa
<const Loop
*>(IR
)) {
401 const Loop
*L
= any_cast
<const Loop
*>(IR
);
405 llvm_unreachable("Unknown wrapped IR type");
408 // Return true when this is a pass for which changes should be ignored
409 bool isIgnored(StringRef PassID
) {
410 return isSpecialPass(PassID
,
411 {"PassManager", "PassAdaptor", "AnalysisManagerProxy",
412 "DevirtSCCRepeatedPass", "ModuleInlinerWrapperPass"});
415 std::string
makeHTMLReady(StringRef SR
) {
419 SR
.take_until([](char C
) { return C
== '<' || C
== '>'; });
420 S
.append(Clean
.str());
421 SR
= SR
.drop_front(Clean
.size());
424 S
.append(SR
[0] == '<' ? "<" : ">");
425 SR
= SR
.drop_front();
427 llvm_unreachable("problems converting string to HTML");
430 // Return the module when that is the appropriate level of comparison for \p IR.
431 const Module
*getModuleForComparison(Any IR
) {
432 if (any_isa
<const Module
*>(IR
))
433 return any_cast
<const Module
*>(IR
);
434 if (any_isa
<const LazyCallGraph::SCC
*>(IR
))
435 return any_cast
<const LazyCallGraph::SCC
*>(IR
)
444 template <typename T
> ChangeReporter
<T
>::~ChangeReporter() {
445 assert(BeforeStack
.empty() && "Problem with Change Printer stack.");
448 template <typename T
>
449 bool ChangeReporter
<T
>::isInterestingFunction(const Function
&F
) {
450 return isFunctionInPrintList(F
.getName());
453 template <typename T
>
454 bool ChangeReporter
<T
>::isInterestingPass(StringRef PassID
) {
455 if (isIgnored(PassID
))
458 static std::unordered_set
<std::string
> PrintPassNames(PrintPassesList
.begin(),
459 PrintPassesList
.end());
460 return PrintPassNames
.empty() || PrintPassNames
.count(PassID
.str());
463 // Return true when this is a pass on IR for which printing
464 // of changes is desired.
465 template <typename T
>
466 bool ChangeReporter
<T
>::isInteresting(Any IR
, StringRef PassID
) {
467 if (!isInterestingPass(PassID
))
469 if (any_isa
<const Function
*>(IR
))
470 return isInterestingFunction(*any_cast
<const Function
*>(IR
));
474 template <typename T
>
475 void ChangeReporter
<T
>::saveIRBeforePass(Any IR
, StringRef PassID
) {
476 // Always need to place something on the stack because invalidated passes
477 // are not given the IR so it cannot be determined whether the pass was for
478 // something that was filtered out.
479 BeforeStack
.emplace_back();
481 if (!isInteresting(IR
, PassID
))
483 // Is this the initial IR?
490 // Save the IR representation on the stack.
491 T
&Data
= BeforeStack
.back();
492 generateIRRepresentation(IR
, PassID
, Data
);
495 template <typename T
>
496 void ChangeReporter
<T
>::handleIRAfterPass(Any IR
, StringRef PassID
) {
497 assert(!BeforeStack
.empty() && "Unexpected empty stack encountered.");
499 std::string Name
= getIRName(IR
);
501 if (isIgnored(PassID
)) {
503 handleIgnored(PassID
, Name
);
504 } else if (!isInteresting(IR
, PassID
)) {
506 handleFiltered(PassID
, Name
);
508 // Get the before rep from the stack
509 T
&Before
= BeforeStack
.back();
510 // Create the after rep
512 generateIRRepresentation(IR
, PassID
, After
);
514 // Was there a change in IR?
515 if (Before
== After
) {
517 omitAfter(PassID
, Name
);
519 handleAfter(PassID
, Name
, Before
, After
, IR
);
521 BeforeStack
.pop_back();
524 template <typename T
>
525 void ChangeReporter
<T
>::handleInvalidatedPass(StringRef PassID
) {
526 assert(!BeforeStack
.empty() && "Unexpected empty stack encountered.");
528 // Always flag it as invalidated as we cannot determine when
529 // a pass for a filtered function is invalidated since we do not
530 // get the IR in the call. Also, the output is just alternate
531 // forms of the banner anyway.
533 handleInvalidated(PassID
);
534 BeforeStack
.pop_back();
537 template <typename T
>
538 void ChangeReporter
<T
>::registerRequiredCallbacks(
539 PassInstrumentationCallbacks
&PIC
) {
540 PIC
.registerBeforeNonSkippedPassCallback(
541 [this](StringRef P
, Any IR
) { saveIRBeforePass(IR
, P
); });
543 PIC
.registerAfterPassCallback(
544 [this](StringRef P
, Any IR
, const PreservedAnalyses
&) {
545 handleIRAfterPass(IR
, P
);
547 PIC
.registerAfterPassInvalidatedCallback(
548 [this](StringRef P
, const PreservedAnalyses
&) {
549 handleInvalidatedPass(P
);
553 template <typename T
>
554 TextChangeReporter
<T
>::TextChangeReporter(bool Verbose
)
555 : ChangeReporter
<T
>(Verbose
), Out(dbgs()) {}
557 template <typename T
> void TextChangeReporter
<T
>::handleInitialIR(Any IR
) {
558 // Always print the module.
559 // Unwrap and print directly to avoid filtering problems in general routines.
560 auto *M
= unwrapModule(IR
, /*Force=*/true);
561 assert(M
&& "Expected module to be unwrapped when forced.");
562 Out
<< "*** IR Dump At Start ***\n";
563 M
->print(Out
, nullptr);
566 template <typename T
>
567 void TextChangeReporter
<T
>::omitAfter(StringRef PassID
, std::string
&Name
) {
568 Out
<< formatv("*** IR Dump After {0} on {1} omitted because no change ***\n",
572 template <typename T
>
573 void TextChangeReporter
<T
>::handleInvalidated(StringRef PassID
) {
574 Out
<< formatv("*** IR Pass {0} invalidated ***\n", PassID
);
577 template <typename T
>
578 void TextChangeReporter
<T
>::handleFiltered(StringRef PassID
,
580 SmallString
<20> Banner
=
581 formatv("*** IR Dump After {0} on {1} filtered out ***\n", PassID
, Name
);
585 template <typename T
>
586 void TextChangeReporter
<T
>::handleIgnored(StringRef PassID
, std::string
&Name
) {
587 Out
<< formatv("*** IR Pass {0} on {1} ignored ***\n", PassID
, Name
);
590 IRChangedPrinter::~IRChangedPrinter() {}
592 void IRChangedPrinter::registerCallbacks(PassInstrumentationCallbacks
&PIC
) {
593 if (PrintChanged
== ChangePrinter::PrintChangedVerbose
||
594 PrintChanged
== ChangePrinter::PrintChangedQuiet
)
595 TextChangeReporter
<std::string
>::registerRequiredCallbacks(PIC
);
598 void IRChangedPrinter::generateIRRepresentation(Any IR
, StringRef PassID
,
599 std::string
&Output
) {
600 raw_string_ostream
OS(Output
);
601 unwrapAndPrint(OS
, IR
);
605 void IRChangedPrinter::handleAfter(StringRef PassID
, std::string
&Name
,
606 const std::string
&Before
,
607 const std::string
&After
, Any
) {
608 // Report the IR before the changes when requested.
609 if (PrintChangedBefore
)
610 Out
<< "*** IR Dump Before " << PassID
<< " on " << Name
<< " ***\n"
613 // We might not get anything to print if we only want to print a specific
614 // function but it gets deleted.
616 Out
<< "*** IR Deleted After " << PassID
<< " on " << Name
<< " ***\n";
620 Out
<< "*** IR Dump After " << PassID
<< " on " << Name
<< " ***\n" << After
;
623 template <typename T
>
624 void OrderedChangedData
<T
>::report(
625 const OrderedChangedData
&Before
, const OrderedChangedData
&After
,
626 function_ref
<void(const T
*, const T
*)> HandlePair
) {
627 const auto &BFD
= Before
.getData();
628 const auto &AFD
= After
.getData();
629 std::vector
<std::string
>::const_iterator BI
= Before
.getOrder().begin();
630 std::vector
<std::string
>::const_iterator BE
= Before
.getOrder().end();
631 std::vector
<std::string
>::const_iterator AI
= After
.getOrder().begin();
632 std::vector
<std::string
>::const_iterator AE
= After
.getOrder().end();
634 auto HandlePotentiallyRemovedData
= [&](std::string S
) {
635 // The order in LLVM may have changed so check if still exists.
637 // This has been removed.
638 HandlePair(&BFD
.find(*BI
)->getValue(), nullptr);
641 auto HandleNewData
= [&](std::vector
<const T
*> &Q
) {
642 // Print out any queued up new sections
643 for (const T
*NBI
: Q
)
644 HandlePair(nullptr, NBI
);
648 // Print out the data in the after order, with before ones interspersed
649 // appropriately (ie, somewhere near where they were in the before list).
650 // Start at the beginning of both lists. Loop through the
651 // after list. If an element is common, then advance in the before list
652 // reporting the removed ones until the common one is reached. Report any
653 // queued up new ones and then report the common one. If an element is not
654 // common, then enqueue it for reporting. When the after list is exhausted,
655 // loop through the before list, reporting any removed ones. Finally,
656 // report the rest of the enqueued new ones.
657 std::vector
<const T
*> NewDataQueue
;
659 if (!BFD
.count(*AI
)) {
660 // This section is new so place it in the queue. This will cause it
661 // to be reported after deleted sections.
662 NewDataQueue
.emplace_back(&AFD
.find(*AI
)->getValue());
666 // This section is in both; advance and print out any before-only
667 // until we get to it.
669 HandlePotentiallyRemovedData(*BI
);
672 // Report any new sections that were queued up and waiting.
673 HandleNewData(NewDataQueue
);
675 const T
&AData
= AFD
.find(*AI
)->getValue();
676 const T
&BData
= BFD
.find(*AI
)->getValue();
677 HandlePair(&BData
, &AData
);
682 // Check any remaining before sections to see if they have been removed
684 HandlePotentiallyRemovedData(*BI
);
688 HandleNewData(NewDataQueue
);
691 template <typename T
>
692 void IRComparer
<T
>::compare(
694 std::function
<void(bool InModule
, unsigned Minor
,
695 const FuncDataT
<T
> &Before
, const FuncDataT
<T
> &After
)>
697 if (!CompareModule
) {
698 // Just handle the single function.
699 assert(Before
.getData().size() == 1 && After
.getData().size() == 1 &&
700 "Expected only one function.");
701 CompareFunc(false, 0, Before
.getData().begin()->getValue(),
702 After
.getData().begin()->getValue());
707 FuncDataT
<T
> Missing("");
708 IRDataT
<T
>::report(Before
, After
,
709 [&](const FuncDataT
<T
> *B
, const FuncDataT
<T
> *A
) {
710 assert((B
|| A
) && "Both functions cannot be missing.");
715 CompareFunc(true, Minor
++, *B
, *A
);
719 template <typename T
> void IRComparer
<T
>::analyzeIR(Any IR
, IRDataT
<T
> &Data
) {
720 if (const Module
*M
= getModuleForComparison(IR
)) {
721 // Create data for each existing/interesting function in the module.
722 for (const Function
&F
: *M
)
723 generateFunctionData(Data
, F
);
727 const Function
*F
= nullptr;
728 if (any_isa
<const Function
*>(IR
))
729 F
= any_cast
<const Function
*>(IR
);
731 assert(any_isa
<const Loop
*>(IR
) && "Unknown IR unit.");
732 const Loop
*L
= any_cast
<const Loop
*>(IR
);
733 F
= L
->getHeader()->getParent();
735 assert(F
&& "Unknown IR unit.");
736 generateFunctionData(Data
, *F
);
739 template <typename T
>
740 bool IRComparer
<T
>::generateFunctionData(IRDataT
<T
> &Data
, const Function
&F
) {
741 if (!F
.isDeclaration() && isFunctionInPrintList(F
.getName())) {
742 FuncDataT
<T
> FD(F
.getEntryBlock().getName().str());
743 for (const auto &B
: F
) {
744 FD
.getOrder().emplace_back(B
.getName());
745 FD
.getData().insert({B
.getName(), B
});
747 Data
.getOrder().emplace_back(F
.getName());
748 Data
.getData().insert({F
.getName(), FD
});
754 PrintIRInstrumentation::~PrintIRInstrumentation() {
755 assert(ModuleDescStack
.empty() && "ModuleDescStack is not empty at exit");
758 void PrintIRInstrumentation::pushModuleDesc(StringRef PassID
, Any IR
) {
759 const Module
*M
= unwrapModule(IR
);
760 ModuleDescStack
.emplace_back(M
, getIRName(IR
), PassID
);
763 PrintIRInstrumentation::PrintModuleDesc
764 PrintIRInstrumentation::popModuleDesc(StringRef PassID
) {
765 assert(!ModuleDescStack
.empty() && "empty ModuleDescStack");
766 PrintModuleDesc ModuleDesc
= ModuleDescStack
.pop_back_val();
767 assert(std::get
<2>(ModuleDesc
).equals(PassID
) && "malformed ModuleDescStack");
771 void PrintIRInstrumentation::printBeforePass(StringRef PassID
, Any IR
) {
772 if (isIgnored(PassID
))
775 // Saving Module for AfterPassInvalidated operations.
776 // Note: here we rely on a fact that we do not change modules while
777 // traversing the pipeline, so the latest captured module is good
778 // for all print operations that has not happen yet.
779 if (shouldPrintAfterPass(PassID
))
780 pushModuleDesc(PassID
, IR
);
782 if (!shouldPrintBeforePass(PassID
))
785 if (!shouldPrintIR(IR
))
788 dbgs() << "*** IR Dump Before " << PassID
<< " on " << getIRName(IR
)
790 unwrapAndPrint(dbgs(), IR
);
793 void PrintIRInstrumentation::printAfterPass(StringRef PassID
, Any IR
) {
794 if (isIgnored(PassID
))
797 if (!shouldPrintAfterPass(PassID
))
802 StringRef StoredPassID
;
803 std::tie(M
, IRName
, StoredPassID
) = popModuleDesc(PassID
);
804 assert(StoredPassID
== PassID
&& "mismatched PassID");
806 if (!shouldPrintIR(IR
))
809 dbgs() << "*** IR Dump After " << PassID
<< " on " << IRName
<< " ***\n";
810 unwrapAndPrint(dbgs(), IR
);
813 void PrintIRInstrumentation::printAfterPassInvalidated(StringRef PassID
) {
814 StringRef PassName
= PIC
->getPassNameForClassName(PassID
);
815 if (!shouldPrintAfterPass(PassName
))
818 if (isIgnored(PassID
))
823 StringRef StoredPassID
;
824 std::tie(M
, IRName
, StoredPassID
) = popModuleDesc(PassID
);
825 assert(StoredPassID
== PassID
&& "mismatched PassID");
826 // Additional filtering (e.g. -filter-print-func) can lead to module
827 // printing being skipped.
831 SmallString
<20> Banner
=
832 formatv("*** IR Dump After {0} on {1} (invalidated) ***", PassID
, IRName
);
833 dbgs() << Banner
<< "\n";
837 bool PrintIRInstrumentation::shouldPrintBeforePass(StringRef PassID
) {
838 if (shouldPrintBeforeAll())
841 StringRef PassName
= PIC
->getPassNameForClassName(PassID
);
842 return is_contained(printBeforePasses(), PassName
);
845 bool PrintIRInstrumentation::shouldPrintAfterPass(StringRef PassID
) {
846 if (shouldPrintAfterAll())
849 StringRef PassName
= PIC
->getPassNameForClassName(PassID
);
850 return is_contained(printAfterPasses(), PassName
);
853 void PrintIRInstrumentation::registerCallbacks(
854 PassInstrumentationCallbacks
&PIC
) {
857 // BeforePass callback is not just for printing, it also saves a Module
858 // for later use in AfterPassInvalidated.
859 if (shouldPrintBeforeSomePass() || shouldPrintAfterSomePass())
860 PIC
.registerBeforeNonSkippedPassCallback(
861 [this](StringRef P
, Any IR
) { this->printBeforePass(P
, IR
); });
863 if (shouldPrintAfterSomePass()) {
864 PIC
.registerAfterPassCallback(
865 [this](StringRef P
, Any IR
, const PreservedAnalyses
&) {
866 this->printAfterPass(P
, IR
);
868 PIC
.registerAfterPassInvalidatedCallback(
869 [this](StringRef P
, const PreservedAnalyses
&) {
870 this->printAfterPassInvalidated(P
);
875 void OptNoneInstrumentation::registerCallbacks(
876 PassInstrumentationCallbacks
&PIC
) {
877 PIC
.registerShouldRunOptionalPassCallback(
878 [this](StringRef P
, Any IR
) { return this->shouldRun(P
, IR
); });
881 bool OptNoneInstrumentation::shouldRun(StringRef PassID
, Any IR
) {
882 const Function
*F
= nullptr;
883 if (any_isa
<const Function
*>(IR
)) {
884 F
= any_cast
<const Function
*>(IR
);
885 } else if (any_isa
<const Loop
*>(IR
)) {
886 F
= any_cast
<const Loop
*>(IR
)->getHeader()->getParent();
888 bool ShouldRun
= !(F
&& F
->hasOptNone());
889 if (!ShouldRun
&& DebugLogging
) {
890 errs() << "Skipping pass " << PassID
<< " on " << F
->getName()
891 << " due to optnone attribute\n";
896 void OptBisectInstrumentation::registerCallbacks(
897 PassInstrumentationCallbacks
&PIC
) {
898 if (!OptBisector
->isEnabled())
900 PIC
.registerShouldRunOptionalPassCallback([](StringRef PassID
, Any IR
) {
901 return isIgnored(PassID
) || OptBisector
->checkPass(PassID
, getIRName(IR
));
905 raw_ostream
&PrintPassInstrumentation::print() {
908 dbgs().indent(Indent
);
913 void PrintPassInstrumentation::registerCallbacks(
914 PassInstrumentationCallbacks
&PIC
) {
918 std::vector
<StringRef
> SpecialPasses
;
920 SpecialPasses
.emplace_back("PassManager");
921 SpecialPasses
.emplace_back("PassAdaptor");
924 PIC
.registerBeforeSkippedPassCallback([this, SpecialPasses
](StringRef PassID
,
926 assert(!isSpecialPass(PassID
, SpecialPasses
) &&
927 "Unexpectedly skipping special pass");
929 print() << "Skipping pass: " << PassID
<< " on " << getIRName(IR
) << "\n";
931 PIC
.registerBeforeNonSkippedPassCallback([this, SpecialPasses
](
932 StringRef PassID
, Any IR
) {
933 if (isSpecialPass(PassID
, SpecialPasses
))
936 print() << "Running pass: " << PassID
<< " on " << getIRName(IR
) << "\n";
939 PIC
.registerAfterPassCallback(
940 [this, SpecialPasses
](StringRef PassID
, Any IR
,
941 const PreservedAnalyses
&) {
942 if (isSpecialPass(PassID
, SpecialPasses
))
947 PIC
.registerAfterPassInvalidatedCallback(
948 [this, SpecialPasses
](StringRef PassID
, Any IR
) {
949 if (isSpecialPass(PassID
, SpecialPasses
))
955 if (!Opts
.SkipAnalyses
) {
956 PIC
.registerBeforeAnalysisCallback([this](StringRef PassID
, Any IR
) {
957 print() << "Running analysis: " << PassID
<< " on " << getIRName(IR
)
961 PIC
.registerAfterAnalysisCallback(
962 [this](StringRef PassID
, Any IR
) { Indent
-= 2; });
963 PIC
.registerAnalysisInvalidatedCallback([this](StringRef PassID
, Any IR
) {
964 print() << "Invalidating analysis: " << PassID
<< " on " << getIRName(IR
)
967 PIC
.registerAnalysesClearedCallback([this](StringRef IRName
) {
968 print() << "Clearing all analysis results for: " << IRName
<< "\n";
973 PreservedCFGCheckerInstrumentation::CFG::CFG(const Function
*F
,
974 bool TrackBBLifetime
) {
976 BBGuards
= DenseMap
<intptr_t, BBGuard
>(F
->size());
977 for (const auto &BB
: *F
) {
979 BBGuards
->try_emplace(intptr_t(&BB
), &BB
);
980 for (auto *Succ
: successors(&BB
)) {
983 BBGuards
->try_emplace(intptr_t(Succ
), Succ
);
988 static void printBBName(raw_ostream
&out
, const BasicBlock
*BB
) {
990 out
<< BB
->getName() << "<" << BB
<< ">";
994 if (!BB
->getParent()) {
995 out
<< "unnamed_removed<" << BB
<< ">";
999 if (BB
->isEntryBlock()) {
1001 << "<" << BB
<< ">";
1005 unsigned FuncOrderBlockNum
= 0;
1006 for (auto &FuncBB
: *BB
->getParent()) {
1009 FuncOrderBlockNum
++;
1011 out
<< "unnamed_" << FuncOrderBlockNum
<< "<" << BB
<< ">";
1014 void PreservedCFGCheckerInstrumentation::CFG::printDiff(raw_ostream
&out
,
1017 assert(!After
.isPoisoned());
1018 if (Before
.isPoisoned()) {
1019 out
<< "Some blocks were deleted\n";
1023 // Find and print graph differences.
1024 if (Before
.Graph
.size() != After
.Graph
.size())
1025 out
<< "Different number of non-leaf basic blocks: before="
1026 << Before
.Graph
.size() << ", after=" << After
.Graph
.size() << "\n";
1028 for (auto &BB
: Before
.Graph
) {
1029 auto BA
= After
.Graph
.find(BB
.first
);
1030 if (BA
== After
.Graph
.end()) {
1031 out
<< "Non-leaf block ";
1032 printBBName(out
, BB
.first
);
1033 out
<< " is removed (" << BB
.second
.size() << " successors)\n";
1037 for (auto &BA
: After
.Graph
) {
1038 auto BB
= Before
.Graph
.find(BA
.first
);
1039 if (BB
== Before
.Graph
.end()) {
1040 out
<< "Non-leaf block ";
1041 printBBName(out
, BA
.first
);
1042 out
<< " is added (" << BA
.second
.size() << " successors)\n";
1046 if (BB
->second
== BA
.second
)
1049 out
<< "Different successors of block ";
1050 printBBName(out
, BA
.first
);
1051 out
<< " (unordered):\n";
1052 out
<< "- before (" << BB
->second
.size() << "): ";
1053 for (auto &SuccB
: BB
->second
) {
1054 printBBName(out
, SuccB
.first
);
1055 if (SuccB
.second
!= 1)
1056 out
<< "(" << SuccB
.second
<< "), ";
1061 out
<< "- after (" << BA
.second
.size() << "): ";
1062 for (auto &SuccA
: BA
.second
) {
1063 printBBName(out
, SuccA
.first
);
1064 if (SuccA
.second
!= 1)
1065 out
<< "(" << SuccA
.second
<< "), ";
1073 // PreservedCFGCheckerInstrumentation uses PreservedCFGCheckerAnalysis to check
1074 // passes, that reported they kept CFG analyses up-to-date, did not actually
1075 // change CFG. This check is done as follows. Before every functional pass in
1076 // BeforeNonSkippedPassCallback a CFG snapshot (an instance of
1077 // PreservedCFGCheckerInstrumentation::CFG) is requested from
1078 // FunctionAnalysisManager as a result of PreservedCFGCheckerAnalysis. When the
1079 // functional pass finishes and reports that CFGAnalyses or AllAnalyses are
1080 // up-to-date then the cached result of PreservedCFGCheckerAnalysis (if
1081 // available) is checked to be equal to a freshly created CFG snapshot.
1082 struct PreservedCFGCheckerAnalysis
1083 : public AnalysisInfoMixin
<PreservedCFGCheckerAnalysis
> {
1084 friend AnalysisInfoMixin
<PreservedCFGCheckerAnalysis
>;
1086 static AnalysisKey Key
;
1089 /// Provide the result type for this analysis pass.
1090 using Result
= PreservedCFGCheckerInstrumentation::CFG
;
1092 /// Run the analysis pass over a function and produce CFG.
1093 Result
run(Function
&F
, FunctionAnalysisManager
&FAM
) {
1094 return Result(&F
, /* TrackBBLifetime */ true);
1098 AnalysisKey
PreservedCFGCheckerAnalysis::Key
;
1100 bool PreservedCFGCheckerInstrumentation::CFG::invalidate(
1101 Function
&F
, const PreservedAnalyses
&PA
,
1102 FunctionAnalysisManager::Invalidator
&) {
1103 auto PAC
= PA
.getChecker
<PreservedCFGCheckerAnalysis
>();
1104 return !(PAC
.preserved() || PAC
.preservedSet
<AllAnalysesOn
<Function
>>() ||
1105 PAC
.preservedSet
<CFGAnalyses
>());
1108 void PreservedCFGCheckerInstrumentation::registerCallbacks(
1109 PassInstrumentationCallbacks
&PIC
, FunctionAnalysisManager
&FAM
) {
1110 if (!VerifyPreservedCFG
)
1113 FAM
.registerPass([&] { return PreservedCFGCheckerAnalysis(); });
1115 auto checkCFG
= [](StringRef Pass
, StringRef FuncName
, const CFG
&GraphBefore
,
1116 const CFG
&GraphAfter
) {
1117 if (GraphAfter
== GraphBefore
)
1120 dbgs() << "Error: " << Pass
1121 << " does not invalidate CFG analyses but CFG changes detected in "
1123 << FuncName
<< ":\n";
1124 CFG::printDiff(dbgs(), GraphBefore
, GraphAfter
);
1125 report_fatal_error(Twine("CFG unexpectedly changed by ", Pass
));
1128 PIC
.registerBeforeNonSkippedPassCallback([this, &FAM
](StringRef P
, Any IR
) {
1129 #ifdef LLVM_ENABLE_ABI_BREAKING_CHECKS
1130 assert(&PassStack
.emplace_back(P
));
1133 if (!any_isa
<const Function
*>(IR
))
1136 const auto *F
= any_cast
<const Function
*>(IR
);
1137 // Make sure a fresh CFG snapshot is available before the pass.
1138 FAM
.getResult
<PreservedCFGCheckerAnalysis
>(*const_cast<Function
*>(F
));
1141 PIC
.registerAfterPassInvalidatedCallback(
1142 [this](StringRef P
, const PreservedAnalyses
&PassPA
) {
1143 #ifdef LLVM_ENABLE_ABI_BREAKING_CHECKS
1144 assert(PassStack
.pop_back_val() == P
&&
1145 "Before and After callbacks must correspond");
1150 PIC
.registerAfterPassCallback([this, &FAM
,
1151 checkCFG
](StringRef P
, Any IR
,
1152 const PreservedAnalyses
&PassPA
) {
1153 #ifdef LLVM_ENABLE_ABI_BREAKING_CHECKS
1154 assert(PassStack
.pop_back_val() == P
&&
1155 "Before and After callbacks must correspond");
1159 if (!any_isa
<const Function
*>(IR
))
1162 if (!PassPA
.allAnalysesInSetPreserved
<CFGAnalyses
>() &&
1163 !PassPA
.allAnalysesInSetPreserved
<AllAnalysesOn
<Function
>>())
1166 const auto *F
= any_cast
<const Function
*>(IR
);
1167 if (auto *GraphBefore
= FAM
.getCachedResult
<PreservedCFGCheckerAnalysis
>(
1168 *const_cast<Function
*>(F
)))
1169 checkCFG(P
, F
->getName(), *GraphBefore
,
1170 CFG(F
, /* TrackBBLifetime */ false));
1174 void VerifyInstrumentation::registerCallbacks(
1175 PassInstrumentationCallbacks
&PIC
) {
1176 PIC
.registerAfterPassCallback(
1177 [this](StringRef P
, Any IR
, const PreservedAnalyses
&PassPA
) {
1178 if (isIgnored(P
) || P
== "VerifierPass")
1180 if (any_isa
<const Function
*>(IR
) || any_isa
<const Loop
*>(IR
)) {
1182 if (any_isa
<const Loop
*>(IR
))
1183 F
= any_cast
<const Loop
*>(IR
)->getHeader()->getParent();
1185 F
= any_cast
<const Function
*>(IR
);
1187 dbgs() << "Verifying function " << F
->getName() << "\n";
1189 if (verifyFunction(*F
))
1190 report_fatal_error("Broken function found, compilation aborted!");
1191 } else if (any_isa
<const Module
*>(IR
) ||
1192 any_isa
<const LazyCallGraph::SCC
*>(IR
)) {
1194 if (any_isa
<const LazyCallGraph::SCC
*>(IR
))
1195 M
= any_cast
<const LazyCallGraph::SCC
*>(IR
)
1200 M
= any_cast
<const Module
*>(IR
);
1202 dbgs() << "Verifying module " << M
->getName() << "\n";
1204 if (verifyModule(*M
))
1205 report_fatal_error("Broken module found, compilation aborted!");
1210 InLineChangePrinter::~InLineChangePrinter() {}
1212 void InLineChangePrinter::generateIRRepresentation(Any IR
, StringRef PassID
,
1213 IRDataT
<EmptyData
> &D
) {
1214 IRComparer
<EmptyData
>::analyzeIR(IR
, D
);
1217 void InLineChangePrinter::handleAfter(StringRef PassID
, std::string
&Name
,
1218 const IRDataT
<EmptyData
> &Before
,
1219 const IRDataT
<EmptyData
> &After
, Any IR
) {
1220 SmallString
<20> Banner
=
1221 formatv("*** IR Dump After {0} on {1} ***\n", PassID
, Name
);
1223 IRComparer
<EmptyData
>(Before
, After
)
1224 .compare(getModuleForComparison(IR
),
1225 [&](bool InModule
, unsigned Minor
,
1226 const FuncDataT
<EmptyData
> &Before
,
1227 const FuncDataT
<EmptyData
> &After
) -> void {
1228 handleFunctionCompare(Name
, "", PassID
, " on ", InModule
,
1229 Minor
, Before
, After
);
1234 void InLineChangePrinter::handleFunctionCompare(
1235 StringRef Name
, StringRef Prefix
, StringRef PassID
, StringRef Divider
,
1236 bool InModule
, unsigned Minor
, const FuncDataT
<EmptyData
> &Before
,
1237 const FuncDataT
<EmptyData
> &After
) {
1238 // Print a banner when this is being shown in the context of a module
1240 Out
<< "\n*** IR for function " << Name
<< " ***\n";
1242 FuncDataT
<EmptyData
>::report(
1244 [&](const BlockDataT
<EmptyData
> *B
, const BlockDataT
<EmptyData
> *A
) {
1245 StringRef BStr
= B
? B
->getBody() : "\n";
1246 StringRef AStr
= A
? A
->getBody() : "\n";
1247 const std::string Removed
=
1248 UseColour
? "\033[31m-%l\033[0m\n" : "-%l\n";
1249 const std::string Added
= UseColour
? "\033[32m+%l\033[0m\n" : "+%l\n";
1250 const std::string NoChange
= " %l\n";
1251 Out
<< doSystemDiff(BStr
, AStr
, Removed
, Added
, NoChange
);
1255 void InLineChangePrinter::registerCallbacks(PassInstrumentationCallbacks
&PIC
) {
1256 if (PrintChanged
== ChangePrinter::PrintChangedDiffVerbose
||
1257 PrintChanged
== ChangePrinter::PrintChangedDiffQuiet
||
1258 PrintChanged
== ChangePrinter::PrintChangedColourDiffVerbose
||
1259 PrintChanged
== ChangePrinter::PrintChangedColourDiffQuiet
)
1260 TextChangeReporter
<IRDataT
<EmptyData
>>::registerRequiredCallbacks(PIC
);
1266 class DotCfgDiffDisplayGraph
;
1268 // Base class for a node or edge in the dot-cfg-changes graph.
1269 class DisplayElement
{
1271 // Is this in before, after, or both?
1272 StringRef
getColour() const { return Colour
; }
1275 DisplayElement(StringRef Colour
) : Colour(Colour
) {}
1276 const StringRef Colour
;
1279 // An edge representing a transition between basic blocks in the
1280 // dot-cfg-changes graph.
1281 class DisplayEdge
: public DisplayElement
{
1283 DisplayEdge(std::string Value
, DisplayNode
&Node
, StringRef Colour
)
1284 : DisplayElement(Colour
), Value(Value
), Node(Node
) {}
1285 // The value on which the transition is made.
1286 std::string
getValue() const { return Value
; }
1287 // The node (representing a basic block) reached by this transition.
1288 const DisplayNode
&getDestinationNode() const { return Node
; }
1292 const DisplayNode
&Node
;
1295 // A node in the dot-cfg-changes graph which represents a basic block.
1296 class DisplayNode
: public DisplayElement
{
1298 // \p C is the content for the node, \p T indicates the colour for the
1299 // outline of the node
1300 DisplayNode(std::string Content
, StringRef Colour
)
1301 : DisplayElement(Colour
), Content(Content
) {}
1303 // Iterator to the child nodes. Required by GraphWriter.
1304 using ChildIterator
= std::unordered_set
<DisplayNode
*>::const_iterator
;
1305 ChildIterator
children_begin() const { return Children
.cbegin(); }
1306 ChildIterator
children_end() const { return Children
.cend(); }
1308 // Iterator for the edges. Required by GraphWriter.
1309 using EdgeIterator
= std::vector
<DisplayEdge
*>::const_iterator
;
1310 EdgeIterator
edges_begin() const { return EdgePtrs
.cbegin(); }
1311 EdgeIterator
edges_end() const { return EdgePtrs
.cend(); }
1313 // Create an edge to \p Node on value \p Value, with colour \p Colour.
1314 void createEdge(StringRef Value
, DisplayNode
&Node
, StringRef Colour
);
1316 // Return the content of this node.
1317 std::string
getContent() const { return Content
; }
1319 // Return the edge to node \p S.
1320 const DisplayEdge
&getEdge(const DisplayNode
&To
) const {
1321 assert(EdgeMap
.find(&To
) != EdgeMap
.end() && "Expected to find edge.");
1322 return *EdgeMap
.find(&To
)->second
;
1325 // Return the value for the transition to basic block \p S.
1326 // Required by GraphWriter.
1327 std::string
getEdgeSourceLabel(const DisplayNode
&Sink
) const {
1328 return getEdge(Sink
).getValue();
1331 void createEdgeMap();
1334 const std::string Content
;
1336 // Place to collect all of the edges. Once they are all in the vector,
1337 // the vector will not reallocate so then we can use pointers to them,
1338 // which are required by the graph writing routines.
1339 std::vector
<DisplayEdge
> Edges
;
1341 std::vector
<DisplayEdge
*> EdgePtrs
;
1342 std::unordered_set
<DisplayNode
*> Children
;
1343 std::unordered_map
<const DisplayNode
*, const DisplayEdge
*> EdgeMap
;
1345 // Safeguard adding of edges.
1346 bool AllEdgesCreated
= false;
1349 // Class representing a difference display (corresponds to a pdf file).
1350 class DotCfgDiffDisplayGraph
{
1352 DotCfgDiffDisplayGraph(std::string Name
) : GraphName(Name
) {}
1354 // Generate the file into \p DotFile.
1355 void generateDotFile(StringRef DotFile
);
1357 // Iterator to the nodes. Required by GraphWriter.
1358 using NodeIterator
= std::vector
<DisplayNode
*>::const_iterator
;
1359 NodeIterator
nodes_begin() const {
1360 assert(NodeGenerationComplete
&& "Unexpected children iterator creation");
1361 return NodePtrs
.cbegin();
1363 NodeIterator
nodes_end() const {
1364 assert(NodeGenerationComplete
&& "Unexpected children iterator creation");
1365 return NodePtrs
.cend();
1368 // Record the index of the entry node. At this point, we can build up
1369 // vectors of pointers that are required by the graph routines.
1370 void setEntryNode(unsigned N
) {
1371 // At this point, there will be no new nodes.
1372 assert(!NodeGenerationComplete
&& "Unexpected node creation");
1373 NodeGenerationComplete
= true;
1374 for (auto &N
: Nodes
)
1375 NodePtrs
.emplace_back(&N
);
1377 EntryNode
= NodePtrs
[N
];
1381 void createNode(std::string C
, StringRef Colour
) {
1382 assert(!NodeGenerationComplete
&& "Unexpected node creation");
1383 Nodes
.emplace_back(C
, Colour
);
1385 // Return the node at index \p N to avoid problems with vectors reallocating.
1386 DisplayNode
&getNode(unsigned N
) {
1387 assert(N
< Nodes
.size() && "Node is out of bounds");
1390 unsigned size() const {
1391 assert(NodeGenerationComplete
&& "Unexpected children iterator creation");
1392 return Nodes
.size();
1395 // Return the name of the graph. Required by GraphWriter.
1396 std::string
getGraphName() const { return GraphName
; }
1398 // Return the string representing the differences for basic block \p Node.
1399 // Required by GraphWriter.
1400 std::string
getNodeLabel(const DisplayNode
&Node
) const {
1401 return Node
.getContent();
1404 // Return a string with colour information for Dot. Required by GraphWriter.
1405 std::string
getNodeAttributes(const DisplayNode
&Node
) const {
1406 return attribute(Node
.getColour());
1409 // Return a string with colour information for Dot. Required by GraphWriter.
1410 std::string
getEdgeColorAttr(const DisplayNode
&From
,
1411 const DisplayNode
&To
) const {
1412 return attribute(From
.getEdge(To
).getColour());
1415 // Get the starting basic block. Required by GraphWriter.
1416 DisplayNode
*getEntryNode() const {
1417 assert(NodeGenerationComplete
&& "Unexpected children iterator creation");
1422 // Return the string containing the colour to use as a Dot attribute.
1423 std::string
attribute(StringRef Colour
) const {
1424 return "color=" + Colour
.str();
1427 bool NodeGenerationComplete
= false;
1428 const std::string GraphName
;
1429 std::vector
<DisplayNode
> Nodes
;
1430 std::vector
<DisplayNode
*> NodePtrs
;
1431 DisplayNode
*EntryNode
= nullptr;
1434 void DisplayNode::createEdge(StringRef Value
, DisplayNode
&Node
,
1436 assert(!AllEdgesCreated
&& "Expected to be able to still create edges.");
1437 Edges
.emplace_back(Value
.str(), Node
, Colour
);
1438 Children
.insert(&Node
);
1441 void DisplayNode::createEdgeMap() {
1442 // No more edges will be added so we can now use pointers to the edges
1443 // as the vector will not grow and reallocate.
1444 AllEdgesCreated
= true;
1445 for (auto &E
: Edges
)
1446 EdgeMap
.insert({&E
.getDestinationNode(), &E
});
1449 class DotCfgDiffNode
;
1452 // A class representing a basic block in the Dot difference graph.
1453 class DotCfgDiffNode
{
1455 DotCfgDiffNode() = delete;
1457 // Create a node in Dot difference graph \p G representing the basic block
1458 // represented by \p BD with colour \p Colour (where it exists).
1459 DotCfgDiffNode(DotCfgDiff
&G
, unsigned N
, const BlockDataT
<DCData
> &BD
,
1461 : Graph(G
), N(N
), Data
{&BD
, nullptr}, Colour(Colour
) {}
1462 DotCfgDiffNode(const DotCfgDiffNode
&DN
)
1463 : Graph(DN
.Graph
), N(DN
.N
), Data
{DN
.Data
[0], DN
.Data
[1]},
1464 Colour(DN
.Colour
), EdgesMap(DN
.EdgesMap
), Children(DN
.Children
),
1467 unsigned getIndex() const { return N
; }
1469 // The label of the basic block
1470 StringRef
getLabel() const {
1471 assert(Data
[0] && "Expected Data[0] to be set.");
1472 return Data
[0]->getLabel();
1474 // Return the colour for this block
1475 StringRef
getColour() const { return Colour
; }
1476 // Change this basic block from being only in before to being common.
1477 // Save the pointer to \p Other.
1478 void setCommon(const BlockDataT
<DCData
> &Other
) {
1479 assert(!Data
[1] && "Expected only one block datum");
1481 Colour
= CommonColour
;
1483 // Add an edge to \p E of colour {\p Value, \p Colour}.
1484 void addEdge(unsigned E
, StringRef Value
, StringRef Colour
) {
1485 // This is a new edge or it is an edge being made common.
1486 assert((EdgesMap
.count(E
) == 0 || Colour
== CommonColour
) &&
1487 "Unexpected edge count and color.");
1488 EdgesMap
[E
] = {Value
.str(), Colour
};
1490 // Record the children and create edges.
1491 void finalize(DotCfgDiff
&G
);
1493 // Return the colour of the edge to node \p S.
1494 StringRef
getEdgeColour(const unsigned S
) const {
1495 assert(EdgesMap
.count(S
) == 1 && "Expected to find edge.");
1496 return EdgesMap
.at(S
).second
;
1499 // Return the string representing the basic block.
1500 std::string
getBodyContent() const;
1502 void createDisplayEdges(DotCfgDiffDisplayGraph
&Graph
, unsigned DisplayNode
,
1503 std::map
<const unsigned, unsigned> &NodeMap
) const;
1508 const BlockDataT
<DCData
> *Data
[2];
1510 std::map
<const unsigned, std::pair
<std::string
, StringRef
>> EdgesMap
;
1511 std::vector
<unsigned> Children
;
1512 std::vector
<unsigned> Edges
;
1515 // Class representing the difference graph between two functions.
1518 // \p Title is the title given to the graph. \p EntryNodeName is the
1519 // entry node for the function. \p Before and \p After are the before
1520 // after versions of the function, respectively. \p Dir is the directory
1521 // in which to store the results.
1522 DotCfgDiff(StringRef Title
, const FuncDataT
<DCData
> &Before
,
1523 const FuncDataT
<DCData
> &After
);
1525 DotCfgDiff(const DotCfgDiff
&) = delete;
1526 DotCfgDiff
&operator=(const DotCfgDiff
&) = delete;
1528 DotCfgDiffDisplayGraph
createDisplayGraph(StringRef Title
,
1529 StringRef EntryNodeName
);
1531 // Return a string consisting of the labels for the \p Source and \p Sink.
1532 // The combination allows distinguishing changing transitions on the
1533 // same value (ie, a transition went to X before and goes to Y after).
1534 // Required by GraphWriter.
1535 StringRef
getEdgeSourceLabel(const unsigned &Source
,
1536 const unsigned &Sink
) const {
1538 getNode(Source
).getLabel().str() + " " + getNode(Sink
).getLabel().str();
1539 assert(EdgeLabels
.count(S
) == 1 && "Expected to find edge label.");
1540 return EdgeLabels
.find(S
)->getValue();
1543 // Return the number of basic blocks (nodes). Required by GraphWriter.
1544 unsigned size() const { return Nodes
.size(); }
1546 const DotCfgDiffNode
&getNode(unsigned N
) const {
1547 assert(N
< Nodes
.size() && "Unexpected index for node reference");
1552 // Return the string surrounded by HTML to make it the appropriate colour.
1553 std::string
colourize(std::string S
, StringRef Colour
) const;
1555 void createNode(StringRef Label
, const BlockDataT
<DCData
> &BD
, StringRef C
) {
1556 unsigned Pos
= Nodes
.size();
1557 Nodes
.emplace_back(*this, Pos
, BD
, C
);
1558 NodePosition
.insert({Label
, Pos
});
1561 // TODO Nodes should probably be a StringMap<DotCfgDiffNode> after the
1562 // display graph is separated out, which would remove the need for
1564 std::vector
<DotCfgDiffNode
> Nodes
;
1565 StringMap
<unsigned> NodePosition
;
1566 const std::string GraphName
;
1568 StringMap
<std::string
> EdgeLabels
;
1571 std::string
DotCfgDiffNode::getBodyContent() const {
1572 if (Colour
== CommonColour
) {
1573 assert(Data
[1] && "Expected Data[1] to be set.");
1576 for (unsigned I
= 0; I
< 2; ++I
) {
1577 SR
[I
] = Data
[I
]->getBody();
1578 // drop initial '\n' if present
1579 if (SR
[I
][0] == '\n')
1580 SR
[I
] = SR
[I
].drop_front();
1581 // drop predecessors as they can be big and are redundant
1582 SR
[I
] = SR
[I
].drop_until([](char C
) { return C
== '\n'; }).drop_front();
1585 SmallString
<80> OldLineFormat
= formatv(
1586 "<FONT COLOR=\"{0}\">%l</FONT><BR align=\"left\"/>", BeforeColour
);
1587 SmallString
<80> NewLineFormat
= formatv(
1588 "<FONT COLOR=\"{0}\">%l</FONT><BR align=\"left\"/>", AfterColour
);
1589 SmallString
<80> UnchangedLineFormat
= formatv(
1590 "<FONT COLOR=\"{0}\">%l</FONT><BR align=\"left\"/>", CommonColour
);
1591 std::string Diff
= Data
[0]->getLabel().str();
1592 Diff
+= ":\n<BR align=\"left\"/>" +
1593 doSystemDiff(makeHTMLReady(SR
[0]), makeHTMLReady(SR
[1]),
1594 OldLineFormat
, NewLineFormat
, UnchangedLineFormat
);
1596 // Diff adds in some empty colour changes which are not valid HTML
1597 // so remove them. Colours are all lowercase alpha characters (as
1598 // listed in https://graphviz.org/pdf/dotguide.pdf).
1599 Regex
R("<FONT COLOR=\"\\w+\"></FONT>");
1602 std::string S
= R
.sub("", Diff
, &Error
);
1609 llvm_unreachable("Should not get here");
1612 // Put node out in the appropriate colour.
1613 assert(!Data
[1] && "Data[1] is set unexpectedly.");
1614 std::string Body
= makeHTMLReady(Data
[0]->getBody());
1615 const StringRef BS
= Body
;
1617 // Drop leading newline, if present.
1618 if (BS
.front() == '\n')
1619 BS1
= BS1
.drop_front(1);
1621 StringRef Label
= BS1
.take_until([](char C
) { return C
== ':'; });
1622 // drop predecessors as they can be big and are redundant
1623 BS1
= BS1
.drop_until([](char C
) { return C
== '\n'; }).drop_front();
1625 std::string S
= "<FONT COLOR=\"" + Colour
.str() + "\">" + Label
.str() + ":";
1627 // align each line to the left.
1628 while (BS1
.size()) {
1629 S
.append("<BR align=\"left\"/>");
1630 StringRef Line
= BS1
.take_until([](char C
) { return C
== '\n'; });
1631 S
.append(Line
.str());
1632 BS1
= BS1
.drop_front(Line
.size() + 1);
1634 S
.append("<BR align=\"left\"/></FONT>");
1638 std::string
DotCfgDiff::colourize(std::string S
, StringRef Colour
) const {
1639 if (S
.length() == 0)
1641 return "<FONT COLOR=\"" + Colour
.str() + "\">" + S
+ "</FONT>";
1644 DotCfgDiff::DotCfgDiff(StringRef Title
, const FuncDataT
<DCData
> &Before
,
1645 const FuncDataT
<DCData
> &After
)
1646 : GraphName(Title
.str()) {
1647 StringMap
<StringRef
> EdgesMap
;
1649 // Handle each basic block in the before IR.
1650 for (auto &B
: Before
.getData()) {
1651 StringRef Label
= B
.getKey();
1652 const BlockDataT
<DCData
> &BD
= B
.getValue();
1653 createNode(Label
, BD
, BeforeColour
);
1655 // Create transitions with names made up of the from block label, the value
1656 // on which the transition is made and the to block label.
1657 for (StringMap
<std::string
>::const_iterator Sink
= BD
.getData().begin(),
1658 E
= BD
.getData().end();
1659 Sink
!= E
; ++Sink
) {
1660 std::string Key
= (Label
+ " " + Sink
->getKey().str()).str() + " " +
1661 BD
.getData().getSuccessorLabel(Sink
->getKey()).str();
1662 EdgesMap
.insert({Key
, BeforeColour
});
1666 // Handle each basic block in the after IR
1667 for (auto &A
: After
.getData()) {
1668 StringRef Label
= A
.getKey();
1669 const BlockDataT
<DCData
> &BD
= A
.getValue();
1670 unsigned C
= NodePosition
.count(Label
);
1672 // This only exists in the after IR. Create the node.
1673 createNode(Label
, BD
, AfterColour
);
1675 assert(C
== 1 && "Unexpected multiple nodes.");
1676 Nodes
[NodePosition
[Label
]].setCommon(BD
);
1678 // Add in the edges between the nodes (as common or only in after).
1679 for (StringMap
<std::string
>::const_iterator Sink
= BD
.getData().begin(),
1680 E
= BD
.getData().end();
1681 Sink
!= E
; ++Sink
) {
1682 std::string Key
= (Label
+ " " + Sink
->getKey().str()).str() + " " +
1683 BD
.getData().getSuccessorLabel(Sink
->getKey()).str();
1684 unsigned C
= EdgesMap
.count(Key
);
1686 EdgesMap
.insert({Key
, AfterColour
});
1688 EdgesMap
[Key
] = CommonColour
;
1693 // Now go through the map of edges and add them to the node.
1694 for (auto &E
: EdgesMap
) {
1695 // Extract the source, sink and value from the edge key.
1696 StringRef S
= E
.getKey();
1697 auto SP1
= S
.rsplit(' ');
1698 auto &SourceSink
= SP1
.first
;
1699 auto SP2
= SourceSink
.split(' ');
1700 StringRef Source
= SP2
.first
;
1701 StringRef Sink
= SP2
.second
;
1702 StringRef Value
= SP1
.second
;
1704 assert(NodePosition
.count(Source
) == 1 && "Expected to find node.");
1705 DotCfgDiffNode
&SourceNode
= Nodes
[NodePosition
[Source
]];
1706 assert(NodePosition
.count(Sink
) == 1 && "Expected to find node.");
1707 unsigned SinkNode
= NodePosition
[Sink
];
1708 StringRef Colour
= E
.second
;
1710 // Look for an edge from Source to Sink
1711 if (EdgeLabels
.count(SourceSink
) == 0)
1712 EdgeLabels
.insert({SourceSink
, colourize(Value
.str(), Colour
)});
1714 StringRef V
= EdgeLabels
.find(SourceSink
)->getValue();
1715 std::string NV
= colourize(V
.str() + " " + Value
.str(), Colour
);
1716 Colour
= CommonColour
;
1717 EdgeLabels
[SourceSink
] = NV
;
1719 SourceNode
.addEdge(SinkNode
, Value
, Colour
);
1721 for (auto &I
: Nodes
)
1725 DotCfgDiffDisplayGraph
DotCfgDiff::createDisplayGraph(StringRef Title
,
1726 StringRef EntryNodeName
) {
1727 assert(NodePosition
.count(EntryNodeName
) == 1 &&
1728 "Expected to find entry block in map.");
1729 unsigned Entry
= NodePosition
[EntryNodeName
];
1730 assert(Entry
< Nodes
.size() && "Expected to find entry node");
1731 DotCfgDiffDisplayGraph
G(Title
.str());
1733 std::map
<const unsigned, unsigned> NodeMap
;
1735 int EntryIndex
= -1;
1737 for (auto &I
: Nodes
) {
1738 if (I
.getIndex() == Entry
)
1740 G
.createNode(I
.getBodyContent(), I
.getColour());
1741 NodeMap
.insert({I
.getIndex(), Index
++});
1743 assert(EntryIndex
>= 0 && "Expected entry node index to be set.");
1744 G
.setEntryNode(EntryIndex
);
1746 for (auto &I
: NodeMap
) {
1747 unsigned SourceNode
= I
.first
;
1748 unsigned DisplayNode
= I
.second
;
1749 getNode(SourceNode
).createDisplayEdges(G
, DisplayNode
, NodeMap
);
1754 void DotCfgDiffNode::createDisplayEdges(
1755 DotCfgDiffDisplayGraph
&DisplayGraph
, unsigned DisplayNodeIndex
,
1756 std::map
<const unsigned, unsigned> &NodeMap
) const {
1758 DisplayNode
&SourceDisplayNode
= DisplayGraph
.getNode(DisplayNodeIndex
);
1760 for (auto I
: Edges
) {
1761 unsigned SinkNodeIndex
= I
;
1762 StringRef Colour
= getEdgeColour(SinkNodeIndex
);
1763 const DotCfgDiffNode
*SinkNode
= &Graph
.getNode(SinkNodeIndex
);
1765 StringRef Label
= Graph
.getEdgeSourceLabel(getIndex(), SinkNodeIndex
);
1766 DisplayNode
&SinkDisplayNode
= DisplayGraph
.getNode(SinkNode
->getIndex());
1767 SourceDisplayNode
.createEdge(Label
, SinkDisplayNode
, Colour
);
1769 SourceDisplayNode
.createEdgeMap();
1772 void DotCfgDiffNode::finalize(DotCfgDiff
&G
) {
1773 for (auto E
: EdgesMap
) {
1774 Children
.emplace_back(E
.first
);
1775 Edges
.emplace_back(E
.first
);
1783 template <> struct GraphTraits
<DotCfgDiffDisplayGraph
*> {
1784 using NodeRef
= const DisplayNode
*;
1785 using ChildIteratorType
= DisplayNode::ChildIterator
;
1786 using nodes_iterator
= DotCfgDiffDisplayGraph::NodeIterator
;
1787 using EdgeRef
= const DisplayEdge
*;
1788 using ChildEdgeIterator
= DisplayNode::EdgeIterator
;
1790 static NodeRef
getEntryNode(const DotCfgDiffDisplayGraph
*G
) {
1791 return G
->getEntryNode();
1793 static ChildIteratorType
child_begin(NodeRef N
) {
1794 return N
->children_begin();
1796 static ChildIteratorType
child_end(NodeRef N
) { return N
->children_end(); }
1797 static nodes_iterator
nodes_begin(const DotCfgDiffDisplayGraph
*G
) {
1798 return G
->nodes_begin();
1800 static nodes_iterator
nodes_end(const DotCfgDiffDisplayGraph
*G
) {
1801 return G
->nodes_end();
1803 static ChildEdgeIterator
child_edge_begin(NodeRef N
) {
1804 return N
->edges_begin();
1806 static ChildEdgeIterator
child_edge_end(NodeRef N
) { return N
->edges_end(); }
1807 static NodeRef
edge_dest(EdgeRef E
) { return &E
->getDestinationNode(); }
1808 static unsigned size(const DotCfgDiffDisplayGraph
*G
) { return G
->size(); }
1812 struct DOTGraphTraits
<DotCfgDiffDisplayGraph
*> : public DefaultDOTGraphTraits
{
1813 explicit DOTGraphTraits(bool Simple
= false)
1814 : DefaultDOTGraphTraits(Simple
) {}
1816 static bool renderNodesUsingHTML() { return true; }
1817 static std::string
getGraphName(const DotCfgDiffDisplayGraph
*DiffData
) {
1818 return DiffData
->getGraphName();
1821 getGraphProperties(const DotCfgDiffDisplayGraph
*DiffData
) {
1822 return "\tsize=\"190, 190\";\n";
1824 static std::string
getNodeLabel(const DisplayNode
*Node
,
1825 const DotCfgDiffDisplayGraph
*DiffData
) {
1826 return DiffData
->getNodeLabel(*Node
);
1828 static std::string
getNodeAttributes(const DisplayNode
*Node
,
1829 const DotCfgDiffDisplayGraph
*DiffData
) {
1830 return DiffData
->getNodeAttributes(*Node
);
1832 static std::string
getEdgeSourceLabel(const DisplayNode
*From
,
1833 DisplayNode::ChildIterator
&To
) {
1834 return From
->getEdgeSourceLabel(**To
);
1836 static std::string
getEdgeAttributes(const DisplayNode
*From
,
1837 DisplayNode::ChildIterator
&To
,
1838 const DotCfgDiffDisplayGraph
*DiffData
) {
1839 return DiffData
->getEdgeColorAttr(*From
, **To
);
1847 void DotCfgDiffDisplayGraph::generateDotFile(StringRef DotFile
) {
1849 raw_fd_ostream
OutStream(DotFile
, EC
);
1851 errs() << "Error: " << EC
.message() << "\n";
1854 WriteGraph(OutStream
, this, false);
1863 DCData::DCData(const BasicBlock
&B
) {
1864 // Build up transition labels.
1865 const Instruction
*Term
= B
.getTerminator();
1866 if (const BranchInst
*Br
= dyn_cast
<const BranchInst
>(Term
))
1867 if (Br
->isUnconditional())
1868 addSuccessorLabel(Br
->getSuccessor(0)->getName().str(), "");
1870 addSuccessorLabel(Br
->getSuccessor(0)->getName().str(), "true");
1871 addSuccessorLabel(Br
->getSuccessor(1)->getName().str(), "false");
1873 else if (const SwitchInst
*Sw
= dyn_cast
<const SwitchInst
>(Term
)) {
1874 addSuccessorLabel(Sw
->case_default()->getCaseSuccessor()->getName().str(),
1876 for (auto &C
: Sw
->cases()) {
1877 assert(C
.getCaseValue() && "Expected to find case value.");
1878 SmallString
<20> Value
= formatv("{0}", C
.getCaseValue()->getSExtValue());
1879 addSuccessorLabel(C
.getCaseSuccessor()->getName().str(), Value
);
1882 for (const_succ_iterator I
= succ_begin(&B
), E
= succ_end(&B
); I
!= E
; ++I
)
1883 addSuccessorLabel((*I
)->getName().str(), "");
1886 DotCfgChangeReporter::DotCfgChangeReporter(bool Verbose
)
1887 : ChangeReporter
<IRDataT
<DCData
>>(Verbose
) {}
1889 void DotCfgChangeReporter::handleFunctionCompare(
1890 StringRef Name
, StringRef Prefix
, StringRef PassID
, StringRef Divider
,
1891 bool InModule
, unsigned Minor
, const FuncDataT
<DCData
> &Before
,
1892 const FuncDataT
<DCData
> &After
) {
1893 assert(HTML
&& "Expected outstream to be set");
1894 SmallString
<8> Extender
;
1895 SmallString
<8> Number
;
1896 // Handle numbering and file names.
1898 Extender
= formatv("{0}_{1}", N
, Minor
);
1899 Number
= formatv("{0}.{1}", N
, Minor
);
1901 Extender
= formatv("{0}", N
);
1902 Number
= formatv("{0}", N
);
1904 // Create a temporary file name for the dot file.
1905 SmallVector
<char, 128> SV
;
1906 sys::fs::createUniquePath("cfgdot-%%%%%%.dot", SV
, true);
1907 std::string DotFile
= Twine(SV
).str();
1909 SmallString
<20> PDFFileName
= formatv("diff_{0}.pdf", Extender
);
1910 SmallString
<200> Text
;
1912 Text
= formatv("{0}.{1}{2}{3}{4}", Number
, Prefix
, makeHTMLReady(PassID
),
1915 DotCfgDiff
Diff(Text
, Before
, After
);
1916 std::string EntryBlockName
= After
.getEntryBlockName();
1917 // Use the before entry block if the after entry block was removed.
1918 if (EntryBlockName
== "")
1919 EntryBlockName
= Before
.getEntryBlockName();
1920 assert(EntryBlockName
!= "" && "Expected to find entry block");
1922 DotCfgDiffDisplayGraph DG
= Diff
.createDisplayGraph(Text
, EntryBlockName
);
1923 DG
.generateDotFile(DotFile
);
1925 *HTML
<< genHTML(Text
, DotFile
, PDFFileName
);
1926 std::error_code EC
= sys::fs::remove(DotFile
);
1928 errs() << "Error: " << EC
.message() << "\n";
1931 std::string
DotCfgChangeReporter::genHTML(StringRef Text
, StringRef DotFile
,
1932 StringRef PDFFileName
) {
1933 SmallString
<20> PDFFile
= formatv("{0}/{1}", DotCfgDir
, PDFFileName
);
1934 // Create the PDF file.
1935 static ErrorOr
<std::string
> DotExe
= sys::findProgramByName(DotBinary
);
1937 return "Unable to find dot executable.";
1939 StringRef Args
[] = {DotBinary
, "-Tpdf", "-o", PDFFile
, DotFile
};
1940 int Result
= sys::ExecuteAndWait(*DotExe
, Args
, None
);
1942 return "Error executing system dot.";
1944 // Create the HTML tag refering to the PDF file.
1945 SmallString
<200> S
= formatv(
1946 " <a href=\"{0}\" target=\"_blank\">{1}</a><br/>\n", PDFFileName
, Text
);
1950 void DotCfgChangeReporter::handleInitialIR(Any IR
) {
1951 assert(HTML
&& "Expected outstream to be set");
1952 *HTML
<< "<button type=\"button\" class=\"collapsible\">0. "
1953 << "Initial IR (by function)</button>\n"
1954 << "<div class=\"content\">\n"
1956 // Create representation of IR
1957 IRDataT
<DCData
> Data
;
1958 IRComparer
<DCData
>::analyzeIR(IR
, Data
);
1959 // Now compare it against itself, which will have everything the
1960 // same and will generate the files.
1961 IRComparer
<DCData
>(Data
, Data
)
1962 .compare(getModuleForComparison(IR
),
1963 [&](bool InModule
, unsigned Minor
,
1964 const FuncDataT
<DCData
> &Before
,
1965 const FuncDataT
<DCData
> &After
) -> void {
1966 handleFunctionCompare("", " ", "Initial IR", "", InModule
,
1967 Minor
, Before
, After
);
1974 void DotCfgChangeReporter::generateIRRepresentation(Any IR
, StringRef PassID
,
1975 IRDataT
<DCData
> &Data
) {
1976 IRComparer
<DCData
>::analyzeIR(IR
, Data
);
1979 void DotCfgChangeReporter::omitAfter(StringRef PassID
, std::string
&Name
) {
1980 assert(HTML
&& "Expected outstream to be set");
1981 SmallString
<20> Banner
=
1982 formatv(" <a>{0}. Pass {1} on {2} omitted because no change</a><br/>\n",
1983 N
, makeHTMLReady(PassID
), Name
);
1988 void DotCfgChangeReporter::handleAfter(StringRef PassID
, std::string
&Name
,
1989 const IRDataT
<DCData
> &Before
,
1990 const IRDataT
<DCData
> &After
, Any IR
) {
1991 assert(HTML
&& "Expected outstream to be set");
1992 IRComparer
<DCData
>(Before
, After
)
1993 .compare(getModuleForComparison(IR
),
1994 [&](bool InModule
, unsigned Minor
,
1995 const FuncDataT
<DCData
> &Before
,
1996 const FuncDataT
<DCData
> &After
) -> void {
1997 handleFunctionCompare(Name
, " Pass ", PassID
, " on ", InModule
,
1998 Minor
, Before
, After
);
2000 *HTML
<< " </p></div>\n";
2004 void DotCfgChangeReporter::handleInvalidated(StringRef PassID
) {
2005 assert(HTML
&& "Expected outstream to be set");
2006 SmallString
<20> Banner
=
2007 formatv(" <a>{0}. {1} invalidated</a><br/>\n", N
, makeHTMLReady(PassID
));
2012 void DotCfgChangeReporter::handleFiltered(StringRef PassID
, std::string
&Name
) {
2013 assert(HTML
&& "Expected outstream to be set");
2014 SmallString
<20> Banner
=
2015 formatv(" <a>{0}. Pass {1} on {2} filtered out</a><br/>\n", N
,
2016 makeHTMLReady(PassID
), Name
);
2021 void DotCfgChangeReporter::handleIgnored(StringRef PassID
, std::string
&Name
) {
2022 assert(HTML
&& "Expected outstream to be set");
2023 SmallString
<20> Banner
= formatv(" <a>{0}. {1} on {2} ignored</a><br/>\n", N
,
2024 makeHTMLReady(PassID
), Name
);
2029 bool DotCfgChangeReporter::initializeHTML() {
2031 HTML
= std::make_unique
<raw_fd_ostream
>(DotCfgDir
+ "/passes.html", EC
);
2037 *HTML
<< "<!doctype html>"
2040 << "<style>.collapsible { "
2041 << "background-color: #777;"
2043 << " cursor: pointer;"
2044 << " padding: 18px;"
2047 << " text-align: left;"
2048 << " outline: none;"
2049 << " font-size: 15px;"
2050 << "} .active, .collapsible:hover {"
2051 << " background-color: #555;"
2053 << " padding: 0 18px;"
2054 << " display: none;"
2055 << " overflow: hidden;"
2056 << " background-color: #f1f1f1;"
2059 << "<title>passes.html</title>"
2065 DotCfgChangeReporter::~DotCfgChangeReporter() {
2069 << "<script>var coll = document.getElementsByClassName(\"collapsible\");"
2071 << "for (i = 0; i < coll.length; i++) {"
2072 << "coll[i].addEventListener(\"click\", function() {"
2073 << " this.classList.toggle(\"active\");"
2074 << " var content = this.nextElementSibling;"
2075 << " if (content.style.display === \"block\"){"
2076 << " content.style.display = \"none\";"
2079 << " content.style.display= \"block\";"
2090 void DotCfgChangeReporter::registerCallbacks(
2091 PassInstrumentationCallbacks
&PIC
) {
2092 if ((PrintChanged
== ChangePrinter::PrintChangedDotCfgVerbose
||
2093 PrintChanged
== ChangePrinter::PrintChangedDotCfgQuiet
)) {
2094 SmallString
<128> OutputDir
;
2095 sys::fs::expand_tilde(DotCfgDir
, OutputDir
);
2096 sys::fs::make_absolute(OutputDir
);
2097 assert(!OutputDir
.empty() && "expected output dir to be non-empty");
2098 DotCfgDir
= OutputDir
.c_str();
2099 if (initializeHTML()) {
2100 ChangeReporter
<IRDataT
<DCData
>>::registerRequiredCallbacks(PIC
);
2103 dbgs() << "Unable to open output stream for -cfg-dot-changed\n";
2107 StandardInstrumentations::StandardInstrumentations(
2108 bool DebugLogging
, bool VerifyEach
, PrintPassOptions PrintPassOpts
)
2109 : PrintPass(DebugLogging
, PrintPassOpts
), OptNone(DebugLogging
),
2110 PrintChangedIR(PrintChanged
== ChangePrinter::PrintChangedVerbose
),
2112 PrintChanged
== ChangePrinter::PrintChangedDiffVerbose
||
2113 PrintChanged
== ChangePrinter::PrintChangedColourDiffVerbose
,
2114 PrintChanged
== ChangePrinter::PrintChangedColourDiffVerbose
||
2115 PrintChanged
== ChangePrinter::PrintChangedColourDiffQuiet
),
2116 WebsiteChangeReporter(PrintChanged
==
2117 ChangePrinter::PrintChangedDotCfgVerbose
),
2118 Verify(DebugLogging
), VerifyEach(VerifyEach
) {}
2120 void StandardInstrumentations::registerCallbacks(
2121 PassInstrumentationCallbacks
&PIC
, FunctionAnalysisManager
*FAM
) {
2122 PrintIR
.registerCallbacks(PIC
);
2123 PrintPass
.registerCallbacks(PIC
);
2124 TimePasses
.registerCallbacks(PIC
);
2125 OptNone
.registerCallbacks(PIC
);
2126 OptBisect
.registerCallbacks(PIC
);
2128 PreservedCFGChecker
.registerCallbacks(PIC
, *FAM
);
2129 PrintChangedIR
.registerCallbacks(PIC
);
2130 PseudoProbeVerification
.registerCallbacks(PIC
);
2132 Verify
.registerCallbacks(PIC
);
2133 PrintChangedDiff
.registerCallbacks(PIC
);
2134 WebsiteChangeReporter
.registerCallbacks(PIC
);
2137 template class ChangeReporter
<std::string
>;
2138 template class TextChangeReporter
<std::string
>;
2140 template class BlockDataT
<EmptyData
>;
2141 template class FuncDataT
<EmptyData
>;
2142 template class IRDataT
<EmptyData
>;
2143 template class ChangeReporter
<IRDataT
<EmptyData
>>;
2144 template class TextChangeReporter
<IRDataT
<EmptyData
>>;
2145 template class IRComparer
<EmptyData
>;