1//===- MIRPrintingPass.cpp - Pass that prints out using the MIR format ----===//
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// This file implements a pass that prints out the LLVM module using the MIR
10// serialization format.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/CodeGen/MIRPrinter.h"
15#include "llvm/CodeGen/MachineFunctionPass.h"
16#include "llvm/CodeGen/MachineModuleInfo.h"
17#include "llvm/CodeGen/Passes.h"
18#include "llvm/CodeGen/VirtRegMap.h"
19#include "llvm/IR/Function.h"
20#include "llvm/InitializePasses.h"
21
22using namespace llvm;
23
24PreservedAnalyses PrintMIRPreparePass::run(Module &M, ModuleAnalysisManager &) {
25 printMIR(OS, M);
26 return PreservedAnalyses::all();
27}
28
29PreservedAnalyses PrintMIRPass::run(MachineFunction &MF,
30 MachineFunctionAnalysisManager &MFAM) {
31 auto &FAM = MFAM.getResult<FunctionAnalysisManagerMachineFunctionProxy>(IR&: MF)
32 .getManager();
33
34 const VirtRegMap *VRM = MFAM.getCachedResult<VirtRegMapAnalysis>(IR&: MF);
35 printMIR(OS, FAM, MF, VRM);
36 return PreservedAnalyses::all();
37}
38
39namespace {
40
41/// This pass prints out the LLVM IR to an output stream using the MIR
42/// serialization format.
43struct MIRPrintingPass : public MachineFunctionPass {
44 static char ID;
45 raw_ostream &OS;
46 std::string MachineFunctions;
47
48 MIRPrintingPass() : MachineFunctionPass(ID), OS(dbgs()) {}
49 MIRPrintingPass(raw_ostream &OS) : MachineFunctionPass(ID), OS(OS) {}
50
51 StringRef getPassName() const override { return "MIR Printing Pass"; }
52
53 void getAnalysisUsage(AnalysisUsage &AU) const override {
54 AU.setPreservesAll();
55 AU.addUsedIfAvailable<VirtRegMapWrapperLegacy>();
56 MachineFunctionPass::getAnalysisUsage(AU);
57 }
58
59 bool runOnMachineFunction(MachineFunction &MF) override {
60 std::string Str;
61 raw_string_ostream StrOS(Str);
62
63 MachineModuleInfo *MMI =
64 &getAnalysis<MachineModuleInfoWrapperPass>().getMMI();
65
66 const VirtRegMap *VRM = nullptr;
67 if (auto *W = getAnalysisIfAvailable<VirtRegMapWrapperLegacy>())
68 VRM = &W->getVRM();
69
70 printMIR(OS&: StrOS, MMI: *MMI, MF, VRM);
71 MachineFunctions.append(str: Str);
72 return false;
73 }
74
75 bool doFinalization(Module &M) override {
76 printMIR(OS, M);
77 OS << MachineFunctions;
78 return false;
79 }
80};
81
82char MIRPrintingPass::ID = 0;
83
84} // end anonymous namespace
85
86char &llvm::MIRPrintingPassID = MIRPrintingPass::ID;
87INITIALIZE_PASS(MIRPrintingPass, "mir-printer", "MIR Printer", false, false)
88
89MachineFunctionPass *llvm::createPrintMIRPass(raw_ostream &OS) {
90 return new MIRPrintingPass(OS);
91}
92