1//===-- MachineFunctionPrinterPass.cpp ------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// MachineFunctionPrinterPass implementation.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/CodeGen/MachineFunction.h"
14#include "llvm/CodeGen/MachineFunctionPass.h"
15#include "llvm/CodeGen/Passes.h"
16#include "llvm/CodeGen/SlotIndexes.h"
17#include "llvm/IR/PrintPasses.h"
18#include "llvm/InitializePasses.h"
19#include "llvm/Support/Debug.h"
20#include "llvm/Support/raw_ostream.h"
21
22using namespace llvm;
23
24namespace {
25bool shouldPrintMachineFunction(const MachineFunction &MF) {
26 bool SourceLocFilterEmpty = isSourceLocFilterEmpty();
27 if (!isFunctionInPrintList(FunctionName: MF.getName()))
28 return false;
29
30 if (SourceLocFilterEmpty)
31 return true;
32
33 for (const MachineBasicBlock &MBB : MF)
34 for (const MachineInstr &MI : MBB)
35 if (isSourceLocInPrintList(Loc: MI.getDebugLoc()))
36 return true;
37 return false;
38}
39
40/// MachineFunctionPrinterPass - This is a pass to dump the IR of a
41/// MachineFunction.
42///
43struct MachineFunctionPrinterPass : public MachineFunctionPass {
44 static char ID;
45
46 raw_ostream &OS;
47 const std::string Banner;
48
49 MachineFunctionPrinterPass() : MachineFunctionPass(ID), OS(dbgs()) { }
50 MachineFunctionPrinterPass(raw_ostream &os, const std::string &banner)
51 : MachineFunctionPass(ID), OS(os), Banner(banner) {}
52
53 StringRef getPassName() const override { return "MachineFunction Printer"; }
54
55 void getAnalysisUsage(AnalysisUsage &AU) const override {
56 AU.setPreservesAll();
57 AU.addUsedIfAvailable<SlotIndexesWrapperPass>();
58 MachineFunctionPass::getAnalysisUsage(AU);
59 }
60
61 bool runOnMachineFunction(MachineFunction &MF) override {
62 if (!shouldPrintMachineFunction(MF))
63 return false;
64 OS << "# " << Banner << ":\n";
65 auto *SIWrapper = getAnalysisIfAvailable<SlotIndexesWrapperPass>();
66 MF.print(OS, SIWrapper ? &SIWrapper->getSI() : nullptr);
67 return false;
68 }
69};
70
71char MachineFunctionPrinterPass::ID = 0;
72}
73
74char &llvm::MachineFunctionPrinterPassID = MachineFunctionPrinterPass::ID;
75INITIALIZE_PASS(MachineFunctionPrinterPass, "machineinstr-printer",
76 "Machine Function Printer", false, false)
77
78/// Returns a newly-created MachineFunction Printer pass. The
79/// default banner is empty.
80///
81MachineFunctionPass *
82llvm::createMachineFunctionPrinterPass(raw_ostream &OS,
83 const std::string &Banner) {
84 return new MachineFunctionPrinterPass(OS, Banner);
85}
86