1//===- NewPMDriver.cpp - Driver for llc using new PM ----------------------===//
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 is just a split of the code that logically belongs in llc.cpp but
11/// that includes the new pass manager headers.
12///
13//===----------------------------------------------------------------------===//
14
15#include "NewPMDriver.h"
16#include "llvm/Analysis/CGSCCPassManager.h"
17#include "llvm/Analysis/RuntimeLibcallInfo.h"
18#include "llvm/Analysis/TargetLibraryInfo.h"
19#include "llvm/CodeGen/CommandFlags.h"
20#include "llvm/CodeGen/MIRParser/MIRParser.h"
21#include "llvm/CodeGen/MIRPrinter.h"
22#include "llvm/CodeGen/MachineFunctionAnalysis.h"
23#include "llvm/CodeGen/MachineModuleInfo.h"
24#include "llvm/CodeGen/MachinePassManager.h"
25#include "llvm/CodeGen/MachineVerifier.h"
26#include "llvm/CodeGen/TargetPassConfig.h"
27#include "llvm/IR/DiagnosticInfo.h"
28#include "llvm/IR/DiagnosticPrinter.h"
29#include "llvm/IR/IRPrintingPasses.h"
30#include "llvm/IR/LLVMContext.h"
31#include "llvm/IR/Module.h"
32#include "llvm/IR/PassManager.h"
33#include "llvm/IR/Verifier.h"
34#include "llvm/IRReader/IRReader.h"
35#include "llvm/Passes/PassBuilder.h"
36#include "llvm/Passes/StandardInstrumentations.h"
37#include "llvm/Plugins/PassPlugin.h"
38#include "llvm/Support/CommandLine.h"
39#include "llvm/Support/Debug.h"
40#include "llvm/Support/Error.h"
41#include "llvm/Support/ErrorHandling.h"
42#include "llvm/Support/ToolOutputFile.h"
43#include "llvm/Support/WithColor.h"
44#include "llvm/Target/CGPassBuilderOption.h"
45#include "llvm/Target/TargetMachine.h"
46#include "llvm/Target/TargetOptions.h"
47#include "llvm/Transforms/Utils/Cloning.h"
48
49using namespace llvm;
50
51static cl::opt<RegAllocType, false, RegAllocTypeParser>
52 RegAlloc("regalloc-npm",
53 cl::desc("Register allocator to use for new pass manager"),
54 cl::Hidden, cl::init(Val: RegAllocType::Unset));
55
56static cl::opt<bool>
57 DebugPM("debug-pass-manager", cl::Hidden,
58 cl::desc("Print pass management debugging information"));
59
60bool LLCDiagnosticHandler::handleDiagnostics(const DiagnosticInfo &DI) {
61 DiagnosticHandler::handleDiagnostics(DI);
62 if (DI.getKind() == llvm::DK_SrcMgr) {
63 const auto &DISM = cast<DiagnosticInfoSrcMgr>(Val: DI);
64 const SMDiagnostic &SMD = DISM.getSMDiag();
65
66 SMD.print(ProgName: nullptr, S&: errs());
67
68 // For testing purposes, we print the LocCookie here.
69 if (DISM.isInlineAsmDiag() && DISM.getLocCookie())
70 WithColor::note() << "!srcloc = " << DISM.getLocCookie() << "\n";
71
72 return true;
73 }
74
75 if (auto *Remark = dyn_cast<DiagnosticInfoOptimizationBase>(Val: &DI))
76 if (!Remark->isEnabled())
77 return true;
78
79 DiagnosticPrinterRawOStream DP(errs());
80 errs() << LLVMContext::getDiagnosticMessagePrefix(Severity: DI.getSeverity()) << ": ";
81 DI.print(DP);
82 errs() << "\n";
83 return true;
84}
85
86static llvm::ExitOnError ExitOnErr;
87
88int llvm::compileModuleWithNewPM(
89 StringRef Arg0, std::unique_ptr<Module> M, std::unique_ptr<MIRParser> MIR,
90 std::unique_ptr<TargetMachine> Target, std::unique_ptr<ToolOutputFile> Out,
91 std::unique_ptr<ToolOutputFile> DwoOut, LLVMContext &Context,
92 const TargetLibraryInfoImpl &TLII, VerifierKind VK, StringRef PassPipeline,
93 ArrayRef<PassPlugin> PassPlugins, CodeGenFileType FileType) {
94
95
96 raw_pwrite_stream *OS = &Out->os();
97
98 std::unique_ptr<buffer_ostream> BOS;
99 if (codegen::getFileType(C: Context.getLibraryOptions()) !=
100 CodeGenFileType::AssemblyFile &&
101 !Out->os().supportsSeeking()) {
102 BOS = std::make_unique<buffer_ostream>(args&: Out->os());
103 OS = BOS.get();
104 }
105
106 // Fetch options from TargetPassConfig
107 CGPassBuilderOption Opt = getCGPassBuilderOption(TM: *Target);
108 Opt.DisableVerify = VK != VerifierKind::InputOutput;
109 if (VK == VerifierKind::EachPass)
110 Opt.VerifyMachineCode = MachineVerifierMode::Each;
111 Opt.DebugPM = DebugPM;
112 Opt.RegAlloc = RegAlloc;
113
114 MachineModuleInfo MMI(Target.get());
115
116 PassInstrumentationCallbacks PIC;
117 if (!PassPipeline.empty()) {
118 auto Info = ExitOnErr(TargetPassConfig::getStartStopInfo(TM: *Target, PIC));
119 if (Info.isLimited()) {
120 WithColor::error(OS&: errs(), Prefix: Arg0)
121 << "--passes cannot be used with " << Info.getLimitReason() << ".\n";
122 return 1;
123 }
124 }
125 StandardInstrumentations SI(Context, Opt.DebugPM,
126 VK == VerifierKind::EachPass);
127 registerCodeGenCallback(PIC, *Target);
128
129 MachineFunctionAnalysisManager MFAM;
130 LoopAnalysisManager LAM;
131 FunctionAnalysisManager FAM;
132 CGSCCAnalysisManager CGAM;
133 ModuleAnalysisManager MAM;
134
135 FAM.registerPass(PassBuilder: [&] { return TargetLibraryAnalysis(TLII); });
136
137 MAM.registerPass(PassBuilder: [&] {
138 const TargetOptions &Options = Target->Options;
139 return RuntimeLibraryAnalysis(Options.MCOptions.ABIName, Options.VecLib);
140 });
141
142 MAM.registerPass(PassBuilder: [&] { return MachineModuleAnalysis(MMI); });
143
144 PassBuilder PB(Context, Target.get(), std::nullopt, std::nullopt, &PIC);
145 for (auto &PassPlugin : PassPlugins)
146 PassPlugin.registerPassBuilderCallbacks(PB);
147 PB.registerModuleAnalyses(MAM);
148 PB.registerCGSCCAnalyses(CGAM);
149 PB.registerFunctionAnalyses(FAM);
150 PB.registerLoopAnalyses(LAM);
151 PB.registerMachineFunctionAnalyses(MFAM);
152 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM, MFAM: &MFAM);
153 SI.registerCallbacks(PIC, MAM: &MAM);
154
155 ModulePassManager MPM;
156
157 if (!PassPipeline.empty()) {
158 // Construct a custom pass pipeline that starts after instruction
159 // selection.
160
161 if (!MIR) {
162 WithColor::error(OS&: errs(), Prefix: Arg0) << "-passes is for .mir file only.\n";
163 return 1;
164 }
165
166 // FIXME: verify that there are no IR passes.
167 ExitOnErr(PB.parsePassPipeline(MPM, PipelineText: PassPipeline));
168 if (Opt.VerifyMachineCode == MachineVerifierMode::End)
169 MPM.addPass(Pass: createModuleToFunctionPassAdaptor(
170 Pass: createFunctionToMachineFunctionPassAdaptor(Pass: MachineVerifierPass())));
171 MPM.addPass(Pass: PrintMIRPass(*OS));
172
173 } else {
174 ExitOnErr(Target->buildCodeGenPipeline(
175 MPM, MAM, Out&: *OS, DwoOut: DwoOut ? &DwoOut->os() : nullptr, FileType, Opt,
176 Ctx&: MMI.getContext(), PIC: &PIC));
177 }
178
179 // If user only wants to print the pipeline, print it before parsing the MIR.
180 if (std::optional<PrintPipelinePassesFormat> Format =
181 PB.getPrintPipelinePasses()) {
182 std::string PipelineStr;
183 raw_string_ostream OS(PipelineStr);
184 MPM.printPipeline(OS, MapClassName2PassName: [&PIC](StringRef ClassName) {
185 auto PassName = PIC.getPassNameForClassName(ClassName);
186 return PassName.empty() ? ClassName : PassName;
187 });
188 printFormattedPipelinePasses(OS&: outs(), Pipeline: PipelineStr, Format: *Format);
189 outs() << '\n';
190 return 0;
191 }
192
193 if (MIR && MIR->parseMachineFunctions(M&: *M, MAM))
194 return 1;
195
196 // Before executing passes, print the final values of the LLVM options.
197 cl::PrintOptionValues();
198
199 MPM.run(IR&: *M, AM&: MAM);
200
201 if (Context.getDiagHandlerPtr()->HasErrors)
202 return 1;
203
204 // Declare success.
205 Out->keep();
206 if (DwoOut)
207 DwoOut->keep();
208
209 return 0;
210}
211