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 
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/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/MemoryBuffer.h"
32 #include "llvm/Support/Program.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include <unordered_set>
35 #include <vector>
36 
37 using namespace llvm;
38 
39 cl::opt<bool> PreservedCFGCheckerInstrumentation::VerifyPreservedCFG(
40     "verify-cfg-preserved", cl::Hidden,
41 #ifdef NDEBUG
42     cl::init(false));
43 #else
44     cl::init(true));
45 #endif
46 
47 // FIXME: Change `-debug-pass-manager` from boolean to enum type. Similar to
48 // `-debug-pass` in legacy PM.
49 static cl::opt<bool>
50     DebugPMVerbose("debug-pass-manager-verbose", cl::Hidden, cl::init(false),
51                    cl::desc("Print all pass management debugging information. "
52                             "`-debug-pass-manager` must also be specified"));
53 
54 // An option that prints out the IR after passes, similar to
55 // -print-after-all except that it only prints the IR after passes that
56 // change the IR.  Those passes that do not make changes to the IR are
57 // reported as not making any changes.  In addition, the initial IR is
58 // also reported.  Other hidden options affect the output from this
59 // option.  -filter-passes will limit the output to the named passes
60 // that actually change the IR and other passes are reported as filtered out.
61 // The specified passes will either be reported as making no changes (with
62 // no IR reported) or the changed IR will be reported.  Also, the
63 // -filter-print-funcs and -print-module-scope options will do similar
64 // filtering based on function name, reporting changed IRs as functions(or
65 // modules if -print-module-scope is specified) for a particular function
66 // or indicating that the IR has been filtered out.  The extra options
67 // can be combined, allowing only changed IRs for certain passes on certain
68 // functions to be reported in different formats, with the rest being
69 // reported as filtered out.  The -print-before-changed option will print
70 // the IR as it was before each pass that changed it.  The optional
71 // value of quiet will only report when the IR changes, suppressing
72 // all other messages, including the initial IR.  The values "diff" and
73 // "diff-quiet" will present the changes in a form similar to a patch, in
74 // either verbose or quiet mode, respectively.  The lines that are removed
75 // and added are prefixed with '-' and '+', respectively.  The
76 // -filter-print-funcs and -filter-passes can be used to filter the output.
77 // This reporter relies on the linux diff utility to do comparisons and
78 // insert the prefixes.  For systems that do not have the necessary
79 // facilities, the error message will be shown in place of the expected output.
80 //
81 enum class ChangePrinter {
82   NoChangePrinter,
83   PrintChangedVerbose,
84   PrintChangedQuiet,
85   PrintChangedDiffVerbose,
86   PrintChangedDiffQuiet,
87   PrintChangedColourDiffVerbose,
88   PrintChangedColourDiffQuiet
89 };
90 static cl::opt<ChangePrinter> PrintChanged(
91     "print-changed", cl::desc("Print changed IRs"), cl::Hidden,
92     cl::ValueOptional, cl::init(ChangePrinter::NoChangePrinter),
93     cl::values(
94         clEnumValN(ChangePrinter::PrintChangedQuiet, "quiet",
95                    "Run in quiet mode"),
96         clEnumValN(ChangePrinter::PrintChangedDiffVerbose, "diff",
97                    "Display patch-like changes"),
98         clEnumValN(ChangePrinter::PrintChangedDiffQuiet, "diff-quiet",
99                    "Display patch-like changes in quiet mode"),
100         clEnumValN(ChangePrinter::PrintChangedColourDiffVerbose, "cdiff",
101                    "Display patch-like changes with color"),
102         clEnumValN(ChangePrinter::PrintChangedColourDiffQuiet, "cdiff-quiet",
103                    "Display patch-like changes in quiet mode with color"),
104         // Sentinel value for unspecified option.
105         clEnumValN(ChangePrinter::PrintChangedVerbose, "", "")));
106 
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 
123 // An option for specifying the diff used by print-changed=[diff | diff-quiet]
124 static cl::opt<std::string>
125     DiffBinary("print-changed-diff-path", cl::Hidden, cl::init("diff"),
126                cl::desc("system diff used by change reporters"));
127 
128 namespace {
129 
130 // Perform a system based diff between \p Before and \p After, using
131 // \p OldLineFormat, \p NewLineFormat, and \p UnchangedLineFormat
132 // to control the formatting of the output.  Return an error message
133 // for any failures instead of the diff.
134 std::string doSystemDiff(StringRef Before, StringRef After,
135                          StringRef OldLineFormat, StringRef NewLineFormat,
136                          StringRef UnchangedLineFormat) {
137   StringRef SR[2]{Before, After};
138   // Store the 2 bodies into temporary files and call diff on them
139   // to get the body of the node.
140   const unsigned NumFiles = 3;
141   std::string FileName[NumFiles];
142   int FD[NumFiles]{-1, -1, -1};
143   for (unsigned I = 0; I < NumFiles; ++I) {
144     if (FD[I] == -1) {
145       SmallVector<char, 200> SV;
146       std::error_code EC =
147           sys::fs::createTemporaryFile("tmpdiff", "txt", FD[I], SV);
148       if (EC)
149         return "Unable to create temporary file.";
150       FileName[I] = Twine(SV).str();
151     }
152     // The third file is used as the result of the diff.
153     if (I == NumFiles - 1)
154       break;
155 
156     std::error_code EC = sys::fs::openFileForWrite(FileName[I], FD[I]);
157     if (EC)
158       return "Unable to open temporary file for writing.";
159 
160     raw_fd_ostream OutStream(FD[I], /*shouldClose=*/true);
161     if (FD[I] == -1)
162       return "Error opening file for writing.";
163     OutStream << SR[I];
164   }
165 
166   static ErrorOr<std::string> DiffExe = sys::findProgramByName(DiffBinary);
167   if (!DiffExe)
168     return "Unable to find diff executable.";
169 
170   SmallString<128> OLF = formatv("--old-line-format={0}", OldLineFormat);
171   SmallString<128> NLF = formatv("--new-line-format={0}", NewLineFormat);
172   SmallString<128> ULF =
173       formatv("--unchanged-line-format={0}", UnchangedLineFormat);
174 
175   StringRef Args[] = {"-w", "-d", OLF, NLF, ULF, FileName[0], FileName[1]};
176   Optional<StringRef> Redirects[] = {None, StringRef(FileName[2]), None};
177   int Result = sys::ExecuteAndWait(*DiffExe, Args, None, Redirects);
178   if (Result < 0)
179     return "Error executing system diff.";
180   std::string Diff;
181   auto B = MemoryBuffer::getFile(FileName[2]);
182   if (B && *B)
183     Diff = (*B)->getBuffer().str();
184   else
185     return "Unable to read result.";
186 
187   // Clean up.
188   for (unsigned I = 0; I < NumFiles; ++I) {
189     std::error_code EC = sys::fs::remove(FileName[I]);
190     if (EC)
191       return "Unable to remove temporary file.";
192   }
193   return Diff;
194 }
195 
196 /// Extract Module out of \p IR unit. May return nullptr if \p IR does not match
197 /// certain global filters. Will never return nullptr if \p Force is true.
198 const Module *unwrapModule(Any IR, bool Force = false) {
199   if (any_isa<const Module *>(IR))
200     return any_cast<const Module *>(IR);
201 
202   if (any_isa<const Function *>(IR)) {
203     const Function *F = any_cast<const Function *>(IR);
204     if (!Force && !isFunctionInPrintList(F->getName()))
205       return nullptr;
206 
207     return F->getParent();
208   }
209 
210   if (any_isa<const LazyCallGraph::SCC *>(IR)) {
211     const LazyCallGraph::SCC *C = any_cast<const LazyCallGraph::SCC *>(IR);
212     for (const LazyCallGraph::Node &N : *C) {
213       const Function &F = N.getFunction();
214       if (Force || (!F.isDeclaration() && isFunctionInPrintList(F.getName()))) {
215         return F.getParent();
216       }
217     }
218     assert(!Force && "Expected a module");
219     return nullptr;
220   }
221 
222   if (any_isa<const Loop *>(IR)) {
223     const Loop *L = any_cast<const Loop *>(IR);
224     const Function *F = L->getHeader()->getParent();
225     if (!Force && !isFunctionInPrintList(F->getName()))
226       return nullptr;
227     return F->getParent();
228   }
229 
230   llvm_unreachable("Unknown IR unit");
231 }
232 
233 void printIR(raw_ostream &OS, const Function *F) {
234   if (!isFunctionInPrintList(F->getName()))
235     return;
236   OS << *F;
237 }
238 
239 void printIR(raw_ostream &OS, const Module *M,
240              bool ShouldPreserveUseListOrder = false) {
241   if (isFunctionInPrintList("*") || forcePrintModuleIR()) {
242     M->print(OS, nullptr, ShouldPreserveUseListOrder);
243   } else {
244     for (const auto &F : M->functions()) {
245       printIR(OS, &F);
246     }
247   }
248 }
249 
250 void printIR(raw_ostream &OS, const LazyCallGraph::SCC *C) {
251   for (const LazyCallGraph::Node &N : *C) {
252     const Function &F = N.getFunction();
253     if (!F.isDeclaration() && isFunctionInPrintList(F.getName())) {
254       F.print(OS);
255     }
256   }
257 }
258 
259 void printIR(raw_ostream &OS, const Loop *L) {
260   const Function *F = L->getHeader()->getParent();
261   if (!isFunctionInPrintList(F->getName()))
262     return;
263   printLoop(const_cast<Loop &>(*L), OS);
264 }
265 
266 std::string getIRName(Any IR) {
267   if (any_isa<const Module *>(IR))
268     return "[module]";
269 
270   if (any_isa<const Function *>(IR)) {
271     const Function *F = any_cast<const Function *>(IR);
272     return F->getName().str();
273   }
274 
275   if (any_isa<const LazyCallGraph::SCC *>(IR)) {
276     const LazyCallGraph::SCC *C = any_cast<const LazyCallGraph::SCC *>(IR);
277     return C->getName();
278   }
279 
280   if (any_isa<const Loop *>(IR)) {
281     const Loop *L = any_cast<const Loop *>(IR);
282     std::string S;
283     raw_string_ostream OS(S);
284     L->print(OS, /*Verbose*/ false, /*PrintNested*/ false);
285     return OS.str();
286   }
287 
288   llvm_unreachable("Unknown wrapped IR type");
289 }
290 
291 bool moduleContainsFilterPrintFunc(const Module &M) {
292   return any_of(M.functions(),
293                 [](const Function &F) {
294                   return isFunctionInPrintList(F.getName());
295                 }) ||
296          isFunctionInPrintList("*");
297 }
298 
299 bool sccContainsFilterPrintFunc(const LazyCallGraph::SCC &C) {
300   return any_of(C,
301                 [](const LazyCallGraph::Node &N) {
302                   return isFunctionInPrintList(N.getName());
303                 }) ||
304          isFunctionInPrintList("*");
305 }
306 
307 bool shouldPrintIR(Any IR) {
308   if (any_isa<const Module *>(IR)) {
309     const Module *M = any_cast<const Module *>(IR);
310     return moduleContainsFilterPrintFunc(*M);
311   }
312 
313   if (any_isa<const Function *>(IR)) {
314     const Function *F = any_cast<const Function *>(IR);
315     return isFunctionInPrintList(F->getName());
316   }
317 
318   if (any_isa<const LazyCallGraph::SCC *>(IR)) {
319     const LazyCallGraph::SCC *C = any_cast<const LazyCallGraph::SCC *>(IR);
320     return sccContainsFilterPrintFunc(*C);
321   }
322 
323   if (any_isa<const Loop *>(IR)) {
324     const Loop *L = any_cast<const Loop *>(IR);
325     return isFunctionInPrintList(L->getHeader()->getParent()->getName());
326   }
327   llvm_unreachable("Unknown wrapped IR type");
328 }
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                     bool ShouldPreserveUseListOrder = false) {
334   if (!shouldPrintIR(IR))
335     return;
336 
337   if (forcePrintModuleIR()) {
338     auto *M = unwrapModule(IR);
339     assert(M && "should have unwrapped module");
340     printIR(OS, M, ShouldPreserveUseListOrder);
341     return;
342   }
343 
344   if (any_isa<const Module *>(IR)) {
345     const Module *M = any_cast<const Module *>(IR);
346     printIR(OS, M, ShouldPreserveUseListOrder);
347     return;
348   }
349 
350   if (any_isa<const Function *>(IR)) {
351     const Function *F = any_cast<const Function *>(IR);
352     printIR(OS, F);
353     return;
354   }
355 
356   if (any_isa<const LazyCallGraph::SCC *>(IR)) {
357     const LazyCallGraph::SCC *C = any_cast<const LazyCallGraph::SCC *>(IR);
358     printIR(OS, C);
359     return;
360   }
361 
362   if (any_isa<const Loop *>(IR)) {
363     const Loop *L = any_cast<const Loop *>(IR);
364     printIR(OS, L);
365     return;
366   }
367   llvm_unreachable("Unknown wrapped IR type");
368 }
369 
370 // Return true when this is a pass for which changes should be ignored
371 bool isIgnored(StringRef PassID) {
372   return isSpecialPass(PassID,
373                        {"PassManager", "PassAdaptor", "AnalysisManagerProxy",
374                         "DevirtSCCRepeatedPass", "ModuleInlinerWrapperPass"});
375 }
376 
377 } // namespace
378 
379 template <typename IRUnitT>
380 ChangeReporter<IRUnitT>::~ChangeReporter<IRUnitT>() {
381   assert(BeforeStack.empty() && "Problem with Change Printer stack.");
382 }
383 
384 template <typename IRUnitT>
385 bool ChangeReporter<IRUnitT>::isInterestingFunction(const Function &F) {
386   return isFunctionInPrintList(F.getName());
387 }
388 
389 template <typename IRUnitT>
390 bool ChangeReporter<IRUnitT>::isInterestingPass(StringRef PassID) {
391   if (isIgnored(PassID))
392     return false;
393 
394   static std::unordered_set<std::string> PrintPassNames(PrintPassesList.begin(),
395                                                         PrintPassesList.end());
396   return PrintPassNames.empty() || PrintPassNames.count(PassID.str());
397 }
398 
399 // Return true when this is a pass on IR for which printing
400 // of changes is desired.
401 template <typename IRUnitT>
402 bool ChangeReporter<IRUnitT>::isInteresting(Any IR, StringRef PassID) {
403   if (!isInterestingPass(PassID))
404     return false;
405   if (any_isa<const Function *>(IR))
406     return isInterestingFunction(*any_cast<const Function *>(IR));
407   return true;
408 }
409 
410 template <typename IRUnitT>
411 void ChangeReporter<IRUnitT>::saveIRBeforePass(Any IR, StringRef PassID) {
412   // Always need to place something on the stack because invalidated passes
413   // are not given the IR so it cannot be determined whether the pass was for
414   // something that was filtered out.
415   BeforeStack.emplace_back();
416 
417   if (!isInteresting(IR, PassID))
418     return;
419   // Is this the initial IR?
420   if (InitialIR) {
421     InitialIR = false;
422     if (VerboseMode)
423       handleInitialIR(IR);
424   }
425 
426   // Save the IR representation on the stack.
427   IRUnitT &Data = BeforeStack.back();
428   generateIRRepresentation(IR, PassID, Data);
429 }
430 
431 template <typename IRUnitT>
432 void ChangeReporter<IRUnitT>::handleIRAfterPass(Any IR, StringRef PassID) {
433   assert(!BeforeStack.empty() && "Unexpected empty stack encountered.");
434 
435   std::string Name = getIRName(IR);
436 
437   if (isIgnored(PassID)) {
438     if (VerboseMode)
439       handleIgnored(PassID, Name);
440   } else if (!isInteresting(IR, PassID)) {
441     if (VerboseMode)
442       handleFiltered(PassID, Name);
443   } else {
444     // Get the before rep from the stack
445     IRUnitT &Before = BeforeStack.back();
446     // Create the after rep
447     IRUnitT After;
448     generateIRRepresentation(IR, PassID, After);
449 
450     // Was there a change in IR?
451     if (same(Before, After)) {
452       if (VerboseMode)
453         omitAfter(PassID, Name);
454     } else
455       handleAfter(PassID, Name, Before, After, IR);
456   }
457   BeforeStack.pop_back();
458 }
459 
460 template <typename IRUnitT>
461 void ChangeReporter<IRUnitT>::handleInvalidatedPass(StringRef PassID) {
462   assert(!BeforeStack.empty() && "Unexpected empty stack encountered.");
463 
464   // Always flag it as invalidated as we cannot determine when
465   // a pass for a filtered function is invalidated since we do not
466   // get the IR in the call.  Also, the output is just alternate
467   // forms of the banner anyway.
468   if (VerboseMode)
469     handleInvalidated(PassID);
470   BeforeStack.pop_back();
471 }
472 
473 template <typename IRUnitT>
474 void ChangeReporter<IRUnitT>::registerRequiredCallbacks(
475     PassInstrumentationCallbacks &PIC) {
476   PIC.registerBeforeNonSkippedPassCallback(
477       [this](StringRef P, Any IR) { saveIRBeforePass(IR, P); });
478 
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 
489 ChangedBlockData::ChangedBlockData(const BasicBlock &B)
490     : Label(B.getName().str()) {
491   raw_string_ostream SS(Body);
492   B.print(SS, nullptr, true, true);
493 }
494 
495 template <typename IRUnitT>
496 TextChangeReporter<IRUnitT>::TextChangeReporter(bool Verbose)
497     : ChangeReporter<IRUnitT>(Verbose), Out(dbgs()) {}
498 
499 template <typename IRUnitT>
500 void TextChangeReporter<IRUnitT>::handleInitialIR(Any IR) {
501   // Always print the module.
502   // Unwrap and print directly to avoid filtering problems in general routines.
503   auto *M = unwrapModule(IR, /*Force=*/true);
504   assert(M && "Expected module to be unwrapped when forced.");
505   Out << "*** IR Dump At Start ***\n";
506   M->print(Out, nullptr,
507            /*ShouldPreserveUseListOrder=*/true);
508 }
509 
510 template <typename IRUnitT>
511 void TextChangeReporter<IRUnitT>::omitAfter(StringRef PassID,
512                                             std::string &Name) {
513   Out << formatv("*** IR Dump After {0} on {1} omitted because no change ***\n",
514                  PassID, Name);
515 }
516 
517 template <typename IRUnitT>
518 void TextChangeReporter<IRUnitT>::handleInvalidated(StringRef PassID) {
519   Out << formatv("*** IR Pass {0} invalidated ***\n", PassID);
520 }
521 
522 template <typename IRUnitT>
523 void TextChangeReporter<IRUnitT>::handleFiltered(StringRef PassID,
524                                                  std::string &Name) {
525   SmallString<20> Banner =
526       formatv("*** IR Dump After {0} on {1} filtered out ***\n", PassID, Name);
527   Out << Banner;
528 }
529 
530 template <typename IRUnitT>
531 void TextChangeReporter<IRUnitT>::handleIgnored(StringRef PassID,
532                                                 std::string &Name) {
533   Out << formatv("*** IR Pass {0} on {1} ignored ***\n", PassID, Name);
534 }
535 
536 IRChangedPrinter::~IRChangedPrinter() {}
537 
538 void IRChangedPrinter::registerCallbacks(PassInstrumentationCallbacks &PIC) {
539   if (PrintChanged == ChangePrinter::PrintChangedVerbose ||
540       PrintChanged == ChangePrinter::PrintChangedQuiet)
541     TextChangeReporter<std::string>::registerRequiredCallbacks(PIC);
542 }
543 
544 void IRChangedPrinter::generateIRRepresentation(Any IR, StringRef PassID,
545                                                 std::string &Output) {
546   raw_string_ostream OS(Output);
547   unwrapAndPrint(OS, IR,
548                  /*ShouldPreserveUseListOrder=*/true);
549   OS.str();
550 }
551 
552 void IRChangedPrinter::handleAfter(StringRef PassID, std::string &Name,
553                                    const std::string &Before,
554                                    const std::string &After, Any) {
555   // Report the IR before the changes when requested.
556   if (PrintChangedBefore)
557     Out << "*** IR Dump Before " << PassID << " on " << Name << " ***\n"
558         << Before;
559 
560   // We might not get anything to print if we only want to print a specific
561   // function but it gets deleted.
562   if (After.empty()) {
563     Out << "*** IR Deleted After " << PassID << " on " << Name << " ***\n";
564     return;
565   }
566 
567   Out << "*** IR Dump After " << PassID << " on " << Name << " ***\n" << After;
568 }
569 
570 bool IRChangedPrinter::same(const std::string &S1, const std::string &S2) {
571   return S1 == S2;
572 }
573 
574 template <typename IRData>
575 void OrderedChangedData<IRData>::report(
576     const OrderedChangedData &Before, const OrderedChangedData &After,
577     function_ref<void(const IRData *, const IRData *)> HandlePair) {
578   const auto &BFD = Before.getData();
579   const auto &AFD = After.getData();
580   std::vector<std::string>::const_iterator BI = Before.getOrder().begin();
581   std::vector<std::string>::const_iterator BE = Before.getOrder().end();
582   std::vector<std::string>::const_iterator AI = After.getOrder().begin();
583   std::vector<std::string>::const_iterator AE = After.getOrder().end();
584 
585   auto handlePotentiallyRemovedIRData = [&](std::string S) {
586     // The order in LLVM may have changed so check if still exists.
587     if (!AFD.count(S)) {
588       // This has been removed.
589       HandlePair(&BFD.find(*BI)->getValue(), nullptr);
590     }
591   };
592   auto handleNewIRData = [&](std::vector<const IRData *> &Q) {
593     // Print out any queued up new sections
594     for (const IRData *NBI : Q)
595       HandlePair(nullptr, NBI);
596     Q.clear();
597   };
598 
599   // Print out the IRData in the after order, with before ones interspersed
600   // appropriately (ie, somewhere near where they were in the before list).
601   // Start at the beginning of both lists.  Loop through the
602   // after list.  If an element is common, then advance in the before list
603   // reporting the removed ones until the common one is reached.  Report any
604   // queued up new ones and then report the common one.  If an element is not
605   // common, then enqueue it for reporting.  When the after list is exhausted,
606   // loop through the before list, reporting any removed ones.  Finally,
607   // report the rest of the enqueued new ones.
608   std::vector<const IRData *> NewIRDataQueue;
609   while (AI != AE) {
610     if (!BFD.count(*AI)) {
611       // This section is new so place it in the queue.  This will cause it
612       // to be reported after deleted sections.
613       NewIRDataQueue.emplace_back(&AFD.find(*AI)->getValue());
614       ++AI;
615       continue;
616     }
617     // This section is in both; advance and print out any before-only
618     // until we get to it.
619     while (*BI != *AI) {
620       handlePotentiallyRemovedIRData(*BI);
621       ++BI;
622     }
623     // Report any new sections that were queued up and waiting.
624     handleNewIRData(NewIRDataQueue);
625 
626     const IRData &AData = AFD.find(*AI)->getValue();
627     const IRData &BData = BFD.find(*AI)->getValue();
628     HandlePair(&BData, &AData);
629     ++BI;
630     ++AI;
631   }
632 
633   // Check any remaining before sections to see if they have been removed
634   while (BI != BE) {
635     handlePotentiallyRemovedIRData(*BI);
636     ++BI;
637   }
638 
639   handleNewIRData(NewIRDataQueue);
640 }
641 
642 void ChangedIRComparer::compare(Any IR, StringRef Prefix, StringRef PassID,
643                                 StringRef Name) {
644   if (!getModuleForComparison(IR)) {
645     // Not a module so just handle the single function.
646     assert(Before.getData().size() == 1 && "Expected only one function.");
647     assert(After.getData().size() == 1 && "Expected only one function.");
648     handleFunctionCompare(Name, Prefix, PassID, false,
649                           Before.getData().begin()->getValue(),
650                           After.getData().begin()->getValue());
651     return;
652   }
653 
654   ChangedIRData::report(
655       Before, After, [&](const ChangedFuncData *B, const ChangedFuncData *A) {
656         ChangedFuncData Missing;
657         if (!B)
658           B = &Missing;
659         else if (!A)
660           A = &Missing;
661         assert(B != &Missing && A != &Missing &&
662                "Both functions cannot be missing.");
663         handleFunctionCompare(Name, Prefix, PassID, true, *B, *A);
664       });
665 }
666 
667 void ChangedIRComparer::analyzeIR(Any IR, ChangedIRData &Data) {
668   if (const Module *M = getModuleForComparison(IR)) {
669     // Create data for each existing/interesting function in the module.
670     for (const Function &F : *M)
671       generateFunctionData(Data, F);
672     return;
673   }
674 
675   const Function *F = nullptr;
676   if (any_isa<const Function *>(IR))
677     F = any_cast<const Function *>(IR);
678   else {
679     assert(any_isa<const Loop *>(IR) && "Unknown IR unit.");
680     const Loop *L = any_cast<const Loop *>(IR);
681     F = L->getHeader()->getParent();
682   }
683   assert(F && "Unknown IR unit.");
684   generateFunctionData(Data, *F);
685 }
686 
687 const Module *ChangedIRComparer::getModuleForComparison(Any IR) {
688   if (any_isa<const Module *>(IR))
689     return any_cast<const Module *>(IR);
690   if (any_isa<const LazyCallGraph::SCC *>(IR))
691     return any_cast<const LazyCallGraph::SCC *>(IR)
692         ->begin()
693         ->getFunction()
694         .getParent();
695   return nullptr;
696 }
697 
698 bool ChangedIRComparer::generateFunctionData(ChangedIRData &Data,
699                                              const Function &F) {
700   if (!F.isDeclaration() && isFunctionInPrintList(F.getName())) {
701     ChangedFuncData CFD;
702     for (const auto &B : F) {
703       CFD.getOrder().emplace_back(B.getName());
704       CFD.getData().insert({B.getName(), B});
705     }
706     Data.getOrder().emplace_back(F.getName());
707     Data.getData().insert({F.getName(), CFD});
708     return true;
709   }
710   return false;
711 }
712 
713 PrintIRInstrumentation::~PrintIRInstrumentation() {
714   assert(ModuleDescStack.empty() && "ModuleDescStack is not empty at exit");
715 }
716 
717 void PrintIRInstrumentation::pushModuleDesc(StringRef PassID, Any IR) {
718   assert(StoreModuleDesc);
719   const Module *M = unwrapModule(IR);
720   ModuleDescStack.emplace_back(M, getIRName(IR), PassID);
721 }
722 
723 PrintIRInstrumentation::PrintModuleDesc
724 PrintIRInstrumentation::popModuleDesc(StringRef PassID) {
725   assert(!ModuleDescStack.empty() && "empty ModuleDescStack");
726   PrintModuleDesc ModuleDesc = ModuleDescStack.pop_back_val();
727   assert(std::get<2>(ModuleDesc).equals(PassID) && "malformed ModuleDescStack");
728   return ModuleDesc;
729 }
730 
731 void PrintIRInstrumentation::printBeforePass(StringRef PassID, Any IR) {
732   if (isIgnored(PassID))
733     return;
734 
735   // Saving Module for AfterPassInvalidated operations.
736   // Note: here we rely on a fact that we do not change modules while
737   // traversing the pipeline, so the latest captured module is good
738   // for all print operations that has not happen yet.
739   if (StoreModuleDesc && shouldPrintAfterPass(PassID))
740     pushModuleDesc(PassID, IR);
741 
742   if (!shouldPrintBeforePass(PassID))
743     return;
744 
745   if (!shouldPrintIR(IR))
746     return;
747 
748   dbgs() << "*** IR Dump Before " << PassID << " on " << getIRName(IR)
749          << " ***\n";
750   unwrapAndPrint(dbgs(), IR);
751 }
752 
753 void PrintIRInstrumentation::printAfterPass(StringRef PassID, Any IR) {
754   if (isIgnored(PassID))
755     return;
756 
757   if (!shouldPrintAfterPass(PassID))
758     return;
759 
760   if (StoreModuleDesc) {
761     const Module *M;
762     std::string IRName;
763     StringRef StoredPassID;
764     std::tie(M, IRName, StoredPassID) = popModuleDesc(PassID);
765     assert(StoredPassID == PassID && "mismatched PassID");
766   }
767 
768   if (!shouldPrintIR(IR))
769     return;
770 
771   dbgs() << "*** IR Dump After " << PassID << " on " << getIRName(IR)
772          << " ***\n";
773   unwrapAndPrint(dbgs(), IR);
774 }
775 
776 void PrintIRInstrumentation::printAfterPassInvalidated(StringRef PassID) {
777   StringRef PassName = PIC->getPassNameForClassName(PassID);
778   if (!StoreModuleDesc || !shouldPrintAfterPass(PassName))
779     return;
780 
781   if (isIgnored(PassID))
782     return;
783 
784   const Module *M;
785   std::string IRName;
786   StringRef StoredPassID;
787   std::tie(M, IRName, StoredPassID) = popModuleDesc(PassID);
788   assert(StoredPassID == PassID && "mismatched PassID");
789   // Additional filtering (e.g. -filter-print-func) can lead to module
790   // printing being skipped.
791   if (!M)
792     return;
793 
794   SmallString<20> Banner =
795       formatv("*** IR Dump After {0} on {1} (invalidated) ***", PassID, IRName);
796   dbgs() << Banner << "\n";
797   printIR(dbgs(), M);
798 }
799 
800 bool PrintIRInstrumentation::shouldPrintBeforePass(StringRef PassID) {
801   if (shouldPrintBeforeAll())
802     return true;
803 
804   StringRef PassName = PIC->getPassNameForClassName(PassID);
805   return llvm::is_contained(printBeforePasses(), PassName);
806 }
807 
808 bool PrintIRInstrumentation::shouldPrintAfterPass(StringRef PassID) {
809   if (shouldPrintAfterAll())
810     return true;
811 
812   StringRef PassName = PIC->getPassNameForClassName(PassID);
813   return llvm::is_contained(printAfterPasses(), PassName);
814 }
815 
816 void PrintIRInstrumentation::registerCallbacks(
817     PassInstrumentationCallbacks &PIC) {
818   this->PIC = &PIC;
819 
820   // BeforePass callback is not just for printing, it also saves a Module
821   // for later use in AfterPassInvalidated.
822   StoreModuleDesc = forcePrintModuleIR() && shouldPrintAfterSomePass();
823   if (shouldPrintBeforeSomePass() || StoreModuleDesc)
824     PIC.registerBeforeNonSkippedPassCallback(
825         [this](StringRef P, Any IR) { this->printBeforePass(P, IR); });
826 
827   if (shouldPrintAfterSomePass()) {
828     PIC.registerAfterPassCallback(
829         [this](StringRef P, Any IR, const PreservedAnalyses &) {
830           this->printAfterPass(P, IR);
831         });
832     PIC.registerAfterPassInvalidatedCallback(
833         [this](StringRef P, const PreservedAnalyses &) {
834           this->printAfterPassInvalidated(P);
835         });
836   }
837 }
838 
839 void OptNoneInstrumentation::registerCallbacks(
840     PassInstrumentationCallbacks &PIC) {
841   PIC.registerShouldRunOptionalPassCallback(
842       [this](StringRef P, Any IR) { return this->shouldRun(P, IR); });
843 }
844 
845 bool OptNoneInstrumentation::shouldRun(StringRef PassID, Any IR) {
846   const Function *F = nullptr;
847   if (any_isa<const Function *>(IR)) {
848     F = any_cast<const Function *>(IR);
849   } else if (any_isa<const Loop *>(IR)) {
850     F = any_cast<const Loop *>(IR)->getHeader()->getParent();
851   }
852   bool ShouldRun = !(F && F->hasOptNone());
853   if (!ShouldRun && DebugLogging) {
854     errs() << "Skipping pass " << PassID << " on " << F->getName()
855            << " due to optnone attribute\n";
856   }
857   return ShouldRun;
858 }
859 
860 void OptBisectInstrumentation::registerCallbacks(
861     PassInstrumentationCallbacks &PIC) {
862   if (!OptBisector->isEnabled())
863     return;
864   PIC.registerShouldRunOptionalPassCallback([](StringRef PassID, Any IR) {
865     return isIgnored(PassID) || OptBisector->checkPass(PassID, getIRName(IR));
866   });
867 }
868 
869 void PrintPassInstrumentation::registerCallbacks(
870     PassInstrumentationCallbacks &PIC) {
871   if (!DebugLogging)
872     return;
873 
874   std::vector<StringRef> SpecialPasses = {"PassManager"};
875   if (!DebugPMVerbose)
876     SpecialPasses.emplace_back("PassAdaptor");
877 
878   PIC.registerBeforeSkippedPassCallback(
879       [SpecialPasses](StringRef PassID, Any IR) {
880         assert(!isSpecialPass(PassID, SpecialPasses) &&
881                "Unexpectedly skipping special pass");
882 
883         dbgs() << "Skipping pass: " << PassID << " on " << getIRName(IR)
884                << "\n";
885       });
886 
887   PIC.registerBeforeNonSkippedPassCallback(
888       [SpecialPasses](StringRef PassID, Any IR) {
889         if (isSpecialPass(PassID, SpecialPasses))
890           return;
891 
892         dbgs() << "Running pass: " << PassID << " on " << getIRName(IR) << "\n";
893       });
894 
895   PIC.registerBeforeAnalysisCallback([](StringRef PassID, Any IR) {
896     dbgs() << "Running analysis: " << PassID << " on " << getIRName(IR) << "\n";
897   });
898 }
899 
900 PreservedCFGCheckerInstrumentation::CFG::CFG(const Function *F,
901                                              bool TrackBBLifetime) {
902   if (TrackBBLifetime)
903     BBGuards = DenseMap<intptr_t, BBGuard>(F->size());
904   for (const auto &BB : *F) {
905     if (BBGuards)
906       BBGuards->try_emplace(intptr_t(&BB), &BB);
907     for (auto *Succ : successors(&BB)) {
908       Graph[&BB][Succ]++;
909       if (BBGuards)
910         BBGuards->try_emplace(intptr_t(Succ), Succ);
911     }
912   }
913 }
914 
915 static void printBBName(raw_ostream &out, const BasicBlock *BB) {
916   if (BB->hasName()) {
917     out << BB->getName() << "<" << BB << ">";
918     return;
919   }
920 
921   if (!BB->getParent()) {
922     out << "unnamed_removed<" << BB << ">";
923     return;
924   }
925 
926   if (BB == &BB->getParent()->getEntryBlock()) {
927     out << "entry"
928         << "<" << BB << ">";
929     return;
930   }
931 
932   unsigned FuncOrderBlockNum = 0;
933   for (auto &FuncBB : *BB->getParent()) {
934     if (&FuncBB == BB)
935       break;
936     FuncOrderBlockNum++;
937   }
938   out << "unnamed_" << FuncOrderBlockNum << "<" << BB << ">";
939 }
940 
941 void PreservedCFGCheckerInstrumentation::CFG::printDiff(raw_ostream &out,
942                                                         const CFG &Before,
943                                                         const CFG &After) {
944   assert(!After.isPoisoned());
945   if (Before.isPoisoned()) {
946     out << "Some blocks were deleted\n";
947     return;
948   }
949 
950   // Find and print graph differences.
951   if (Before.Graph.size() != After.Graph.size())
952     out << "Different number of non-leaf basic blocks: before="
953         << Before.Graph.size() << ", after=" << After.Graph.size() << "\n";
954 
955   for (auto &BB : Before.Graph) {
956     auto BA = After.Graph.find(BB.first);
957     if (BA == After.Graph.end()) {
958       out << "Non-leaf block ";
959       printBBName(out, BB.first);
960       out << " is removed (" << BB.second.size() << " successors)\n";
961     }
962   }
963 
964   for (auto &BA : After.Graph) {
965     auto BB = Before.Graph.find(BA.first);
966     if (BB == Before.Graph.end()) {
967       out << "Non-leaf block ";
968       printBBName(out, BA.first);
969       out << " is added (" << BA.second.size() << " successors)\n";
970       continue;
971     }
972 
973     if (BB->second == BA.second)
974       continue;
975 
976     out << "Different successors of block ";
977     printBBName(out, BA.first);
978     out << " (unordered):\n";
979     out << "- before (" << BB->second.size() << "): ";
980     for (auto &SuccB : BB->second) {
981       printBBName(out, SuccB.first);
982       if (SuccB.second != 1)
983         out << "(" << SuccB.second << "), ";
984       else
985         out << ", ";
986     }
987     out << "\n";
988     out << "- after (" << BA.second.size() << "): ";
989     for (auto &SuccA : BA.second) {
990       printBBName(out, SuccA.first);
991       if (SuccA.second != 1)
992         out << "(" << SuccA.second << "), ";
993       else
994         out << ", ";
995     }
996     out << "\n";
997   }
998 }
999 
1000 // PreservedCFGCheckerInstrumentation uses PreservedCFGCheckerAnalysis to check
1001 // passes, that reported they kept CFG analyses up-to-date, did not actually
1002 // change CFG. This check is done as follows. Before every functional pass in
1003 // BeforeNonSkippedPassCallback a CFG snapshot (an instance of
1004 // PreservedCFGCheckerInstrumentation::CFG) is requested from
1005 // FunctionAnalysisManager as a result of PreservedCFGCheckerAnalysis. When the
1006 // functional pass finishes and reports that CFGAnalyses or AllAnalyses are
1007 // up-to-date then the cached result of PreservedCFGCheckerAnalysis (if
1008 // available) is checked to be equal to a freshly created CFG snapshot.
1009 struct PreservedCFGCheckerAnalysis
1010     : public AnalysisInfoMixin<PreservedCFGCheckerAnalysis> {
1011   friend AnalysisInfoMixin<PreservedCFGCheckerAnalysis>;
1012 
1013   static AnalysisKey Key;
1014 
1015 public:
1016   /// Provide the result type for this analysis pass.
1017   using Result = PreservedCFGCheckerInstrumentation::CFG;
1018 
1019   /// Run the analysis pass over a function and produce CFG.
1020   Result run(Function &F, FunctionAnalysisManager &FAM) {
1021     return Result(&F, /* TrackBBLifetime */ true);
1022   }
1023 };
1024 
1025 AnalysisKey PreservedCFGCheckerAnalysis::Key;
1026 
1027 bool PreservedCFGCheckerInstrumentation::CFG::invalidate(
1028     Function &F, const PreservedAnalyses &PA,
1029     FunctionAnalysisManager::Invalidator &) {
1030   auto PAC = PA.getChecker<PreservedCFGCheckerAnalysis>();
1031   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>() ||
1032            PAC.preservedSet<CFGAnalyses>());
1033 }
1034 
1035 void PreservedCFGCheckerInstrumentation::registerCallbacks(
1036     PassInstrumentationCallbacks &PIC, FunctionAnalysisManager &FAM) {
1037   if (!VerifyPreservedCFG)
1038     return;
1039 
1040   FAM.registerPass([&] { return PreservedCFGCheckerAnalysis(); });
1041 
1042   auto checkCFG = [](StringRef Pass, StringRef FuncName, const CFG &GraphBefore,
1043                      const CFG &GraphAfter) {
1044     if (GraphAfter == GraphBefore)
1045       return;
1046 
1047     dbgs() << "Error: " << Pass
1048            << " does not invalidate CFG analyses but CFG changes detected in "
1049               "function @"
1050            << FuncName << ":\n";
1051     CFG::printDiff(dbgs(), GraphBefore, GraphAfter);
1052     report_fatal_error(Twine("CFG unexpectedly changed by ", Pass));
1053   };
1054 
1055   PIC.registerBeforeNonSkippedPassCallback(
1056       [this, &FAM](StringRef P, Any IR) {
1057         assert(&PassStack.emplace_back(P));
1058         (void)this;
1059         if (!any_isa<const Function *>(IR))
1060           return;
1061 
1062         const auto *F = any_cast<const Function *>(IR);
1063         // Make sure a fresh CFG snapshot is available before the pass.
1064         FAM.getResult<PreservedCFGCheckerAnalysis>(*const_cast<Function *>(F));
1065       });
1066 
1067   PIC.registerAfterPassInvalidatedCallback(
1068       [this](StringRef P, const PreservedAnalyses &PassPA) {
1069         assert(PassStack.pop_back_val() == P &&
1070                "Before and After callbacks must correspond");
1071         (void)this;
1072       });
1073 
1074   PIC.registerAfterPassCallback([this, &FAM,
1075                                  checkCFG](StringRef P, Any IR,
1076                                            const PreservedAnalyses &PassPA) {
1077     assert(PassStack.pop_back_val() == P &&
1078            "Before and After callbacks must correspond");
1079     (void)this;
1080 
1081     if (!any_isa<const Function *>(IR))
1082       return;
1083 
1084     if (!PassPA.allAnalysesInSetPreserved<CFGAnalyses>() &&
1085         !PassPA.allAnalysesInSetPreserved<AllAnalysesOn<Function>>())
1086       return;
1087 
1088     const auto *F = any_cast<const Function *>(IR);
1089     if (auto *GraphBefore = FAM.getCachedResult<PreservedCFGCheckerAnalysis>(
1090             *const_cast<Function *>(F)))
1091       checkCFG(P, F->getName(), *GraphBefore,
1092                CFG(F, /* TrackBBLifetime */ false));
1093   });
1094 }
1095 
1096 void VerifyInstrumentation::registerCallbacks(
1097     PassInstrumentationCallbacks &PIC) {
1098   PIC.registerAfterPassCallback(
1099       [this](StringRef P, Any IR, const PreservedAnalyses &PassPA) {
1100         if (isIgnored(P) || P == "VerifierPass")
1101           return;
1102         if (any_isa<const Function *>(IR) || any_isa<const Loop *>(IR)) {
1103           const Function *F;
1104           if (any_isa<const Loop *>(IR))
1105             F = any_cast<const Loop *>(IR)->getHeader()->getParent();
1106           else
1107             F = any_cast<const Function *>(IR);
1108           if (DebugLogging)
1109             dbgs() << "Verifying function " << F->getName() << "\n";
1110 
1111           if (verifyFunction(*F))
1112             report_fatal_error("Broken function found, compilation aborted!");
1113         } else if (any_isa<const Module *>(IR) ||
1114                    any_isa<const LazyCallGraph::SCC *>(IR)) {
1115           const Module *M;
1116           if (any_isa<const LazyCallGraph::SCC *>(IR))
1117             M = any_cast<const LazyCallGraph::SCC *>(IR)
1118                     ->begin()
1119                     ->getFunction()
1120                     .getParent();
1121           else
1122             M = any_cast<const Module *>(IR);
1123           if (DebugLogging)
1124             dbgs() << "Verifying module " << M->getName() << "\n";
1125 
1126           if (verifyModule(*M))
1127             report_fatal_error("Broken module found, compilation aborted!");
1128         }
1129       });
1130 }
1131 
1132 InLineChangePrinter::~InLineChangePrinter() {}
1133 
1134 void InLineChangePrinter::generateIRRepresentation(Any IR, StringRef PassID,
1135                                                    ChangedIRData &D) {
1136   ChangedIRComparer::analyzeIR(IR, D);
1137 }
1138 
1139 void InLineChangePrinter::handleAfter(StringRef PassID, std::string &Name,
1140                                       const ChangedIRData &Before,
1141                                       const ChangedIRData &After, Any IR) {
1142   SmallString<20> Banner =
1143       formatv("*** IR Dump After {0} on {1} ***\n", PassID, Name);
1144   Out << Banner;
1145   ChangedIRComparer(Out, Before, After, UseColour)
1146       .compare(IR, "", PassID, Name);
1147   Out << "\n";
1148 }
1149 
1150 bool InLineChangePrinter::same(const ChangedIRData &D1,
1151                                const ChangedIRData &D2) {
1152   return D1 == D2;
1153 }
1154 
1155 void ChangedIRComparer::handleFunctionCompare(StringRef Name, StringRef Prefix,
1156                                               StringRef PassID, bool InModule,
1157                                               const ChangedFuncData &Before,
1158                                               const ChangedFuncData &After) {
1159   // Print a banner when this is being shown in the context of a module
1160   if (InModule)
1161     Out << "\n*** IR for function " << Name << " ***\n";
1162 
1163   ChangedFuncData::report(
1164       Before, After, [&](const ChangedBlockData *B, const ChangedBlockData *A) {
1165         StringRef BStr = B ? B->getBody() : "\n";
1166         StringRef AStr = A ? A->getBody() : "\n";
1167         const std::string Removed =
1168             UseColour ? "\033[31m-%l\033[0m\n" : "-%l\n";
1169         const std::string Added = UseColour ? "\033[32m+%l\033[0m\n" : "+%l\n";
1170         const std::string NoChange = " %l\n";
1171         Out << doSystemDiff(BStr, AStr, Removed, Added, NoChange);
1172       });
1173 }
1174 
1175 void InLineChangePrinter::registerCallbacks(PassInstrumentationCallbacks &PIC) {
1176   if (PrintChanged == ChangePrinter::PrintChangedDiffVerbose ||
1177       PrintChanged == ChangePrinter::PrintChangedDiffQuiet ||
1178       PrintChanged == ChangePrinter::PrintChangedColourDiffVerbose ||
1179       PrintChanged == ChangePrinter::PrintChangedColourDiffQuiet)
1180     TextChangeReporter<ChangedIRData>::registerRequiredCallbacks(PIC);
1181 }
1182 
1183 StandardInstrumentations::StandardInstrumentations(bool DebugLogging,
1184                                                    bool VerifyEach)
1185     : PrintPass(DebugLogging), OptNone(DebugLogging),
1186       PrintChangedIR(PrintChanged == ChangePrinter::PrintChangedVerbose),
1187       PrintChangedDiff(
1188           PrintChanged == ChangePrinter::PrintChangedDiffVerbose ||
1189               PrintChanged == ChangePrinter::PrintChangedColourDiffVerbose,
1190           PrintChanged == ChangePrinter::PrintChangedColourDiffVerbose ||
1191               PrintChanged == ChangePrinter::PrintChangedColourDiffQuiet),
1192       Verify(DebugLogging), VerifyEach(VerifyEach) {}
1193 
1194 void StandardInstrumentations::registerCallbacks(
1195     PassInstrumentationCallbacks &PIC, FunctionAnalysisManager *FAM) {
1196   PrintIR.registerCallbacks(PIC);
1197   PrintPass.registerCallbacks(PIC);
1198   TimePasses.registerCallbacks(PIC);
1199   OptNone.registerCallbacks(PIC);
1200   OptBisect.registerCallbacks(PIC);
1201   if (FAM)
1202     PreservedCFGChecker.registerCallbacks(PIC, *FAM);
1203   PrintChangedIR.registerCallbacks(PIC);
1204   PseudoProbeVerification.registerCallbacks(PIC);
1205   if (VerifyEach)
1206     Verify.registerCallbacks(PIC);
1207   PrintChangedDiff.registerCallbacks(PIC);
1208 }
1209 
1210 namespace llvm {
1211 
1212 template class ChangeReporter<std::string>;
1213 template class TextChangeReporter<std::string>;
1214 
1215 template class ChangeReporter<ChangedIRData>;
1216 template class TextChangeReporter<ChangedIRData>;
1217 
1218 } // namespace llvm
1219