Path: blob/main/contrib/llvm-project/llvm/lib/Passes/StandardInstrumentations.cpp
35262 views
//===- Standard pass instrumentations handling ----------------*- C++ -*--===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7/// \file8///9/// This file defines IR-printing pass instrumentation callbacks as well as10/// StandardInstrumentations class that manages standard pass instrumentations.11///12//===----------------------------------------------------------------------===//1314#include "llvm/Passes/StandardInstrumentations.h"15#include "llvm/ADT/Any.h"16#include "llvm/ADT/StableHashing.h"17#include "llvm/ADT/StringRef.h"18#include "llvm/Analysis/CallGraphSCCPass.h"19#include "llvm/Analysis/LazyCallGraph.h"20#include "llvm/Analysis/LoopInfo.h"21#include "llvm/CodeGen/MIRPrinter.h"22#include "llvm/CodeGen/MachineFunction.h"23#include "llvm/CodeGen/MachineModuleInfo.h"24#include "llvm/CodeGen/MachineVerifier.h"25#include "llvm/IR/Constants.h"26#include "llvm/IR/Function.h"27#include "llvm/IR/Module.h"28#include "llvm/IR/PassInstrumentation.h"29#include "llvm/IR/PassManager.h"30#include "llvm/IR/PrintPasses.h"31#include "llvm/IR/StructuralHash.h"32#include "llvm/IR/Verifier.h"33#include "llvm/Support/CommandLine.h"34#include "llvm/Support/CrashRecoveryContext.h"35#include "llvm/Support/Debug.h"36#include "llvm/Support/Error.h"37#include "llvm/Support/FormatVariadic.h"38#include "llvm/Support/GraphWriter.h"39#include "llvm/Support/MemoryBuffer.h"40#include "llvm/Support/Path.h"41#include "llvm/Support/Program.h"42#include "llvm/Support/Regex.h"43#include "llvm/Support/Signals.h"44#include "llvm/Support/raw_ostream.h"45#include <unordered_map>46#include <unordered_set>47#include <utility>48#include <vector>4950using namespace llvm;5152static cl::opt<bool> VerifyAnalysisInvalidation("verify-analysis-invalidation",53cl::Hidden,54#ifdef EXPENSIVE_CHECKS55cl::init(true)56#else57cl::init(false)58#endif59);6061// An option that supports the -print-changed option. See62// the description for -print-changed for an explanation of the use63// of this option. Note that this option has no effect without -print-changed.64static cl::opt<bool>65PrintChangedBefore("print-before-changed",66cl::desc("Print before passes that change them"),67cl::init(false), cl::Hidden);6869// An option for specifying the dot used by70// print-changed=[dot-cfg | dot-cfg-quiet]71static cl::opt<std::string>72DotBinary("print-changed-dot-path", cl::Hidden, cl::init("dot"),73cl::desc("system dot used by change reporters"));7475// An option that determines the colour used for elements that are only76// in the before part. Must be a colour named in appendix J of77// https://graphviz.org/pdf/dotguide.pdf78static cl::opt<std::string>79BeforeColour("dot-cfg-before-color",80cl::desc("Color for dot-cfg before elements"), cl::Hidden,81cl::init("red"));82// An option that determines the colour used for elements that are only83// in the after part. Must be a colour named in appendix J of84// https://graphviz.org/pdf/dotguide.pdf85static cl::opt<std::string>86AfterColour("dot-cfg-after-color",87cl::desc("Color for dot-cfg after elements"), cl::Hidden,88cl::init("forestgreen"));89// An option that determines the colour used for elements that are in both90// the before and after parts. Must be a colour named in appendix J of91// https://graphviz.org/pdf/dotguide.pdf92static cl::opt<std::string>93CommonColour("dot-cfg-common-color",94cl::desc("Color for dot-cfg common elements"), cl::Hidden,95cl::init("black"));9697// An option that determines where the generated website file (named98// passes.html) and the associated pdf files (named diff_*.pdf) are saved.99static cl::opt<std::string> DotCfgDir(100"dot-cfg-dir",101cl::desc("Generate dot files into specified directory for changed IRs"),102cl::Hidden, cl::init("./"));103104// Options to print the IR that was being processed when a pass crashes.105static cl::opt<std::string> PrintOnCrashPath(106"print-on-crash-path",107cl::desc("Print the last form of the IR before crash to a file"),108cl::Hidden);109110static cl::opt<bool> PrintOnCrash(111"print-on-crash",112cl::desc("Print the last form of the IR before crash (use -print-on-crash-path to dump to a file)"),113cl::Hidden);114115static cl::opt<std::string> OptBisectPrintIRPath(116"opt-bisect-print-ir-path",117cl::desc("Print IR to path when opt-bisect-limit is reached"), cl::Hidden);118119static cl::opt<bool> PrintPassNumbers(120"print-pass-numbers", cl::init(false), cl::Hidden,121cl::desc("Print pass names and their ordinals"));122123static cl::opt<unsigned> PrintBeforePassNumber(124"print-before-pass-number", cl::init(0), cl::Hidden,125cl::desc("Print IR before the pass with this number as "126"reported by print-pass-numbers"));127128static cl::opt<unsigned>129PrintAfterPassNumber("print-after-pass-number", cl::init(0), cl::Hidden,130cl::desc("Print IR after the pass with this number as "131"reported by print-pass-numbers"));132133static cl::opt<std::string> IRDumpDirectory(134"ir-dump-directory",135cl::desc("If specified, IR printed using the "136"-print-[before|after]{-all} options will be dumped into "137"files in this directory rather than written to stderr"),138cl::Hidden, cl::value_desc("filename"));139140template <typename IRUnitT> static const IRUnitT *unwrapIR(Any IR) {141const IRUnitT **IRPtr = llvm::any_cast<const IRUnitT *>(&IR);142return IRPtr ? *IRPtr : nullptr;143}144145namespace {146147// An option for specifying an executable that will be called with the IR148// everytime it changes in the opt pipeline. It will also be called on149// the initial IR as it enters the pipeline. The executable will be passed150// the name of a temporary file containing the IR and the PassID. This may151// be used, for example, to call llc on the IR and run a test to determine152// which pass makes a change that changes the functioning of the IR.153// The usual modifier options work as expected.154static cl::opt<std::string>155TestChanged("exec-on-ir-change", cl::Hidden, cl::init(""),156cl::desc("exe called with module IR after each pass that "157"changes it"));158159/// Extract Module out of \p IR unit. May return nullptr if \p IR does not match160/// certain global filters. Will never return nullptr if \p Force is true.161const Module *unwrapModule(Any IR, bool Force = false) {162if (const auto *M = unwrapIR<Module>(IR))163return M;164165if (const auto *F = unwrapIR<Function>(IR)) {166if (!Force && !isFunctionInPrintList(F->getName()))167return nullptr;168169return F->getParent();170}171172if (const auto *C = unwrapIR<LazyCallGraph::SCC>(IR)) {173for (const LazyCallGraph::Node &N : *C) {174const Function &F = N.getFunction();175if (Force || (!F.isDeclaration() && isFunctionInPrintList(F.getName()))) {176return F.getParent();177}178}179assert(!Force && "Expected a module");180return nullptr;181}182183if (const auto *L = unwrapIR<Loop>(IR)) {184const Function *F = L->getHeader()->getParent();185if (!Force && !isFunctionInPrintList(F->getName()))186return nullptr;187return F->getParent();188}189190if (const auto *MF = unwrapIR<MachineFunction>(IR)) {191if (!Force && !isFunctionInPrintList(MF->getName()))192return nullptr;193return MF->getFunction().getParent();194}195196llvm_unreachable("Unknown IR unit");197}198199void printIR(raw_ostream &OS, const Function *F) {200if (!isFunctionInPrintList(F->getName()))201return;202OS << *F;203}204205void printIR(raw_ostream &OS, const Module *M) {206if (isFunctionInPrintList("*") || forcePrintModuleIR()) {207M->print(OS, nullptr);208} else {209for (const auto &F : M->functions()) {210printIR(OS, &F);211}212}213}214215void printIR(raw_ostream &OS, const LazyCallGraph::SCC *C) {216for (const LazyCallGraph::Node &N : *C) {217const Function &F = N.getFunction();218if (!F.isDeclaration() && isFunctionInPrintList(F.getName())) {219F.print(OS);220}221}222}223224void printIR(raw_ostream &OS, const Loop *L) {225const Function *F = L->getHeader()->getParent();226if (!isFunctionInPrintList(F->getName()))227return;228printLoop(const_cast<Loop &>(*L), OS);229}230231void printIR(raw_ostream &OS, const MachineFunction *MF) {232if (!isFunctionInPrintList(MF->getName()))233return;234MF->print(OS);235}236237std::string getIRName(Any IR) {238if (unwrapIR<Module>(IR))239return "[module]";240241if (const auto *F = unwrapIR<Function>(IR))242return F->getName().str();243244if (const auto *C = unwrapIR<LazyCallGraph::SCC>(IR))245return C->getName();246247if (const auto *L = unwrapIR<Loop>(IR))248return "loop %" + L->getName().str() + " in function " +249L->getHeader()->getParent()->getName().str();250251if (const auto *MF = unwrapIR<MachineFunction>(IR))252return MF->getName().str();253254llvm_unreachable("Unknown wrapped IR type");255}256257bool moduleContainsFilterPrintFunc(const Module &M) {258return any_of(M.functions(),259[](const Function &F) {260return isFunctionInPrintList(F.getName());261}) ||262isFunctionInPrintList("*");263}264265bool sccContainsFilterPrintFunc(const LazyCallGraph::SCC &C) {266return any_of(C,267[](const LazyCallGraph::Node &N) {268return isFunctionInPrintList(N.getName());269}) ||270isFunctionInPrintList("*");271}272273bool shouldPrintIR(Any IR) {274if (const auto *M = unwrapIR<Module>(IR))275return moduleContainsFilterPrintFunc(*M);276277if (const auto *F = unwrapIR<Function>(IR))278return isFunctionInPrintList(F->getName());279280if (const auto *C = unwrapIR<LazyCallGraph::SCC>(IR))281return sccContainsFilterPrintFunc(*C);282283if (const auto *L = unwrapIR<Loop>(IR))284return isFunctionInPrintList(L->getHeader()->getParent()->getName());285286if (const auto *MF = unwrapIR<MachineFunction>(IR))287return isFunctionInPrintList(MF->getName());288llvm_unreachable("Unknown wrapped IR type");289}290291/// Generic IR-printing helper that unpacks a pointer to IRUnit wrapped into292/// Any and does actual print job.293void unwrapAndPrint(raw_ostream &OS, Any IR) {294if (!shouldPrintIR(IR))295return;296297if (forcePrintModuleIR()) {298auto *M = unwrapModule(IR);299assert(M && "should have unwrapped module");300printIR(OS, M);301return;302}303304if (const auto *M = unwrapIR<Module>(IR)) {305printIR(OS, M);306return;307}308309if (const auto *F = unwrapIR<Function>(IR)) {310printIR(OS, F);311return;312}313314if (const auto *C = unwrapIR<LazyCallGraph::SCC>(IR)) {315printIR(OS, C);316return;317}318319if (const auto *L = unwrapIR<Loop>(IR)) {320printIR(OS, L);321return;322}323324if (const auto *MF = unwrapIR<MachineFunction>(IR)) {325printIR(OS, MF);326return;327}328llvm_unreachable("Unknown wrapped IR type");329}330331// Return true when this is a pass for which changes should be ignored332bool isIgnored(StringRef PassID) {333return isSpecialPass(PassID,334{"PassManager", "PassAdaptor", "AnalysisManagerProxy",335"DevirtSCCRepeatedPass", "ModuleInlinerWrapperPass",336"VerifierPass", "PrintModulePass", "PrintMIRPass",337"PrintMIRPreparePass"});338}339340std::string makeHTMLReady(StringRef SR) {341std::string S;342while (true) {343StringRef Clean =344SR.take_until([](char C) { return C == '<' || C == '>'; });345S.append(Clean.str());346SR = SR.drop_front(Clean.size());347if (SR.size() == 0)348return S;349S.append(SR[0] == '<' ? "<" : ">");350SR = SR.drop_front();351}352llvm_unreachable("problems converting string to HTML");353}354355// Return the module when that is the appropriate level of comparison for \p IR.356const Module *getModuleForComparison(Any IR) {357if (const auto *M = unwrapIR<Module>(IR))358return M;359if (const auto *C = unwrapIR<LazyCallGraph::SCC>(IR))360return C->begin()->getFunction().getParent();361return nullptr;362}363364bool isInterestingFunction(const Function &F) {365return isFunctionInPrintList(F.getName());366}367368// Return true when this is a pass on IR for which printing369// of changes is desired.370bool isInteresting(Any IR, StringRef PassID, StringRef PassName) {371if (isIgnored(PassID) || !isPassInPrintList(PassName))372return false;373if (const auto *F = unwrapIR<Function>(IR))374return isInterestingFunction(*F);375return true;376}377378} // namespace379380template <typename T> ChangeReporter<T>::~ChangeReporter() {381assert(BeforeStack.empty() && "Problem with Change Printer stack.");382}383384template <typename T>385void ChangeReporter<T>::saveIRBeforePass(Any IR, StringRef PassID,386StringRef PassName) {387// Is this the initial IR?388if (InitialIR) {389InitialIR = false;390if (VerboseMode)391handleInitialIR(IR);392}393394// Always need to place something on the stack because invalidated passes395// are not given the IR so it cannot be determined whether the pass was for396// something that was filtered out.397BeforeStack.emplace_back();398399if (!isInteresting(IR, PassID, PassName))400return;401402// Save the IR representation on the stack.403T &Data = BeforeStack.back();404generateIRRepresentation(IR, PassID, Data);405}406407template <typename T>408void ChangeReporter<T>::handleIRAfterPass(Any IR, StringRef PassID,409StringRef PassName) {410assert(!BeforeStack.empty() && "Unexpected empty stack encountered.");411412std::string Name = getIRName(IR);413414if (isIgnored(PassID)) {415if (VerboseMode)416handleIgnored(PassID, Name);417} else if (!isInteresting(IR, PassID, PassName)) {418if (VerboseMode)419handleFiltered(PassID, Name);420} else {421// Get the before rep from the stack422T &Before = BeforeStack.back();423// Create the after rep424T After;425generateIRRepresentation(IR, PassID, After);426427// Was there a change in IR?428if (Before == After) {429if (VerboseMode)430omitAfter(PassID, Name);431} else432handleAfter(PassID, Name, Before, After, IR);433}434BeforeStack.pop_back();435}436437template <typename T>438void ChangeReporter<T>::handleInvalidatedPass(StringRef PassID) {439assert(!BeforeStack.empty() && "Unexpected empty stack encountered.");440441// Always flag it as invalidated as we cannot determine when442// a pass for a filtered function is invalidated since we do not443// get the IR in the call. Also, the output is just alternate444// forms of the banner anyway.445if (VerboseMode)446handleInvalidated(PassID);447BeforeStack.pop_back();448}449450template <typename T>451void ChangeReporter<T>::registerRequiredCallbacks(452PassInstrumentationCallbacks &PIC) {453PIC.registerBeforeNonSkippedPassCallback([&PIC, this](StringRef P, Any IR) {454saveIRBeforePass(IR, P, PIC.getPassNameForClassName(P));455});456457PIC.registerAfterPassCallback(458[&PIC, this](StringRef P, Any IR, const PreservedAnalyses &) {459handleIRAfterPass(IR, P, PIC.getPassNameForClassName(P));460});461PIC.registerAfterPassInvalidatedCallback(462[this](StringRef P, const PreservedAnalyses &) {463handleInvalidatedPass(P);464});465}466467template <typename T>468TextChangeReporter<T>::TextChangeReporter(bool Verbose)469: ChangeReporter<T>(Verbose), Out(dbgs()) {}470471template <typename T> void TextChangeReporter<T>::handleInitialIR(Any IR) {472// Always print the module.473// Unwrap and print directly to avoid filtering problems in general routines.474auto *M = unwrapModule(IR, /*Force=*/true);475assert(M && "Expected module to be unwrapped when forced.");476Out << "*** IR Dump At Start ***\n";477M->print(Out, nullptr);478}479480template <typename T>481void TextChangeReporter<T>::omitAfter(StringRef PassID, std::string &Name) {482Out << formatv("*** IR Dump After {0} on {1} omitted because no change ***\n",483PassID, Name);484}485486template <typename T>487void TextChangeReporter<T>::handleInvalidated(StringRef PassID) {488Out << formatv("*** IR Pass {0} invalidated ***\n", PassID);489}490491template <typename T>492void TextChangeReporter<T>::handleFiltered(StringRef PassID,493std::string &Name) {494SmallString<20> Banner =495formatv("*** IR Dump After {0} on {1} filtered out ***\n", PassID, Name);496Out << Banner;497}498499template <typename T>500void TextChangeReporter<T>::handleIgnored(StringRef PassID, std::string &Name) {501Out << formatv("*** IR Pass {0} on {1} ignored ***\n", PassID, Name);502}503504IRChangedPrinter::~IRChangedPrinter() = default;505506void IRChangedPrinter::registerCallbacks(PassInstrumentationCallbacks &PIC) {507if (PrintChanged == ChangePrinter::Verbose ||508PrintChanged == ChangePrinter::Quiet)509TextChangeReporter<std::string>::registerRequiredCallbacks(PIC);510}511512void IRChangedPrinter::generateIRRepresentation(Any IR, StringRef PassID,513std::string &Output) {514raw_string_ostream OS(Output);515unwrapAndPrint(OS, IR);516OS.str();517}518519void IRChangedPrinter::handleAfter(StringRef PassID, std::string &Name,520const std::string &Before,521const std::string &After, Any) {522// Report the IR before the changes when requested.523if (PrintChangedBefore)524Out << "*** IR Dump Before " << PassID << " on " << Name << " ***\n"525<< Before;526527// We might not get anything to print if we only want to print a specific528// function but it gets deleted.529if (After.empty()) {530Out << "*** IR Deleted After " << PassID << " on " << Name << " ***\n";531return;532}533534Out << "*** IR Dump After " << PassID << " on " << Name << " ***\n" << After;535}536537IRChangedTester::~IRChangedTester() {}538539void IRChangedTester::registerCallbacks(PassInstrumentationCallbacks &PIC) {540if (TestChanged != "")541TextChangeReporter<std::string>::registerRequiredCallbacks(PIC);542}543544void IRChangedTester::handleIR(const std::string &S, StringRef PassID) {545// Store the body into a temporary file546static SmallVector<int> FD{-1};547SmallVector<StringRef> SR{S};548static SmallVector<std::string> FileName{""};549if (prepareTempFiles(FD, SR, FileName)) {550dbgs() << "Unable to create temporary file.";551return;552}553static ErrorOr<std::string> Exe = sys::findProgramByName(TestChanged);554if (!Exe) {555dbgs() << "Unable to find test-changed executable.";556return;557}558559StringRef Args[] = {TestChanged, FileName[0], PassID};560int Result = sys::ExecuteAndWait(*Exe, Args);561if (Result < 0) {562dbgs() << "Error executing test-changed executable.";563return;564}565566if (cleanUpTempFiles(FileName))567dbgs() << "Unable to remove temporary file.";568}569570void IRChangedTester::handleInitialIR(Any IR) {571// Always test the initial module.572// Unwrap and print directly to avoid filtering problems in general routines.573std::string S;574generateIRRepresentation(IR, "Initial IR", S);575handleIR(S, "Initial IR");576}577578void IRChangedTester::omitAfter(StringRef PassID, std::string &Name) {}579void IRChangedTester::handleInvalidated(StringRef PassID) {}580void IRChangedTester::handleFiltered(StringRef PassID, std::string &Name) {}581void IRChangedTester::handleIgnored(StringRef PassID, std::string &Name) {}582void IRChangedTester::handleAfter(StringRef PassID, std::string &Name,583const std::string &Before,584const std::string &After, Any) {585handleIR(After, PassID);586}587588template <typename T>589void OrderedChangedData<T>::report(590const OrderedChangedData &Before, const OrderedChangedData &After,591function_ref<void(const T *, const T *)> HandlePair) {592const auto &BFD = Before.getData();593const auto &AFD = After.getData();594std::vector<std::string>::const_iterator BI = Before.getOrder().begin();595std::vector<std::string>::const_iterator BE = Before.getOrder().end();596std::vector<std::string>::const_iterator AI = After.getOrder().begin();597std::vector<std::string>::const_iterator AE = After.getOrder().end();598599auto HandlePotentiallyRemovedData = [&](std::string S) {600// The order in LLVM may have changed so check if still exists.601if (!AFD.count(S)) {602// This has been removed.603HandlePair(&BFD.find(*BI)->getValue(), nullptr);604}605};606auto HandleNewData = [&](std::vector<const T *> &Q) {607// Print out any queued up new sections608for (const T *NBI : Q)609HandlePair(nullptr, NBI);610Q.clear();611};612613// Print out the data in the after order, with before ones interspersed614// appropriately (ie, somewhere near where they were in the before list).615// Start at the beginning of both lists. Loop through the616// after list. If an element is common, then advance in the before list617// reporting the removed ones until the common one is reached. Report any618// queued up new ones and then report the common one. If an element is not619// common, then enqueue it for reporting. When the after list is exhausted,620// loop through the before list, reporting any removed ones. Finally,621// report the rest of the enqueued new ones.622std::vector<const T *> NewDataQueue;623while (AI != AE) {624if (!BFD.count(*AI)) {625// This section is new so place it in the queue. This will cause it626// to be reported after deleted sections.627NewDataQueue.emplace_back(&AFD.find(*AI)->getValue());628++AI;629continue;630}631// This section is in both; advance and print out any before-only632// until we get to it.633// It's possible that this section has moved to be later than before. This634// will mess up printing most blocks side by side, but it's a rare case and635// it's better than crashing.636while (BI != BE && *BI != *AI) {637HandlePotentiallyRemovedData(*BI);638++BI;639}640// Report any new sections that were queued up and waiting.641HandleNewData(NewDataQueue);642643const T &AData = AFD.find(*AI)->getValue();644const T &BData = BFD.find(*AI)->getValue();645HandlePair(&BData, &AData);646if (BI != BE)647++BI;648++AI;649}650651// Check any remaining before sections to see if they have been removed652while (BI != BE) {653HandlePotentiallyRemovedData(*BI);654++BI;655}656657HandleNewData(NewDataQueue);658}659660template <typename T>661void IRComparer<T>::compare(662bool CompareModule,663std::function<void(bool InModule, unsigned Minor,664const FuncDataT<T> &Before, const FuncDataT<T> &After)>665CompareFunc) {666if (!CompareModule) {667// Just handle the single function.668assert(Before.getData().size() == 1 && After.getData().size() == 1 &&669"Expected only one function.");670CompareFunc(false, 0, Before.getData().begin()->getValue(),671After.getData().begin()->getValue());672return;673}674675unsigned Minor = 0;676FuncDataT<T> Missing("");677IRDataT<T>::report(Before, After,678[&](const FuncDataT<T> *B, const FuncDataT<T> *A) {679assert((B || A) && "Both functions cannot be missing.");680if (!B)681B = &Missing;682else if (!A)683A = &Missing;684CompareFunc(true, Minor++, *B, *A);685});686}687688template <typename T> void IRComparer<T>::analyzeIR(Any IR, IRDataT<T> &Data) {689if (const Module *M = getModuleForComparison(IR)) {690// Create data for each existing/interesting function in the module.691for (const Function &F : *M)692generateFunctionData(Data, F);693return;694}695696if (const auto *F = unwrapIR<Function>(IR)) {697generateFunctionData(Data, *F);698return;699}700701if (const auto *L = unwrapIR<Loop>(IR)) {702auto *F = L->getHeader()->getParent();703generateFunctionData(Data, *F);704return;705}706707if (const auto *MF = unwrapIR<MachineFunction>(IR)) {708generateFunctionData(Data, *MF);709return;710}711712llvm_unreachable("Unknown IR unit");713}714715static bool shouldGenerateData(const Function &F) {716return !F.isDeclaration() && isFunctionInPrintList(F.getName());717}718719static bool shouldGenerateData(const MachineFunction &MF) {720return isFunctionInPrintList(MF.getName());721}722723template <typename T>724template <typename FunctionT>725bool IRComparer<T>::generateFunctionData(IRDataT<T> &Data, const FunctionT &F) {726if (shouldGenerateData(F)) {727FuncDataT<T> FD(F.front().getName().str());728int I = 0;729for (const auto &B : F) {730std::string BBName = B.getName().str();731if (BBName.empty()) {732BBName = formatv("{0}", I);733++I;734}735FD.getOrder().emplace_back(BBName);736FD.getData().insert({BBName, B});737}738Data.getOrder().emplace_back(F.getName());739Data.getData().insert({F.getName(), FD});740return true;741}742return false;743}744745PrintIRInstrumentation::~PrintIRInstrumentation() {746assert(PassRunDescriptorStack.empty() &&747"PassRunDescriptorStack is not empty at exit");748}749750static SmallString<32> getIRFileDisplayName(Any IR) {751SmallString<32> Result;752raw_svector_ostream ResultStream(Result);753const Module *M = unwrapModule(IR);754stable_hash NameHash = stable_hash_combine_string(M->getName());755unsigned int MaxHashWidth = sizeof(stable_hash) * 8 / 4;756write_hex(ResultStream, NameHash, HexPrintStyle::Lower, MaxHashWidth);757if (unwrapIR<Module>(IR)) {758ResultStream << "-module";759} else if (const auto *F = unwrapIR<Function>(IR)) {760ResultStream << "-function-";761stable_hash FunctionNameHash = stable_hash_combine_string(F->getName());762write_hex(ResultStream, FunctionNameHash, HexPrintStyle::Lower,763MaxHashWidth);764} else if (const auto *C = unwrapIR<LazyCallGraph::SCC>(IR)) {765ResultStream << "-scc-";766stable_hash SCCNameHash = stable_hash_combine_string(C->getName());767write_hex(ResultStream, SCCNameHash, HexPrintStyle::Lower, MaxHashWidth);768} else if (const auto *L = unwrapIR<Loop>(IR)) {769ResultStream << "-loop-";770stable_hash LoopNameHash = stable_hash_combine_string(L->getName());771write_hex(ResultStream, LoopNameHash, HexPrintStyle::Lower, MaxHashWidth);772} else if (const auto *MF = unwrapIR<MachineFunction>(IR)) {773ResultStream << "-machine-function-";774stable_hash MachineFunctionNameHash =775stable_hash_combine_string(MF->getName());776write_hex(ResultStream, MachineFunctionNameHash, HexPrintStyle::Lower,777MaxHashWidth);778} else {779llvm_unreachable("Unknown wrapped IR type");780}781return Result;782}783784std::string PrintIRInstrumentation::fetchDumpFilename(StringRef PassName,785Any IR) {786const StringRef RootDirectory = IRDumpDirectory;787assert(!RootDirectory.empty() &&788"The flag -ir-dump-directory must be passed to dump IR to files");789SmallString<128> ResultPath;790ResultPath += RootDirectory;791SmallString<64> Filename;792raw_svector_ostream FilenameStream(Filename);793FilenameStream << CurrentPassNumber;794FilenameStream << "-";795FilenameStream << getIRFileDisplayName(IR);796FilenameStream << "-";797FilenameStream << PassName;798sys::path::append(ResultPath, Filename);799return std::string(ResultPath);800}801802enum class IRDumpFileSuffixType {803Before,804After,805Invalidated,806};807808static StringRef getFileSuffix(IRDumpFileSuffixType Type) {809static constexpr std::array FileSuffixes = {"-before.ll", "-after.ll",810"-invalidated.ll"};811return FileSuffixes[static_cast<size_t>(Type)];812}813814void PrintIRInstrumentation::pushPassRunDescriptor(815StringRef PassID, Any IR, std::string &DumpIRFilename) {816const Module *M = unwrapModule(IR);817PassRunDescriptorStack.emplace_back(818PassRunDescriptor(M, DumpIRFilename, getIRName(IR), PassID));819}820821PrintIRInstrumentation::PassRunDescriptor822PrintIRInstrumentation::popPassRunDescriptor(StringRef PassID) {823assert(!PassRunDescriptorStack.empty() && "empty PassRunDescriptorStack");824PassRunDescriptor Descriptor = PassRunDescriptorStack.pop_back_val();825assert(Descriptor.PassID == PassID && "malformed PassRunDescriptorStack");826return Descriptor;827}828829// Callers are responsible for closing the returned file descriptor830static int prepareDumpIRFileDescriptor(const StringRef DumpIRFilename) {831std::error_code EC;832auto ParentPath = llvm::sys::path::parent_path(DumpIRFilename);833if (!ParentPath.empty()) {834std::error_code EC = llvm::sys::fs::create_directories(ParentPath);835if (EC)836report_fatal_error(Twine("Failed to create directory ") + ParentPath +837" to support -ir-dump-directory: " + EC.message());838}839int Result = 0;840EC = sys::fs::openFile(DumpIRFilename, Result, sys::fs::CD_OpenAlways,841sys::fs::FA_Write, sys::fs::OF_Text);842if (EC)843report_fatal_error(Twine("Failed to open ") + DumpIRFilename +844" to support -ir-dump-directory: " + EC.message());845return Result;846}847848void PrintIRInstrumentation::printBeforePass(StringRef PassID, Any IR) {849if (isIgnored(PassID))850return;851852std::string DumpIRFilename;853if (!IRDumpDirectory.empty() &&854(shouldPrintBeforePass(PassID) || shouldPrintAfterPass(PassID) ||855shouldPrintBeforeCurrentPassNumber() ||856shouldPrintAfterCurrentPassNumber()))857DumpIRFilename = fetchDumpFilename(PassID, IR);858859// Saving Module for AfterPassInvalidated operations.860// Note: here we rely on a fact that we do not change modules while861// traversing the pipeline, so the latest captured module is good862// for all print operations that has not happen yet.863if (shouldPrintAfterPass(PassID))864pushPassRunDescriptor(PassID, IR, DumpIRFilename);865866if (!shouldPrintIR(IR))867return;868869++CurrentPassNumber;870871if (shouldPrintPassNumbers())872dbgs() << " Running pass " << CurrentPassNumber << " " << PassID873<< " on " << getIRName(IR) << "\n";874875if (shouldPrintAfterCurrentPassNumber())876pushPassRunDescriptor(PassID, IR, DumpIRFilename);877878if (!shouldPrintBeforePass(PassID) && !shouldPrintBeforeCurrentPassNumber())879return;880881auto WriteIRToStream = [&](raw_ostream &Stream) {882Stream << "; *** IR Dump Before ";883if (shouldPrintBeforeSomePassNumber())884Stream << CurrentPassNumber << "-";885Stream << PassID << " on " << getIRName(IR) << " ***\n";886unwrapAndPrint(Stream, IR);887};888889if (!DumpIRFilename.empty()) {890DumpIRFilename += getFileSuffix(IRDumpFileSuffixType::Before);891llvm::raw_fd_ostream DumpIRFileStream{892prepareDumpIRFileDescriptor(DumpIRFilename), /* shouldClose */ true};893WriteIRToStream(DumpIRFileStream);894} else {895WriteIRToStream(dbgs());896}897}898899void PrintIRInstrumentation::printAfterPass(StringRef PassID, Any IR) {900if (isIgnored(PassID))901return;902903if (!shouldPrintAfterPass(PassID) && !shouldPrintAfterCurrentPassNumber())904return;905906auto [M, DumpIRFilename, IRName, StoredPassID] = popPassRunDescriptor(PassID);907assert(StoredPassID == PassID && "mismatched PassID");908909if (!shouldPrintIR(IR) ||910(!shouldPrintAfterPass(PassID) && !shouldPrintAfterCurrentPassNumber()))911return;912913auto WriteIRToStream = [&](raw_ostream &Stream, const StringRef IRName) {914Stream << "; *** IR Dump After ";915if (shouldPrintAfterSomePassNumber())916Stream << CurrentPassNumber << "-";917Stream << StringRef(formatv("{0}", PassID)) << " on " << IRName << " ***\n";918unwrapAndPrint(Stream, IR);919};920921if (!IRDumpDirectory.empty()) {922assert(!DumpIRFilename.empty() && "DumpIRFilename must not be empty and "923"should be set in printBeforePass");924const std::string DumpIRFilenameWithSuffix =925DumpIRFilename + getFileSuffix(IRDumpFileSuffixType::After).str();926llvm::raw_fd_ostream DumpIRFileStream{927prepareDumpIRFileDescriptor(DumpIRFilenameWithSuffix),928/* shouldClose */ true};929WriteIRToStream(DumpIRFileStream, IRName);930} else {931WriteIRToStream(dbgs(), IRName);932}933}934935void PrintIRInstrumentation::printAfterPassInvalidated(StringRef PassID) {936if (isIgnored(PassID))937return;938939if (!shouldPrintAfterPass(PassID) && !shouldPrintAfterCurrentPassNumber())940return;941942auto [M, DumpIRFilename, IRName, StoredPassID] = popPassRunDescriptor(PassID);943assert(StoredPassID == PassID && "mismatched PassID");944// Additional filtering (e.g. -filter-print-func) can lead to module945// printing being skipped.946if (!M ||947(!shouldPrintAfterPass(PassID) && !shouldPrintAfterCurrentPassNumber()))948return;949950auto WriteIRToStream = [&](raw_ostream &Stream, const Module *M,951const StringRef IRName) {952SmallString<20> Banner;953Banner = formatv("; *** IR Dump After {0} on {1} (invalidated) ***", PassID,954IRName);955Stream << Banner << "\n";956printIR(Stream, M);957};958959if (!IRDumpDirectory.empty()) {960assert(!DumpIRFilename.empty() && "DumpIRFilename must not be empty and "961"should be set in printBeforePass");962const std::string DumpIRFilenameWithSuffix =963DumpIRFilename + getFileSuffix(IRDumpFileSuffixType::Invalidated).str();964llvm::raw_fd_ostream DumpIRFileStream{965prepareDumpIRFileDescriptor(DumpIRFilenameWithSuffix),966/* shouldClose */ true};967WriteIRToStream(DumpIRFileStream, M, IRName);968} else {969WriteIRToStream(dbgs(), M, IRName);970}971}972973bool PrintIRInstrumentation::shouldPrintBeforePass(StringRef PassID) {974if (shouldPrintBeforeAll())975return true;976977StringRef PassName = PIC->getPassNameForClassName(PassID);978return is_contained(printBeforePasses(), PassName);979}980981bool PrintIRInstrumentation::shouldPrintAfterPass(StringRef PassID) {982if (shouldPrintAfterAll())983return true;984985StringRef PassName = PIC->getPassNameForClassName(PassID);986return is_contained(printAfterPasses(), PassName);987}988989bool PrintIRInstrumentation::shouldPrintBeforeCurrentPassNumber() {990return shouldPrintBeforeSomePassNumber() &&991(CurrentPassNumber == PrintBeforePassNumber);992}993994bool PrintIRInstrumentation::shouldPrintAfterCurrentPassNumber() {995return shouldPrintAfterSomePassNumber() &&996(CurrentPassNumber == PrintAfterPassNumber);997}998999bool PrintIRInstrumentation::shouldPrintPassNumbers() {1000return PrintPassNumbers;1001}10021003bool PrintIRInstrumentation::shouldPrintBeforeSomePassNumber() {1004return PrintBeforePassNumber > 0;1005}10061007bool PrintIRInstrumentation::shouldPrintAfterSomePassNumber() {1008return PrintAfterPassNumber > 0;1009}10101011void PrintIRInstrumentation::registerCallbacks(1012PassInstrumentationCallbacks &PIC) {1013this->PIC = &PIC;10141015// BeforePass callback is not just for printing, it also saves a Module1016// for later use in AfterPassInvalidated and keeps tracks of the1017// CurrentPassNumber.1018if (shouldPrintPassNumbers() || shouldPrintBeforeSomePassNumber() ||1019shouldPrintAfterSomePassNumber() || shouldPrintBeforeSomePass() ||1020shouldPrintAfterSomePass())1021PIC.registerBeforeNonSkippedPassCallback(1022[this](StringRef P, Any IR) { this->printBeforePass(P, IR); });10231024if (shouldPrintAfterSomePass() || shouldPrintAfterSomePassNumber()) {1025PIC.registerAfterPassCallback(1026[this](StringRef P, Any IR, const PreservedAnalyses &) {1027this->printAfterPass(P, IR);1028});1029PIC.registerAfterPassInvalidatedCallback(1030[this](StringRef P, const PreservedAnalyses &) {1031this->printAfterPassInvalidated(P);1032});1033}1034}10351036void OptNoneInstrumentation::registerCallbacks(1037PassInstrumentationCallbacks &PIC) {1038PIC.registerShouldRunOptionalPassCallback(1039[this](StringRef P, Any IR) { return this->shouldRun(P, IR); });1040}10411042bool OptNoneInstrumentation::shouldRun(StringRef PassID, Any IR) {1043const auto *F = unwrapIR<Function>(IR);1044if (!F) {1045if (const auto *L = unwrapIR<Loop>(IR))1046F = L->getHeader()->getParent();1047}1048bool ShouldRun = !(F && F->hasOptNone());1049if (!ShouldRun && DebugLogging) {1050errs() << "Skipping pass " << PassID << " on " << F->getName()1051<< " due to optnone attribute\n";1052}1053return ShouldRun;1054}10551056bool OptPassGateInstrumentation::shouldRun(StringRef PassName, Any IR) {1057if (isIgnored(PassName))1058return true;10591060bool ShouldRun =1061Context.getOptPassGate().shouldRunPass(PassName, getIRName(IR));1062if (!ShouldRun && !this->HasWrittenIR && !OptBisectPrintIRPath.empty()) {1063// FIXME: print IR if limit is higher than number of opt-bisect1064// invocations1065this->HasWrittenIR = true;1066const Module *M = unwrapModule(IR, /*Force=*/true);1067assert((M && &M->getContext() == &Context) && "Missing/Mismatching Module");1068std::error_code EC;1069raw_fd_ostream OS(OptBisectPrintIRPath, EC);1070if (EC)1071report_fatal_error(errorCodeToError(EC));1072M->print(OS, nullptr);1073}1074return ShouldRun;1075}10761077void OptPassGateInstrumentation::registerCallbacks(1078PassInstrumentationCallbacks &PIC) {1079OptPassGate &PassGate = Context.getOptPassGate();1080if (!PassGate.isEnabled())1081return;10821083PIC.registerShouldRunOptionalPassCallback([this](StringRef PassName, Any IR) {1084return this->shouldRun(PassName, IR);1085});1086}10871088raw_ostream &PrintPassInstrumentation::print() {1089if (Opts.Indent) {1090assert(Indent >= 0);1091dbgs().indent(Indent);1092}1093return dbgs();1094}10951096void PrintPassInstrumentation::registerCallbacks(1097PassInstrumentationCallbacks &PIC) {1098if (!Enabled)1099return;11001101std::vector<StringRef> SpecialPasses;1102if (!Opts.Verbose) {1103SpecialPasses.emplace_back("PassManager");1104SpecialPasses.emplace_back("PassAdaptor");1105}11061107PIC.registerBeforeSkippedPassCallback([this, SpecialPasses](StringRef PassID,1108Any IR) {1109assert(!isSpecialPass(PassID, SpecialPasses) &&1110"Unexpectedly skipping special pass");11111112print() << "Skipping pass: " << PassID << " on " << getIRName(IR) << "\n";1113});1114PIC.registerBeforeNonSkippedPassCallback([this, SpecialPasses](1115StringRef PassID, Any IR) {1116if (isSpecialPass(PassID, SpecialPasses))1117return;11181119auto &OS = print();1120OS << "Running pass: " << PassID << " on " << getIRName(IR);1121if (const auto *F = unwrapIR<Function>(IR)) {1122unsigned Count = F->getInstructionCount();1123OS << " (" << Count << " instruction";1124if (Count != 1)1125OS << 's';1126OS << ')';1127} else if (const auto *C = unwrapIR<LazyCallGraph::SCC>(IR)) {1128int Count = C->size();1129OS << " (" << Count << " node";1130if (Count != 1)1131OS << 's';1132OS << ')';1133}1134OS << "\n";1135Indent += 2;1136});1137PIC.registerAfterPassCallback(1138[this, SpecialPasses](StringRef PassID, Any IR,1139const PreservedAnalyses &) {1140if (isSpecialPass(PassID, SpecialPasses))1141return;11421143Indent -= 2;1144});1145PIC.registerAfterPassInvalidatedCallback(1146[this, SpecialPasses](StringRef PassID, Any IR) {1147if (isSpecialPass(PassID, SpecialPasses))1148return;11491150Indent -= 2;1151});11521153if (!Opts.SkipAnalyses) {1154PIC.registerBeforeAnalysisCallback([this](StringRef PassID, Any IR) {1155print() << "Running analysis: " << PassID << " on " << getIRName(IR)1156<< "\n";1157Indent += 2;1158});1159PIC.registerAfterAnalysisCallback(1160[this](StringRef PassID, Any IR) { Indent -= 2; });1161PIC.registerAnalysisInvalidatedCallback([this](StringRef PassID, Any IR) {1162print() << "Invalidating analysis: " << PassID << " on " << getIRName(IR)1163<< "\n";1164});1165PIC.registerAnalysesClearedCallback([this](StringRef IRName) {1166print() << "Clearing all analysis results for: " << IRName << "\n";1167});1168}1169}11701171PreservedCFGCheckerInstrumentation::CFG::CFG(const Function *F,1172bool TrackBBLifetime) {1173if (TrackBBLifetime)1174BBGuards = DenseMap<intptr_t, BBGuard>(F->size());1175for (const auto &BB : *F) {1176if (BBGuards)1177BBGuards->try_emplace(intptr_t(&BB), &BB);1178for (const auto *Succ : successors(&BB)) {1179Graph[&BB][Succ]++;1180if (BBGuards)1181BBGuards->try_emplace(intptr_t(Succ), Succ);1182}1183}1184}11851186static void printBBName(raw_ostream &out, const BasicBlock *BB) {1187if (BB->hasName()) {1188out << BB->getName() << "<" << BB << ">";1189return;1190}11911192if (!BB->getParent()) {1193out << "unnamed_removed<" << BB << ">";1194return;1195}11961197if (BB->isEntryBlock()) {1198out << "entry"1199<< "<" << BB << ">";1200return;1201}12021203unsigned FuncOrderBlockNum = 0;1204for (auto &FuncBB : *BB->getParent()) {1205if (&FuncBB == BB)1206break;1207FuncOrderBlockNum++;1208}1209out << "unnamed_" << FuncOrderBlockNum << "<" << BB << ">";1210}12111212void PreservedCFGCheckerInstrumentation::CFG::printDiff(raw_ostream &out,1213const CFG &Before,1214const CFG &After) {1215assert(!After.isPoisoned());1216if (Before.isPoisoned()) {1217out << "Some blocks were deleted\n";1218return;1219}12201221// Find and print graph differences.1222if (Before.Graph.size() != After.Graph.size())1223out << "Different number of non-leaf basic blocks: before="1224<< Before.Graph.size() << ", after=" << After.Graph.size() << "\n";12251226for (auto &BB : Before.Graph) {1227auto BA = After.Graph.find(BB.first);1228if (BA == After.Graph.end()) {1229out << "Non-leaf block ";1230printBBName(out, BB.first);1231out << " is removed (" << BB.second.size() << " successors)\n";1232}1233}12341235for (auto &BA : After.Graph) {1236auto BB = Before.Graph.find(BA.first);1237if (BB == Before.Graph.end()) {1238out << "Non-leaf block ";1239printBBName(out, BA.first);1240out << " is added (" << BA.second.size() << " successors)\n";1241continue;1242}12431244if (BB->second == BA.second)1245continue;12461247out << "Different successors of block ";1248printBBName(out, BA.first);1249out << " (unordered):\n";1250out << "- before (" << BB->second.size() << "): ";1251for (auto &SuccB : BB->second) {1252printBBName(out, SuccB.first);1253if (SuccB.second != 1)1254out << "(" << SuccB.second << "), ";1255else1256out << ", ";1257}1258out << "\n";1259out << "- after (" << BA.second.size() << "): ";1260for (auto &SuccA : BA.second) {1261printBBName(out, SuccA.first);1262if (SuccA.second != 1)1263out << "(" << SuccA.second << "), ";1264else1265out << ", ";1266}1267out << "\n";1268}1269}12701271// PreservedCFGCheckerInstrumentation uses PreservedCFGCheckerAnalysis to check1272// passes, that reported they kept CFG analyses up-to-date, did not actually1273// change CFG. This check is done as follows. Before every functional pass in1274// BeforeNonSkippedPassCallback a CFG snapshot (an instance of1275// PreservedCFGCheckerInstrumentation::CFG) is requested from1276// FunctionAnalysisManager as a result of PreservedCFGCheckerAnalysis. When the1277// functional pass finishes and reports that CFGAnalyses or AllAnalyses are1278// up-to-date then the cached result of PreservedCFGCheckerAnalysis (if1279// available) is checked to be equal to a freshly created CFG snapshot.1280struct PreservedCFGCheckerAnalysis1281: public AnalysisInfoMixin<PreservedCFGCheckerAnalysis> {1282friend AnalysisInfoMixin<PreservedCFGCheckerAnalysis>;12831284static AnalysisKey Key;12851286public:1287/// Provide the result type for this analysis pass.1288using Result = PreservedCFGCheckerInstrumentation::CFG;12891290/// Run the analysis pass over a function and produce CFG.1291Result run(Function &F, FunctionAnalysisManager &FAM) {1292return Result(&F, /* TrackBBLifetime */ true);1293}1294};12951296AnalysisKey PreservedCFGCheckerAnalysis::Key;12971298struct PreservedFunctionHashAnalysis1299: public AnalysisInfoMixin<PreservedFunctionHashAnalysis> {1300static AnalysisKey Key;13011302struct FunctionHash {1303uint64_t Hash;1304};13051306using Result = FunctionHash;13071308Result run(Function &F, FunctionAnalysisManager &FAM) {1309return Result{StructuralHash(F)};1310}1311};13121313AnalysisKey PreservedFunctionHashAnalysis::Key;13141315struct PreservedModuleHashAnalysis1316: public AnalysisInfoMixin<PreservedModuleHashAnalysis> {1317static AnalysisKey Key;13181319struct ModuleHash {1320uint64_t Hash;1321};13221323using Result = ModuleHash;13241325Result run(Module &F, ModuleAnalysisManager &FAM) {1326return Result{StructuralHash(F)};1327}1328};13291330AnalysisKey PreservedModuleHashAnalysis::Key;13311332bool PreservedCFGCheckerInstrumentation::CFG::invalidate(1333Function &F, const PreservedAnalyses &PA,1334FunctionAnalysisManager::Invalidator &) {1335auto PAC = PA.getChecker<PreservedCFGCheckerAnalysis>();1336return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>() ||1337PAC.preservedSet<CFGAnalyses>());1338}13391340static SmallVector<Function *, 1> GetFunctions(Any IR) {1341SmallVector<Function *, 1> Functions;13421343if (const auto *MaybeF = unwrapIR<Function>(IR)) {1344Functions.push_back(const_cast<Function *>(MaybeF));1345} else if (const auto *MaybeM = unwrapIR<Module>(IR)) {1346for (Function &F : *const_cast<Module *>(MaybeM))1347Functions.push_back(&F);1348}1349return Functions;1350}13511352void PreservedCFGCheckerInstrumentation::registerCallbacks(1353PassInstrumentationCallbacks &PIC, ModuleAnalysisManager &MAM) {1354if (!VerifyAnalysisInvalidation)1355return;13561357bool Registered = false;1358PIC.registerBeforeNonSkippedPassCallback([this, &MAM, Registered](1359StringRef P, Any IR) mutable {1360#ifdef LLVM_ENABLE_ABI_BREAKING_CHECKS1361assert(&PassStack.emplace_back(P));1362#endif1363(void)this;13641365auto &FAM = MAM.getResult<FunctionAnalysisManagerModuleProxy>(1366*const_cast<Module *>(unwrapModule(IR, /*Force=*/true)))1367.getManager();1368if (!Registered) {1369FAM.registerPass([&] { return PreservedCFGCheckerAnalysis(); });1370FAM.registerPass([&] { return PreservedFunctionHashAnalysis(); });1371MAM.registerPass([&] { return PreservedModuleHashAnalysis(); });1372Registered = true;1373}13741375for (Function *F : GetFunctions(IR)) {1376// Make sure a fresh CFG snapshot is available before the pass.1377FAM.getResult<PreservedCFGCheckerAnalysis>(*F);1378FAM.getResult<PreservedFunctionHashAnalysis>(*F);1379}13801381if (const auto *MPtr = unwrapIR<Module>(IR)) {1382auto &M = *const_cast<Module *>(MPtr);1383MAM.getResult<PreservedModuleHashAnalysis>(M);1384}1385});13861387PIC.registerAfterPassInvalidatedCallback(1388[this](StringRef P, const PreservedAnalyses &PassPA) {1389#ifdef LLVM_ENABLE_ABI_BREAKING_CHECKS1390assert(PassStack.pop_back_val() == P &&1391"Before and After callbacks must correspond");1392#endif1393(void)this;1394});13951396PIC.registerAfterPassCallback([this, &MAM](StringRef P, Any IR,1397const PreservedAnalyses &PassPA) {1398#ifdef LLVM_ENABLE_ABI_BREAKING_CHECKS1399assert(PassStack.pop_back_val() == P &&1400"Before and After callbacks must correspond");1401#endif1402(void)this;14031404// We have to get the FAM via the MAM, rather than directly use a passed in1405// FAM because if MAM has not cached the FAM, it won't invalidate function1406// analyses in FAM.1407auto &FAM = MAM.getResult<FunctionAnalysisManagerModuleProxy>(1408*const_cast<Module *>(unwrapModule(IR, /*Force=*/true)))1409.getManager();14101411for (Function *F : GetFunctions(IR)) {1412if (auto *HashBefore =1413FAM.getCachedResult<PreservedFunctionHashAnalysis>(*F)) {1414if (HashBefore->Hash != StructuralHash(*F)) {1415report_fatal_error(formatv(1416"Function @{0} changed by {1} without invalidating analyses",1417F->getName(), P));1418}1419}14201421auto CheckCFG = [](StringRef Pass, StringRef FuncName,1422const CFG &GraphBefore, const CFG &GraphAfter) {1423if (GraphAfter == GraphBefore)1424return;14251426dbgs()1427<< "Error: " << Pass1428<< " does not invalidate CFG analyses but CFG changes detected in "1429"function @"1430<< FuncName << ":\n";1431CFG::printDiff(dbgs(), GraphBefore, GraphAfter);1432report_fatal_error(Twine("CFG unexpectedly changed by ", Pass));1433};14341435if (auto *GraphBefore =1436FAM.getCachedResult<PreservedCFGCheckerAnalysis>(*F))1437CheckCFG(P, F->getName(), *GraphBefore,1438CFG(F, /* TrackBBLifetime */ false));1439}1440if (const auto *MPtr = unwrapIR<Module>(IR)) {1441auto &M = *const_cast<Module *>(MPtr);1442if (auto *HashBefore =1443MAM.getCachedResult<PreservedModuleHashAnalysis>(M)) {1444if (HashBefore->Hash != StructuralHash(M)) {1445report_fatal_error(formatv(1446"Module changed by {0} without invalidating analyses", P));1447}1448}1449}1450});1451}14521453void VerifyInstrumentation::registerCallbacks(PassInstrumentationCallbacks &PIC,1454ModuleAnalysisManager *MAM) {1455PIC.registerAfterPassCallback(1456[this, MAM](StringRef P, Any IR, const PreservedAnalyses &PassPA) {1457if (isIgnored(P) || P == "VerifierPass")1458return;1459const auto *F = unwrapIR<Function>(IR);1460if (!F) {1461if (const auto *L = unwrapIR<Loop>(IR))1462F = L->getHeader()->getParent();1463}14641465if (F) {1466if (DebugLogging)1467dbgs() << "Verifying function " << F->getName() << "\n";14681469if (verifyFunction(*F, &errs()))1470report_fatal_error(formatv("Broken function found after pass "1471"\"{0}\", compilation aborted!",1472P));1473} else {1474const auto *M = unwrapIR<Module>(IR);1475if (!M) {1476if (const auto *C = unwrapIR<LazyCallGraph::SCC>(IR))1477M = C->begin()->getFunction().getParent();1478}14791480if (M) {1481if (DebugLogging)1482dbgs() << "Verifying module " << M->getName() << "\n";14831484if (verifyModule(*M, &errs()))1485report_fatal_error(formatv("Broken module found after pass "1486"\"{0}\", compilation aborted!",1487P));1488}14891490if (auto *MF = unwrapIR<MachineFunction>(IR)) {1491if (DebugLogging)1492dbgs() << "Verifying machine function " << MF->getName() << '\n';1493std::string Banner =1494formatv("Broken machine function found after pass "1495"\"{0}\", compilation aborted!",1496P);1497if (MAM) {1498Module &M = const_cast<Module &>(*MF->getFunction().getParent());1499auto &MFAM =1500MAM->getResult<MachineFunctionAnalysisManagerModuleProxy>(M)1501.getManager();1502MachineVerifierPass Verifier(Banner);1503Verifier.run(const_cast<MachineFunction &>(*MF), MFAM);1504} else {1505verifyMachineFunction(Banner, *MF);1506}1507}1508}1509});1510}15111512InLineChangePrinter::~InLineChangePrinter() = default;15131514void InLineChangePrinter::generateIRRepresentation(Any IR,1515StringRef PassID,1516IRDataT<EmptyData> &D) {1517IRComparer<EmptyData>::analyzeIR(IR, D);1518}15191520void InLineChangePrinter::handleAfter(StringRef PassID, std::string &Name,1521const IRDataT<EmptyData> &Before,1522const IRDataT<EmptyData> &After,1523Any IR) {1524SmallString<20> Banner =1525formatv("*** IR Dump After {0} on {1} ***\n", PassID, Name);1526Out << Banner;1527IRComparer<EmptyData>(Before, After)1528.compare(getModuleForComparison(IR),1529[&](bool InModule, unsigned Minor,1530const FuncDataT<EmptyData> &Before,1531const FuncDataT<EmptyData> &After) -> void {1532handleFunctionCompare(Name, "", PassID, " on ", InModule,1533Minor, Before, After);1534});1535Out << "\n";1536}15371538void InLineChangePrinter::handleFunctionCompare(1539StringRef Name, StringRef Prefix, StringRef PassID, StringRef Divider,1540bool InModule, unsigned Minor, const FuncDataT<EmptyData> &Before,1541const FuncDataT<EmptyData> &After) {1542// Print a banner when this is being shown in the context of a module1543if (InModule)1544Out << "\n*** IR for function " << Name << " ***\n";15451546FuncDataT<EmptyData>::report(1547Before, After,1548[&](const BlockDataT<EmptyData> *B, const BlockDataT<EmptyData> *A) {1549StringRef BStr = B ? B->getBody() : "\n";1550StringRef AStr = A ? A->getBody() : "\n";1551const std::string Removed =1552UseColour ? "\033[31m-%l\033[0m\n" : "-%l\n";1553const std::string Added = UseColour ? "\033[32m+%l\033[0m\n" : "+%l\n";1554const std::string NoChange = " %l\n";1555Out << doSystemDiff(BStr, AStr, Removed, Added, NoChange);1556});1557}15581559void InLineChangePrinter::registerCallbacks(PassInstrumentationCallbacks &PIC) {1560if (PrintChanged == ChangePrinter::DiffVerbose ||1561PrintChanged == ChangePrinter::DiffQuiet ||1562PrintChanged == ChangePrinter::ColourDiffVerbose ||1563PrintChanged == ChangePrinter::ColourDiffQuiet)1564TextChangeReporter<IRDataT<EmptyData>>::registerRequiredCallbacks(PIC);1565}15661567TimeProfilingPassesHandler::TimeProfilingPassesHandler() {}15681569void TimeProfilingPassesHandler::registerCallbacks(1570PassInstrumentationCallbacks &PIC) {1571if (!getTimeTraceProfilerInstance())1572return;1573PIC.registerBeforeNonSkippedPassCallback(1574[this](StringRef P, Any IR) { this->runBeforePass(P, IR); });1575PIC.registerAfterPassCallback(1576[this](StringRef P, Any IR, const PreservedAnalyses &) {1577this->runAfterPass();1578},1579true);1580PIC.registerAfterPassInvalidatedCallback(1581[this](StringRef P, const PreservedAnalyses &) { this->runAfterPass(); },1582true);1583PIC.registerBeforeAnalysisCallback(1584[this](StringRef P, Any IR) { this->runBeforePass(P, IR); });1585PIC.registerAfterAnalysisCallback(1586[this](StringRef P, Any IR) { this->runAfterPass(); }, true);1587}15881589void TimeProfilingPassesHandler::runBeforePass(StringRef PassID, Any IR) {1590timeTraceProfilerBegin(PassID, getIRName(IR));1591}15921593void TimeProfilingPassesHandler::runAfterPass() { timeTraceProfilerEnd(); }15941595namespace {15961597class DisplayNode;1598class DotCfgDiffDisplayGraph;15991600// Base class for a node or edge in the dot-cfg-changes graph.1601class DisplayElement {1602public:1603// Is this in before, after, or both?1604StringRef getColour() const { return Colour; }16051606protected:1607DisplayElement(StringRef Colour) : Colour(Colour) {}1608const StringRef Colour;1609};16101611// An edge representing a transition between basic blocks in the1612// dot-cfg-changes graph.1613class DisplayEdge : public DisplayElement {1614public:1615DisplayEdge(std::string Value, DisplayNode &Node, StringRef Colour)1616: DisplayElement(Colour), Value(Value), Node(Node) {}1617// The value on which the transition is made.1618std::string getValue() const { return Value; }1619// The node (representing a basic block) reached by this transition.1620const DisplayNode &getDestinationNode() const { return Node; }16211622protected:1623std::string Value;1624const DisplayNode &Node;1625};16261627// A node in the dot-cfg-changes graph which represents a basic block.1628class DisplayNode : public DisplayElement {1629public:1630// \p C is the content for the node, \p T indicates the colour for the1631// outline of the node1632DisplayNode(std::string Content, StringRef Colour)1633: DisplayElement(Colour), Content(Content) {}16341635// Iterator to the child nodes. Required by GraphWriter.1636using ChildIterator = std::unordered_set<DisplayNode *>::const_iterator;1637ChildIterator children_begin() const { return Children.cbegin(); }1638ChildIterator children_end() const { return Children.cend(); }16391640// Iterator for the edges. Required by GraphWriter.1641using EdgeIterator = std::vector<DisplayEdge *>::const_iterator;1642EdgeIterator edges_begin() const { return EdgePtrs.cbegin(); }1643EdgeIterator edges_end() const { return EdgePtrs.cend(); }16441645// Create an edge to \p Node on value \p Value, with colour \p Colour.1646void createEdge(StringRef Value, DisplayNode &Node, StringRef Colour);16471648// Return the content of this node.1649std::string getContent() const { return Content; }16501651// Return the edge to node \p S.1652const DisplayEdge &getEdge(const DisplayNode &To) const {1653assert(EdgeMap.find(&To) != EdgeMap.end() && "Expected to find edge.");1654return *EdgeMap.find(&To)->second;1655}16561657// Return the value for the transition to basic block \p S.1658// Required by GraphWriter.1659std::string getEdgeSourceLabel(const DisplayNode &Sink) const {1660return getEdge(Sink).getValue();1661}16621663void createEdgeMap();16641665protected:1666const std::string Content;16671668// Place to collect all of the edges. Once they are all in the vector,1669// the vector will not reallocate so then we can use pointers to them,1670// which are required by the graph writing routines.1671std::vector<DisplayEdge> Edges;16721673std::vector<DisplayEdge *> EdgePtrs;1674std::unordered_set<DisplayNode *> Children;1675std::unordered_map<const DisplayNode *, const DisplayEdge *> EdgeMap;16761677// Safeguard adding of edges.1678bool AllEdgesCreated = false;1679};16801681// Class representing a difference display (corresponds to a pdf file).1682class DotCfgDiffDisplayGraph {1683public:1684DotCfgDiffDisplayGraph(std::string Name) : GraphName(Name) {}16851686// Generate the file into \p DotFile.1687void generateDotFile(StringRef DotFile);16881689// Iterator to the nodes. Required by GraphWriter.1690using NodeIterator = std::vector<DisplayNode *>::const_iterator;1691NodeIterator nodes_begin() const {1692assert(NodeGenerationComplete && "Unexpected children iterator creation");1693return NodePtrs.cbegin();1694}1695NodeIterator nodes_end() const {1696assert(NodeGenerationComplete && "Unexpected children iterator creation");1697return NodePtrs.cend();1698}16991700// Record the index of the entry node. At this point, we can build up1701// vectors of pointers that are required by the graph routines.1702void setEntryNode(unsigned N) {1703// At this point, there will be no new nodes.1704assert(!NodeGenerationComplete && "Unexpected node creation");1705NodeGenerationComplete = true;1706for (auto &N : Nodes)1707NodePtrs.emplace_back(&N);17081709EntryNode = NodePtrs[N];1710}17111712// Create a node.1713void createNode(std::string C, StringRef Colour) {1714assert(!NodeGenerationComplete && "Unexpected node creation");1715Nodes.emplace_back(C, Colour);1716}1717// Return the node at index \p N to avoid problems with vectors reallocating.1718DisplayNode &getNode(unsigned N) {1719assert(N < Nodes.size() && "Node is out of bounds");1720return Nodes[N];1721}1722unsigned size() const {1723assert(NodeGenerationComplete && "Unexpected children iterator creation");1724return Nodes.size();1725}17261727// Return the name of the graph. Required by GraphWriter.1728std::string getGraphName() const { return GraphName; }17291730// Return the string representing the differences for basic block \p Node.1731// Required by GraphWriter.1732std::string getNodeLabel(const DisplayNode &Node) const {1733return Node.getContent();1734}17351736// Return a string with colour information for Dot. Required by GraphWriter.1737std::string getNodeAttributes(const DisplayNode &Node) const {1738return attribute(Node.getColour());1739}17401741// Return a string with colour information for Dot. Required by GraphWriter.1742std::string getEdgeColorAttr(const DisplayNode &From,1743const DisplayNode &To) const {1744return attribute(From.getEdge(To).getColour());1745}17461747// Get the starting basic block. Required by GraphWriter.1748DisplayNode *getEntryNode() const {1749assert(NodeGenerationComplete && "Unexpected children iterator creation");1750return EntryNode;1751}17521753protected:1754// Return the string containing the colour to use as a Dot attribute.1755std::string attribute(StringRef Colour) const {1756return "color=" + Colour.str();1757}17581759bool NodeGenerationComplete = false;1760const std::string GraphName;1761std::vector<DisplayNode> Nodes;1762std::vector<DisplayNode *> NodePtrs;1763DisplayNode *EntryNode = nullptr;1764};17651766void DisplayNode::createEdge(StringRef Value, DisplayNode &Node,1767StringRef Colour) {1768assert(!AllEdgesCreated && "Expected to be able to still create edges.");1769Edges.emplace_back(Value.str(), Node, Colour);1770Children.insert(&Node);1771}17721773void DisplayNode::createEdgeMap() {1774// No more edges will be added so we can now use pointers to the edges1775// as the vector will not grow and reallocate.1776AllEdgesCreated = true;1777for (auto &E : Edges)1778EdgeMap.insert({&E.getDestinationNode(), &E});1779}17801781class DotCfgDiffNode;1782class DotCfgDiff;17831784// A class representing a basic block in the Dot difference graph.1785class DotCfgDiffNode {1786public:1787DotCfgDiffNode() = delete;17881789// Create a node in Dot difference graph \p G representing the basic block1790// represented by \p BD with colour \p Colour (where it exists).1791DotCfgDiffNode(DotCfgDiff &G, unsigned N, const BlockDataT<DCData> &BD,1792StringRef Colour)1793: Graph(G), N(N), Data{&BD, nullptr}, Colour(Colour) {}1794DotCfgDiffNode(const DotCfgDiffNode &DN)1795: Graph(DN.Graph), N(DN.N), Data{DN.Data[0], DN.Data[1]},1796Colour(DN.Colour), EdgesMap(DN.EdgesMap), Children(DN.Children),1797Edges(DN.Edges) {}17981799unsigned getIndex() const { return N; }18001801// The label of the basic block1802StringRef getLabel() const {1803assert(Data[0] && "Expected Data[0] to be set.");1804return Data[0]->getLabel();1805}1806// Return the colour for this block1807StringRef getColour() const { return Colour; }1808// Change this basic block from being only in before to being common.1809// Save the pointer to \p Other.1810void setCommon(const BlockDataT<DCData> &Other) {1811assert(!Data[1] && "Expected only one block datum");1812Data[1] = &Other;1813Colour = CommonColour;1814}1815// Add an edge to \p E of colour {\p Value, \p Colour}.1816void addEdge(unsigned E, StringRef Value, StringRef Colour) {1817// This is a new edge or it is an edge being made common.1818assert((EdgesMap.count(E) == 0 || Colour == CommonColour) &&1819"Unexpected edge count and color.");1820EdgesMap[E] = {Value.str(), Colour};1821}1822// Record the children and create edges.1823void finalize(DotCfgDiff &G);18241825// Return the colour of the edge to node \p S.1826StringRef getEdgeColour(const unsigned S) const {1827assert(EdgesMap.count(S) == 1 && "Expected to find edge.");1828return EdgesMap.at(S).second;1829}18301831// Return the string representing the basic block.1832std::string getBodyContent() const;18331834void createDisplayEdges(DotCfgDiffDisplayGraph &Graph, unsigned DisplayNode,1835std::map<const unsigned, unsigned> &NodeMap) const;18361837protected:1838DotCfgDiff &Graph;1839const unsigned N;1840const BlockDataT<DCData> *Data[2];1841StringRef Colour;1842std::map<const unsigned, std::pair<std::string, StringRef>> EdgesMap;1843std::vector<unsigned> Children;1844std::vector<unsigned> Edges;1845};18461847// Class representing the difference graph between two functions.1848class DotCfgDiff {1849public:1850// \p Title is the title given to the graph. \p EntryNodeName is the1851// entry node for the function. \p Before and \p After are the before1852// after versions of the function, respectively. \p Dir is the directory1853// in which to store the results.1854DotCfgDiff(StringRef Title, const FuncDataT<DCData> &Before,1855const FuncDataT<DCData> &After);18561857DotCfgDiff(const DotCfgDiff &) = delete;1858DotCfgDiff &operator=(const DotCfgDiff &) = delete;18591860DotCfgDiffDisplayGraph createDisplayGraph(StringRef Title,1861StringRef EntryNodeName);18621863// Return a string consisting of the labels for the \p Source and \p Sink.1864// The combination allows distinguishing changing transitions on the1865// same value (ie, a transition went to X before and goes to Y after).1866// Required by GraphWriter.1867StringRef getEdgeSourceLabel(const unsigned &Source,1868const unsigned &Sink) const {1869std::string S =1870getNode(Source).getLabel().str() + " " + getNode(Sink).getLabel().str();1871assert(EdgeLabels.count(S) == 1 && "Expected to find edge label.");1872return EdgeLabels.find(S)->getValue();1873}18741875// Return the number of basic blocks (nodes). Required by GraphWriter.1876unsigned size() const { return Nodes.size(); }18771878const DotCfgDiffNode &getNode(unsigned N) const {1879assert(N < Nodes.size() && "Unexpected index for node reference");1880return Nodes[N];1881}18821883protected:1884// Return the string surrounded by HTML to make it the appropriate colour.1885std::string colourize(std::string S, StringRef Colour) const;18861887void createNode(StringRef Label, const BlockDataT<DCData> &BD, StringRef C) {1888unsigned Pos = Nodes.size();1889Nodes.emplace_back(*this, Pos, BD, C);1890NodePosition.insert({Label, Pos});1891}18921893// TODO Nodes should probably be a StringMap<DotCfgDiffNode> after the1894// display graph is separated out, which would remove the need for1895// NodePosition.1896std::vector<DotCfgDiffNode> Nodes;1897StringMap<unsigned> NodePosition;1898const std::string GraphName;18991900StringMap<std::string> EdgeLabels;1901};19021903std::string DotCfgDiffNode::getBodyContent() const {1904if (Colour == CommonColour) {1905assert(Data[1] && "Expected Data[1] to be set.");19061907StringRef SR[2];1908for (unsigned I = 0; I < 2; ++I) {1909SR[I] = Data[I]->getBody();1910// drop initial '\n' if present1911SR[I].consume_front("\n");1912// drop predecessors as they can be big and are redundant1913SR[I] = SR[I].drop_until([](char C) { return C == '\n'; }).drop_front();1914}19151916SmallString<80> OldLineFormat = formatv(1917"<FONT COLOR=\"{0}\">%l</FONT><BR align=\"left\"/>", BeforeColour);1918SmallString<80> NewLineFormat = formatv(1919"<FONT COLOR=\"{0}\">%l</FONT><BR align=\"left\"/>", AfterColour);1920SmallString<80> UnchangedLineFormat = formatv(1921"<FONT COLOR=\"{0}\">%l</FONT><BR align=\"left\"/>", CommonColour);1922std::string Diff = Data[0]->getLabel().str();1923Diff += ":\n<BR align=\"left\"/>" +1924doSystemDiff(makeHTMLReady(SR[0]), makeHTMLReady(SR[1]),1925OldLineFormat, NewLineFormat, UnchangedLineFormat);19261927// Diff adds in some empty colour changes which are not valid HTML1928// so remove them. Colours are all lowercase alpha characters (as1929// listed in https://graphviz.org/pdf/dotguide.pdf).1930Regex R("<FONT COLOR=\"\\w+\"></FONT>");1931while (true) {1932std::string Error;1933std::string S = R.sub("", Diff, &Error);1934if (Error != "")1935return Error;1936if (S == Diff)1937return Diff;1938Diff = S;1939}1940llvm_unreachable("Should not get here");1941}19421943// Put node out in the appropriate colour.1944assert(!Data[1] && "Data[1] is set unexpectedly.");1945std::string Body = makeHTMLReady(Data[0]->getBody());1946const StringRef BS = Body;1947StringRef BS1 = BS;1948// Drop leading newline, if present.1949if (BS.front() == '\n')1950BS1 = BS1.drop_front(1);1951// Get label.1952StringRef Label = BS1.take_until([](char C) { return C == ':'; });1953// drop predecessors as they can be big and are redundant1954BS1 = BS1.drop_until([](char C) { return C == '\n'; }).drop_front();19551956std::string S = "<FONT COLOR=\"" + Colour.str() + "\">" + Label.str() + ":";19571958// align each line to the left.1959while (BS1.size()) {1960S.append("<BR align=\"left\"/>");1961StringRef Line = BS1.take_until([](char C) { return C == '\n'; });1962S.append(Line.str());1963BS1 = BS1.drop_front(Line.size() + 1);1964}1965S.append("<BR align=\"left\"/></FONT>");1966return S;1967}19681969std::string DotCfgDiff::colourize(std::string S, StringRef Colour) const {1970if (S.length() == 0)1971return S;1972return "<FONT COLOR=\"" + Colour.str() + "\">" + S + "</FONT>";1973}19741975DotCfgDiff::DotCfgDiff(StringRef Title, const FuncDataT<DCData> &Before,1976const FuncDataT<DCData> &After)1977: GraphName(Title.str()) {1978StringMap<StringRef> EdgesMap;19791980// Handle each basic block in the before IR.1981for (auto &B : Before.getData()) {1982StringRef Label = B.getKey();1983const BlockDataT<DCData> &BD = B.getValue();1984createNode(Label, BD, BeforeColour);19851986// Create transitions with names made up of the from block label, the value1987// on which the transition is made and the to block label.1988for (StringMap<std::string>::const_iterator Sink = BD.getData().begin(),1989E = BD.getData().end();1990Sink != E; ++Sink) {1991std::string Key = (Label + " " + Sink->getKey().str()).str() + " " +1992BD.getData().getSuccessorLabel(Sink->getKey()).str();1993EdgesMap.insert({Key, BeforeColour});1994}1995}19961997// Handle each basic block in the after IR1998for (auto &A : After.getData()) {1999StringRef Label = A.getKey();2000const BlockDataT<DCData> &BD = A.getValue();2001unsigned C = NodePosition.count(Label);2002if (C == 0)2003// This only exists in the after IR. Create the node.2004createNode(Label, BD, AfterColour);2005else {2006assert(C == 1 && "Unexpected multiple nodes.");2007Nodes[NodePosition[Label]].setCommon(BD);2008}2009// Add in the edges between the nodes (as common or only in after).2010for (StringMap<std::string>::const_iterator Sink = BD.getData().begin(),2011E = BD.getData().end();2012Sink != E; ++Sink) {2013std::string Key = (Label + " " + Sink->getKey().str()).str() + " " +2014BD.getData().getSuccessorLabel(Sink->getKey()).str();2015unsigned C = EdgesMap.count(Key);2016if (C == 0)2017EdgesMap.insert({Key, AfterColour});2018else {2019EdgesMap[Key] = CommonColour;2020}2021}2022}20232024// Now go through the map of edges and add them to the node.2025for (auto &E : EdgesMap) {2026// Extract the source, sink and value from the edge key.2027StringRef S = E.getKey();2028auto SP1 = S.rsplit(' ');2029auto &SourceSink = SP1.first;2030auto SP2 = SourceSink.split(' ');2031StringRef Source = SP2.first;2032StringRef Sink = SP2.second;2033StringRef Value = SP1.second;20342035assert(NodePosition.count(Source) == 1 && "Expected to find node.");2036DotCfgDiffNode &SourceNode = Nodes[NodePosition[Source]];2037assert(NodePosition.count(Sink) == 1 && "Expected to find node.");2038unsigned SinkNode = NodePosition[Sink];2039StringRef Colour = E.second;20402041// Look for an edge from Source to Sink2042if (EdgeLabels.count(SourceSink) == 0)2043EdgeLabels.insert({SourceSink, colourize(Value.str(), Colour)});2044else {2045StringRef V = EdgeLabels.find(SourceSink)->getValue();2046std::string NV = colourize(V.str() + " " + Value.str(), Colour);2047Colour = CommonColour;2048EdgeLabels[SourceSink] = NV;2049}2050SourceNode.addEdge(SinkNode, Value, Colour);2051}2052for (auto &I : Nodes)2053I.finalize(*this);2054}20552056DotCfgDiffDisplayGraph DotCfgDiff::createDisplayGraph(StringRef Title,2057StringRef EntryNodeName) {2058assert(NodePosition.count(EntryNodeName) == 1 &&2059"Expected to find entry block in map.");2060unsigned Entry = NodePosition[EntryNodeName];2061assert(Entry < Nodes.size() && "Expected to find entry node");2062DotCfgDiffDisplayGraph G(Title.str());20632064std::map<const unsigned, unsigned> NodeMap;20652066int EntryIndex = -1;2067unsigned Index = 0;2068for (auto &I : Nodes) {2069if (I.getIndex() == Entry)2070EntryIndex = Index;2071G.createNode(I.getBodyContent(), I.getColour());2072NodeMap.insert({I.getIndex(), Index++});2073}2074assert(EntryIndex >= 0 && "Expected entry node index to be set.");2075G.setEntryNode(EntryIndex);20762077for (auto &I : NodeMap) {2078unsigned SourceNode = I.first;2079unsigned DisplayNode = I.second;2080getNode(SourceNode).createDisplayEdges(G, DisplayNode, NodeMap);2081}2082return G;2083}20842085void DotCfgDiffNode::createDisplayEdges(2086DotCfgDiffDisplayGraph &DisplayGraph, unsigned DisplayNodeIndex,2087std::map<const unsigned, unsigned> &NodeMap) const {20882089DisplayNode &SourceDisplayNode = DisplayGraph.getNode(DisplayNodeIndex);20902091for (auto I : Edges) {2092unsigned SinkNodeIndex = I;2093StringRef Colour = getEdgeColour(SinkNodeIndex);2094const DotCfgDiffNode *SinkNode = &Graph.getNode(SinkNodeIndex);20952096StringRef Label = Graph.getEdgeSourceLabel(getIndex(), SinkNodeIndex);2097DisplayNode &SinkDisplayNode = DisplayGraph.getNode(SinkNode->getIndex());2098SourceDisplayNode.createEdge(Label, SinkDisplayNode, Colour);2099}2100SourceDisplayNode.createEdgeMap();2101}21022103void DotCfgDiffNode::finalize(DotCfgDiff &G) {2104for (auto E : EdgesMap) {2105Children.emplace_back(E.first);2106Edges.emplace_back(E.first);2107}2108}21092110} // namespace21112112namespace llvm {21132114template <> struct GraphTraits<DotCfgDiffDisplayGraph *> {2115using NodeRef = const DisplayNode *;2116using ChildIteratorType = DisplayNode::ChildIterator;2117using nodes_iterator = DotCfgDiffDisplayGraph::NodeIterator;2118using EdgeRef = const DisplayEdge *;2119using ChildEdgeIterator = DisplayNode::EdgeIterator;21202121static NodeRef getEntryNode(const DotCfgDiffDisplayGraph *G) {2122return G->getEntryNode();2123}2124static ChildIteratorType child_begin(NodeRef N) {2125return N->children_begin();2126}2127static ChildIteratorType child_end(NodeRef N) { return N->children_end(); }2128static nodes_iterator nodes_begin(const DotCfgDiffDisplayGraph *G) {2129return G->nodes_begin();2130}2131static nodes_iterator nodes_end(const DotCfgDiffDisplayGraph *G) {2132return G->nodes_end();2133}2134static ChildEdgeIterator child_edge_begin(NodeRef N) {2135return N->edges_begin();2136}2137static ChildEdgeIterator child_edge_end(NodeRef N) { return N->edges_end(); }2138static NodeRef edge_dest(EdgeRef E) { return &E->getDestinationNode(); }2139static unsigned size(const DotCfgDiffDisplayGraph *G) { return G->size(); }2140};21412142template <>2143struct DOTGraphTraits<DotCfgDiffDisplayGraph *> : public DefaultDOTGraphTraits {2144explicit DOTGraphTraits(bool Simple = false)2145: DefaultDOTGraphTraits(Simple) {}21462147static bool renderNodesUsingHTML() { return true; }2148static std::string getGraphName(const DotCfgDiffDisplayGraph *DiffData) {2149return DiffData->getGraphName();2150}2151static std::string2152getGraphProperties(const DotCfgDiffDisplayGraph *DiffData) {2153return "\tsize=\"190, 190\";\n";2154}2155static std::string getNodeLabel(const DisplayNode *Node,2156const DotCfgDiffDisplayGraph *DiffData) {2157return DiffData->getNodeLabel(*Node);2158}2159static std::string getNodeAttributes(const DisplayNode *Node,2160const DotCfgDiffDisplayGraph *DiffData) {2161return DiffData->getNodeAttributes(*Node);2162}2163static std::string getEdgeSourceLabel(const DisplayNode *From,2164DisplayNode::ChildIterator &To) {2165return From->getEdgeSourceLabel(**To);2166}2167static std::string getEdgeAttributes(const DisplayNode *From,2168DisplayNode::ChildIterator &To,2169const DotCfgDiffDisplayGraph *DiffData) {2170return DiffData->getEdgeColorAttr(*From, **To);2171}2172};21732174} // namespace llvm21752176namespace {21772178void DotCfgDiffDisplayGraph::generateDotFile(StringRef DotFile) {2179std::error_code EC;2180raw_fd_ostream OutStream(DotFile, EC);2181if (EC) {2182errs() << "Error: " << EC.message() << "\n";2183return;2184}2185WriteGraph(OutStream, this, false);2186OutStream.flush();2187OutStream.close();2188}21892190} // namespace21912192namespace llvm {21932194DCData::DCData(const BasicBlock &B) {2195// Build up transition labels.2196const Instruction *Term = B.getTerminator();2197if (const BranchInst *Br = dyn_cast<const BranchInst>(Term))2198if (Br->isUnconditional())2199addSuccessorLabel(Br->getSuccessor(0)->getName().str(), "");2200else {2201addSuccessorLabel(Br->getSuccessor(0)->getName().str(), "true");2202addSuccessorLabel(Br->getSuccessor(1)->getName().str(), "false");2203}2204else if (const SwitchInst *Sw = dyn_cast<const SwitchInst>(Term)) {2205addSuccessorLabel(Sw->case_default()->getCaseSuccessor()->getName().str(),2206"default");2207for (auto &C : Sw->cases()) {2208assert(C.getCaseValue() && "Expected to find case value.");2209SmallString<20> Value = formatv("{0}", C.getCaseValue()->getSExtValue());2210addSuccessorLabel(C.getCaseSuccessor()->getName().str(), Value);2211}2212} else2213for (const BasicBlock *Succ : successors(&B))2214addSuccessorLabel(Succ->getName().str(), "");2215}22162217DCData::DCData(const MachineBasicBlock &B) {2218for (const MachineBasicBlock *Succ : successors(&B))2219addSuccessorLabel(Succ->getName().str(), "");2220}22212222DotCfgChangeReporter::DotCfgChangeReporter(bool Verbose)2223: ChangeReporter<IRDataT<DCData>>(Verbose) {}22242225void DotCfgChangeReporter::handleFunctionCompare(2226StringRef Name, StringRef Prefix, StringRef PassID, StringRef Divider,2227bool InModule, unsigned Minor, const FuncDataT<DCData> &Before,2228const FuncDataT<DCData> &After) {2229assert(HTML && "Expected outstream to be set");2230SmallString<8> Extender;2231SmallString<8> Number;2232// Handle numbering and file names.2233if (InModule) {2234Extender = formatv("{0}_{1}", N, Minor);2235Number = formatv("{0}.{1}", N, Minor);2236} else {2237Extender = formatv("{0}", N);2238Number = formatv("{0}", N);2239}2240// Create a temporary file name for the dot file.2241SmallVector<char, 128> SV;2242sys::fs::createUniquePath("cfgdot-%%%%%%.dot", SV, true);2243std::string DotFile = Twine(SV).str();22442245SmallString<20> PDFFileName = formatv("diff_{0}.pdf", Extender);2246SmallString<200> Text;22472248Text = formatv("{0}.{1}{2}{3}{4}", Number, Prefix, makeHTMLReady(PassID),2249Divider, Name);22502251DotCfgDiff Diff(Text, Before, After);2252std::string EntryBlockName = After.getEntryBlockName();2253// Use the before entry block if the after entry block was removed.2254if (EntryBlockName == "")2255EntryBlockName = Before.getEntryBlockName();2256assert(EntryBlockName != "" && "Expected to find entry block");22572258DotCfgDiffDisplayGraph DG = Diff.createDisplayGraph(Text, EntryBlockName);2259DG.generateDotFile(DotFile);22602261*HTML << genHTML(Text, DotFile, PDFFileName);2262std::error_code EC = sys::fs::remove(DotFile);2263if (EC)2264errs() << "Error: " << EC.message() << "\n";2265}22662267std::string DotCfgChangeReporter::genHTML(StringRef Text, StringRef DotFile,2268StringRef PDFFileName) {2269SmallString<20> PDFFile = formatv("{0}/{1}", DotCfgDir, PDFFileName);2270// Create the PDF file.2271static ErrorOr<std::string> DotExe = sys::findProgramByName(DotBinary);2272if (!DotExe)2273return "Unable to find dot executable.";22742275StringRef Args[] = {DotBinary, "-Tpdf", "-o", PDFFile, DotFile};2276int Result = sys::ExecuteAndWait(*DotExe, Args, std::nullopt);2277if (Result < 0)2278return "Error executing system dot.";22792280// Create the HTML tag refering to the PDF file.2281SmallString<200> S = formatv(2282" <a href=\"{0}\" target=\"_blank\">{1}</a><br/>\n", PDFFileName, Text);2283return S.c_str();2284}22852286void DotCfgChangeReporter::handleInitialIR(Any IR) {2287assert(HTML && "Expected outstream to be set");2288*HTML << "<button type=\"button\" class=\"collapsible\">0. "2289<< "Initial IR (by function)</button>\n"2290<< "<div class=\"content\">\n"2291<< " <p>\n";2292// Create representation of IR2293IRDataT<DCData> Data;2294IRComparer<DCData>::analyzeIR(IR, Data);2295// Now compare it against itself, which will have everything the2296// same and will generate the files.2297IRComparer<DCData>(Data, Data)2298.compare(getModuleForComparison(IR),2299[&](bool InModule, unsigned Minor,2300const FuncDataT<DCData> &Before,2301const FuncDataT<DCData> &After) -> void {2302handleFunctionCompare("", " ", "Initial IR", "", InModule,2303Minor, Before, After);2304});2305*HTML << " </p>\n"2306<< "</div><br/>\n";2307++N;2308}23092310void DotCfgChangeReporter::generateIRRepresentation(Any IR, StringRef PassID,2311IRDataT<DCData> &Data) {2312IRComparer<DCData>::analyzeIR(IR, Data);2313}23142315void DotCfgChangeReporter::omitAfter(StringRef PassID, std::string &Name) {2316assert(HTML && "Expected outstream to be set");2317SmallString<20> Banner =2318formatv(" <a>{0}. Pass {1} on {2} omitted because no change</a><br/>\n",2319N, makeHTMLReady(PassID), Name);2320*HTML << Banner;2321++N;2322}23232324void DotCfgChangeReporter::handleAfter(StringRef PassID, std::string &Name,2325const IRDataT<DCData> &Before,2326const IRDataT<DCData> &After, Any IR) {2327assert(HTML && "Expected outstream to be set");2328IRComparer<DCData>(Before, After)2329.compare(getModuleForComparison(IR),2330[&](bool InModule, unsigned Minor,2331const FuncDataT<DCData> &Before,2332const FuncDataT<DCData> &After) -> void {2333handleFunctionCompare(Name, " Pass ", PassID, " on ", InModule,2334Minor, Before, After);2335});2336*HTML << " </p></div>\n";2337++N;2338}23392340void DotCfgChangeReporter::handleInvalidated(StringRef PassID) {2341assert(HTML && "Expected outstream to be set");2342SmallString<20> Banner =2343formatv(" <a>{0}. {1} invalidated</a><br/>\n", N, makeHTMLReady(PassID));2344*HTML << Banner;2345++N;2346}23472348void DotCfgChangeReporter::handleFiltered(StringRef PassID, std::string &Name) {2349assert(HTML && "Expected outstream to be set");2350SmallString<20> Banner =2351formatv(" <a>{0}. Pass {1} on {2} filtered out</a><br/>\n", N,2352makeHTMLReady(PassID), Name);2353*HTML << Banner;2354++N;2355}23562357void DotCfgChangeReporter::handleIgnored(StringRef PassID, std::string &Name) {2358assert(HTML && "Expected outstream to be set");2359SmallString<20> Banner = formatv(" <a>{0}. {1} on {2} ignored</a><br/>\n", N,2360makeHTMLReady(PassID), Name);2361*HTML << Banner;2362++N;2363}23642365bool DotCfgChangeReporter::initializeHTML() {2366std::error_code EC;2367HTML = std::make_unique<raw_fd_ostream>(DotCfgDir + "/passes.html", EC);2368if (EC) {2369HTML = nullptr;2370return false;2371}23722373*HTML << "<!doctype html>"2374<< "<html>"2375<< "<head>"2376<< "<style>.collapsible { "2377<< "background-color: #777;"2378<< " color: white;"2379<< " cursor: pointer;"2380<< " padding: 18px;"2381<< " width: 100%;"2382<< " border: none;"2383<< " text-align: left;"2384<< " outline: none;"2385<< " font-size: 15px;"2386<< "} .active, .collapsible:hover {"2387<< " background-color: #555;"2388<< "} .content {"2389<< " padding: 0 18px;"2390<< " display: none;"2391<< " overflow: hidden;"2392<< " background-color: #f1f1f1;"2393<< "}"2394<< "</style>"2395<< "<title>passes.html</title>"2396<< "</head>\n"2397<< "<body>";2398return true;2399}24002401DotCfgChangeReporter::~DotCfgChangeReporter() {2402if (!HTML)2403return;2404*HTML2405<< "<script>var coll = document.getElementsByClassName(\"collapsible\");"2406<< "var i;"2407<< "for (i = 0; i < coll.length; i++) {"2408<< "coll[i].addEventListener(\"click\", function() {"2409<< " this.classList.toggle(\"active\");"2410<< " var content = this.nextElementSibling;"2411<< " if (content.style.display === \"block\"){"2412<< " content.style.display = \"none\";"2413<< " }"2414<< " else {"2415<< " content.style.display= \"block\";"2416<< " }"2417<< " });"2418<< " }"2419<< "</script>"2420<< "</body>"2421<< "</html>\n";2422HTML->flush();2423HTML->close();2424}24252426void DotCfgChangeReporter::registerCallbacks(2427PassInstrumentationCallbacks &PIC) {2428if (PrintChanged == ChangePrinter::DotCfgVerbose ||2429PrintChanged == ChangePrinter::DotCfgQuiet) {2430SmallString<128> OutputDir;2431sys::fs::expand_tilde(DotCfgDir, OutputDir);2432sys::fs::make_absolute(OutputDir);2433assert(!OutputDir.empty() && "expected output dir to be non-empty");2434DotCfgDir = OutputDir.c_str();2435if (initializeHTML()) {2436ChangeReporter<IRDataT<DCData>>::registerRequiredCallbacks(PIC);2437return;2438}2439dbgs() << "Unable to open output stream for -cfg-dot-changed\n";2440}2441}24422443StandardInstrumentations::StandardInstrumentations(2444LLVMContext &Context, bool DebugLogging, bool VerifyEach,2445PrintPassOptions PrintPassOpts)2446: PrintPass(DebugLogging, PrintPassOpts),2447OptNone(DebugLogging),2448OptPassGate(Context),2449PrintChangedIR(PrintChanged == ChangePrinter::Verbose),2450PrintChangedDiff(PrintChanged == ChangePrinter::DiffVerbose ||2451PrintChanged == ChangePrinter::ColourDiffVerbose,2452PrintChanged == ChangePrinter::ColourDiffVerbose ||2453PrintChanged == ChangePrinter::ColourDiffQuiet),2454WebsiteChangeReporter(PrintChanged == ChangePrinter::DotCfgVerbose),2455Verify(DebugLogging), VerifyEach(VerifyEach) {}24562457PrintCrashIRInstrumentation *PrintCrashIRInstrumentation::CrashReporter =2458nullptr;24592460void PrintCrashIRInstrumentation::reportCrashIR() {2461if (!PrintOnCrashPath.empty()) {2462std::error_code EC;2463raw_fd_ostream Out(PrintOnCrashPath, EC);2464if (EC)2465report_fatal_error(errorCodeToError(EC));2466Out << SavedIR;2467} else {2468dbgs() << SavedIR;2469}2470}24712472void PrintCrashIRInstrumentation::SignalHandler(void *) {2473// Called by signal handlers so do not lock here2474// Is the PrintCrashIRInstrumentation still alive?2475if (!CrashReporter)2476return;24772478assert((PrintOnCrash || !PrintOnCrashPath.empty()) &&2479"Did not expect to get here without option set.");2480CrashReporter->reportCrashIR();2481}24822483PrintCrashIRInstrumentation::~PrintCrashIRInstrumentation() {2484if (!CrashReporter)2485return;24862487assert((PrintOnCrash || !PrintOnCrashPath.empty()) &&2488"Did not expect to get here without option set.");2489CrashReporter = nullptr;2490}24912492void PrintCrashIRInstrumentation::registerCallbacks(2493PassInstrumentationCallbacks &PIC) {2494if ((!PrintOnCrash && PrintOnCrashPath.empty()) || CrashReporter)2495return;24962497sys::AddSignalHandler(SignalHandler, nullptr);2498CrashReporter = this;24992500PIC.registerBeforeNonSkippedPassCallback(2501[&PIC, this](StringRef PassID, Any IR) {2502SavedIR.clear();2503raw_string_ostream OS(SavedIR);2504OS << formatv("*** Dump of {0}IR Before Last Pass {1}",2505llvm::forcePrintModuleIR() ? "Module " : "", PassID);2506if (!isInteresting(IR, PassID, PIC.getPassNameForClassName(PassID))) {2507OS << " Filtered Out ***\n";2508return;2509}2510OS << " Started ***\n";2511unwrapAndPrint(OS, IR);2512});2513}25142515void StandardInstrumentations::registerCallbacks(2516PassInstrumentationCallbacks &PIC, ModuleAnalysisManager *MAM) {2517PrintIR.registerCallbacks(PIC);2518PrintPass.registerCallbacks(PIC);2519TimePasses.registerCallbacks(PIC);2520OptNone.registerCallbacks(PIC);2521OptPassGate.registerCallbacks(PIC);2522PrintChangedIR.registerCallbacks(PIC);2523PseudoProbeVerification.registerCallbacks(PIC);2524if (VerifyEach)2525Verify.registerCallbacks(PIC, MAM);2526PrintChangedDiff.registerCallbacks(PIC);2527WebsiteChangeReporter.registerCallbacks(PIC);2528ChangeTester.registerCallbacks(PIC);2529PrintCrashIR.registerCallbacks(PIC);2530if (MAM)2531PreservedCFGChecker.registerCallbacks(PIC, *MAM);25322533// TimeProfiling records the pass running time cost.2534// Its 'BeforePassCallback' can be appended at the tail of all the2535// BeforeCallbacks by calling `registerCallbacks` in the end.2536// Its 'AfterPassCallback' is put at the front of all the2537// AfterCallbacks by its `registerCallbacks`. This is necessary2538// to ensure that other callbacks are not included in the timings.2539TimeProfilingPasses.registerCallbacks(PIC);2540}25412542template class ChangeReporter<std::string>;2543template class TextChangeReporter<std::string>;25442545template class BlockDataT<EmptyData>;2546template class FuncDataT<EmptyData>;2547template class IRDataT<EmptyData>;2548template class ChangeReporter<IRDataT<EmptyData>>;2549template class TextChangeReporter<IRDataT<EmptyData>>;2550template class IRComparer<EmptyData>;25512552} // namespace llvm255325542555