LLVM 24.0.0git
WebAssemblyCodeGenPassBuilder.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
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#include "WebAssembly.h"
31#include "llvm/MC/MCStreamer.h"
35#include "llvm/Support/Error.h"
38
39using namespace llvm;
40
41namespace WebAssembly {
43} // namespace WebAssembly
44
46
47namespace {
48
49class WebAssemblyCodeGenPassBuilder : public CodeGenPassBuilder {
51
53 return static_cast<WebAssemblyTargetMachine &>(TM);
54 }
55
56public:
57 explicit WebAssemblyCodeGenPassBuilder(WebAssemblyTargetMachine &TM,
58 const CGPassBuilderOption &Opts,
59 PassInstrumentationCallbacks *PIC)
60 : CodeGenPassBuilder(TM, Opts, PIC) {
61 disablePass<MachineBlockPlacementPass>();
62
63 // Currently RegisterCoalesce degrades wasm debug info quality by a
64 // significant margin. As a quick fix, disable this for -O1, which is often
65 // used for debugging large applications. Disabling this increases code size
66 // of Emscripten core benchmarks by ~5%, which is acceptable for -O1, which
67 // is usually not used for production builds.
68 // TODO Investigate why RegisterCoalesce degrades debug info quality and fix
69 // it properly
70 if (getOptLevel() == CodeGenOptLevel::Less)
71 disablePass<RegisterCoalescerPass>();
72 }
73
74protected:
75 void addIRPasses(PassManagerWrapper &PMW) override;
76 void addISelPrepare(PassManagerWrapper &PMW) override;
77
78 Error addInstSelector(PassManagerWrapper &PMW) override;
79
80 Error addIRTranslator(PassManagerWrapper &PMW) override;
81 void addPreLegalizeMachineIR(PassManagerWrapper &PMW) override;
82 Error addLegalizeMachineIR(PassManagerWrapper &PMW) override;
83 void addPreRegBankSelect(PassManagerWrapper &PMW) override;
84 Error addRegBankSelect(PassManagerWrapper &PMW) override;
85 Error addGlobalInstructionSelect(PassManagerWrapper &PMW) override;
86
87 void addPreEmitPass(PassManagerWrapper &PMW) override;
88 void addAsmPrinterBegin(PassManagerWrapper &PMW) override;
89 void addAsmPrinter(PassManagerWrapper &PMW) override;
90 void addAsmPrinterEnd(PassManagerWrapper &PMW) override;
91};
92
93} // namespace
94
95void WebAssemblyCodeGenPassBuilder::addIRPasses(PassManagerWrapper &PMW) {
96 // Add signatures to prototype-less function declarations
97 flushFPMsToMPM(PMW);
98 addModulePass(WebAssemblyAddMissingPrototypesPass(), PMW);
99
100 // Lower .llvm.global_dtors into .llvm.global_ctors with __cxa_atexit calls.
101 addModulePass(LowerGlobalDtorsPass(), PMW);
102
103 // Fix function bitcasts, as WebAssembly requires caller and callee signatures
104 // to match.
105 addModulePass(WebAssemblyFixFunctionBitcastsPass(), PMW);
106
107 // Optimize "returned" function attributes.
108 if (getOptLevel() != CodeGenOptLevel::None)
109 addFunctionPass(WebAssemblyOptimizeReturnedPass(), PMW);
110
111 // Wasm SjLj shares Emscripten SjLj's transformation, so it is handled here.
112 // Without Wasm or Emscripten EH, this also lowers invokes.
113 flushFPMsToMPM(PMW);
114 addModulePass(WebAssemblyLowerEmscriptenEHSjLjPass(), PMW);
115
116 // Expand indirectbr instructions to switches.
117 addFunctionPass(IndirectBrExpandPass(TM), PMW);
118
119 // Try to expand `vecreduce_{and, or}` into `{any, all}_true`.
120 addFunctionPass(WebAssemblyReduceToAnyAllTruePass(getTM()), PMW);
121
122 Base::addIRPasses(PMW);
123}
124
125void WebAssemblyCodeGenPassBuilder::addISelPrepare(PassManagerWrapper &PMW) {
126 // We need to move reference type allocas to WASM_ADDRESS_SPACE_VAR so that
127 // loads and stores are promoted to local.gets/local.sets.
128 addFunctionPass(WebAssemblyRefTypeMem2LocalPass(), PMW);
129 // Lower atomics and TLS if necessary
130 flushFPMsToMPM(PMW);
131 addModulePass(WebAssemblyCoalesceFeaturesAndStripAtomicsPass(getTM()), PMW);
132
133 // This is a no-op if atomics are not used in the module
134 addFunctionPass(AtomicExpandPass(TM), PMW);
135
136 Base::addISelPrepare(PMW);
137}
138
139Error WebAssemblyCodeGenPassBuilder::addInstSelector(PassManagerWrapper &PMW) {
140 addMachineFunctionPass(WebAssemblyISelDAGToDAGPass(getTM(), getOptLevel()),
141 PMW);
142
143 // Run the argument-move pass immediately after the ScheduleDAG scheduler
144 // so that we can fix up the ARGUMENT instructions before anything else
145 // sees them in the wrong place.
146 addMachineFunctionPass(WebAssemblyArgumentMovePass(), PMW);
147
148 // Set the p2align operands. This information is present during ISel, however
149 // it's inconvenient to collect. Collect it now, and update the immediate
150 // operands.
151 addMachineFunctionPass(WebAssemblySetP2AlignOperandsPass(), PMW);
152
153 // Eliminate range checks and add default targets to br_table instructions.
154 addMachineFunctionPass(WebAssemblyFixBrTableDefaultsPass(), PMW);
155
156 // unreachable is terminator, non-terminator instruction after it is not
157 // allowed.
158 addMachineFunctionPass(WebAssemblyCleanCodeAfterTrapPass(), PMW);
159
160 return Error::success();
161}
162
163Error WebAssemblyCodeGenPassBuilder::addIRTranslator(PassManagerWrapper &PMW) {
164 addMachineFunctionPass(IRTranslatorPass(getOptLevel()), PMW);
165 return Error::success();
166}
167
168void WebAssemblyCodeGenPassBuilder::addPreLegalizeMachineIR(
169 PassManagerWrapper &PMW) {
170 if (getOptLevel() != CodeGenOptLevel::None)
171 addMachineFunctionPass(WebAssemblyPreLegalizerCombinerPass(), PMW);
172}
173
174Error WebAssemblyCodeGenPassBuilder::addLegalizeMachineIR(
175 PassManagerWrapper &PMW) {
176 addMachineFunctionPass(LegalizerPass(), PMW);
177 return Error::success();
178}
179
180void WebAssemblyCodeGenPassBuilder::addPreRegBankSelect(
181 PassManagerWrapper &PMW) {
182 if (getOptLevel() != CodeGenOptLevel::None)
183 addMachineFunctionPass(WebAssemblyPostLegalizerCombinerPass(), PMW);
184}
185
186Error WebAssemblyCodeGenPassBuilder::addRegBankSelect(PassManagerWrapper &PMW) {
187 addMachineFunctionPass(RegBankSelectPass(), PMW);
188 return Error::success();
189}
190
191Error WebAssemblyCodeGenPassBuilder::addGlobalInstructionSelect(
192 PassManagerWrapper &PMW) {
193 addMachineFunctionPass(InstructionSelectPass(getOptLevel()), PMW);
194
195 if (isGlobalISelAbortEnabled()) {
196 addMachineFunctionPass(WebAssemblyArgumentMovePass(), PMW);
197 addMachineFunctionPass(WebAssemblySetP2AlignOperandsPass(), PMW);
198 addMachineFunctionPass(WebAssemblyFixBrTableDefaultsPass(), PMW);
199 addMachineFunctionPass(WebAssemblyCleanCodeAfterTrapPass(), PMW);
200 }
201
202 return Error::success();
203}
204
205void WebAssemblyCodeGenPassBuilder::addPreEmitPass(PassManagerWrapper &PMW) {
206 Base::addPreEmitPass(PMW);
207
208 // Nullify DBG_VALUE_LISTs that we cannot handle.
209 addMachineFunctionPass(WebAssemblyNullifyDebugValueListsPass(), PMW);
210
211 // Remove any unreachable blocks that may be left floating around.
212 // Rare, but possible. Needed for WebAssemblyFixIrreducibleControlFlow.
213 addMachineFunctionPass(UnreachableMachineBlockElimPass(), PMW);
214
215 // Eliminate multiple-entry loops.
216 addMachineFunctionPass(WebAssemblyFixIrreducibleControlFlowPass(), PMW);
217
218 // Do various transformations for exception handling.
219 // Every CFG-changing optimizations should come before this.
220 addMachineFunctionPass(WebAssemblyLateEHPreparePass(), PMW);
221
222 // Now that we have a prologue and epilogue and all frame indices are
223 // rewritten, eliminate SP and FP. This allows them to be stackified,
224 // colored, and numbered with the rest of the registers.
225 addMachineFunctionPass(WebAssemblyReplacePhysRegsPass(), PMW);
226
227 // Preparations and optimizations related to register stackification.
228 if (getOptLevel() != CodeGenOptLevel::None) {
229 // Depend on LiveIntervals and perform some optimizations on it.
230 addMachineFunctionPass(WebAssemblyOptimizeLiveIntervalsPass(), PMW);
231
232 // Prepare memory intrinsic calls for register stackifying.
233 addMachineFunctionPass(WebAssemblyMemIntrinsicResultsPass(), PMW);
234 }
235
236 // Mark registers as representing wasm's value stack. This is a key
237 // code-compression technique in WebAssembly. We run this pass (and
238 // MemIntrinsicResults above) very late, so that it sees as much code as
239 // possible, including code emitted by PEI and expanded by late tail
240 // duplication.
241 addMachineFunctionPass(WebAssemblyRegStackifyPass(getOptLevel()), PMW);
242
243 if (getOptLevel() != CodeGenOptLevel::None) {
244 // Run the register coloring pass to reduce the total number of registers.
245 // This runs after stackification so that it doesn't consider registers
246 // that become stackified.
247 addMachineFunctionPass(WebAssemblyRegColoringPass(), PMW);
248 }
249
250 // Sort the blocks of the CFG into topological order, a prerequisite for
251 // BLOCK and LOOP markers.
252 addMachineFunctionPass(WebAssemblyCFGSortPass(), PMW);
253
254 // Insert BLOCK and LOOP markers.
255 addMachineFunctionPass(WebAssemblyCFGStackifyPass(), PMW);
256
257 // Insert explicit local.get and local.set operators.
259 addMachineFunctionPass(WebAssemblyExplicitLocalsPass(), PMW);
260
261 // Lower br_unless into br_if.
262 addMachineFunctionPass(WebAssemblyLowerBrUnlessPass(), PMW);
263
264 // Perform the very last peephole optimizations on the code.
265 if (getOptLevel() != CodeGenOptLevel::None)
266 addMachineFunctionPass(WebAssemblyPeepholePass(), PMW);
267
268 // Create a mapping from LLVM CodeGen virtual registers to wasm registers.
269 addMachineFunctionPass(WebAssemblyRegNumberingPass(), PMW);
270
271 // Fix debug_values whose defs have been stackified.
273 addMachineFunctionPass(WebAssemblyDebugFixupPass(), PMW);
274
275 // Collect information to prepare for MC lowering / asm printing.
276 flushFPMsToMPM(PMW);
277 addModulePass(WebAssemblyMCLowerPrePass(), PMW);
278}
279
280void WebAssemblyCodeGenPassBuilder::addAsmPrinterBegin(
281 PassManagerWrapper &PMW) {
282 addModulePass(WebAssemblyAsmPrinterBeginPass(), PMW, /*Force=*/true);
283}
284
285void WebAssemblyCodeGenPassBuilder::addAsmPrinter(PassManagerWrapper &PMW) {
286 addMachineFunctionPass(WebAssemblyAsmPrinterPass(), PMW);
287}
288
289void WebAssemblyCodeGenPassBuilder::addAsmPrinterEnd(PassManagerWrapper &PMW) {
290 addModulePass(WebAssemblyAsmPrinterEndPass(), PMW);
291}
292
294#define GET_PASS_REGISTRY "WebAssemblyPassRegistry.def"
296}
297
300 raw_pwrite_stream *DwoOut, CodeGenFileType FileType,
301 const CGPassBuilderOption &Opt, MCContext &Ctx,
303 auto CGPB = WebAssemblyCodeGenPassBuilder(*this, Opt, PIC);
304 return CGPB.buildPipeline(MPM, MAM, Out, DwoOut, FileType, Ctx);
305}
Interfaces for producing common pass manager configurations.
This file declares the IRTranslator pass.
ModuleAnalysisManager MAM
PassBuilder PB(Mod->getContext(), Machine, PassOpts->PTO, std::nullopt, &PIC)
PassInstrumentationCallbacks PIC
This file defines the Pass Instrumentation classes that provide instrumentation points into the pass ...
This file describes the interface of the MachineFunctionPass responsible for assigning the generic vi...
const GCNTargetMachine & getTM(const GCNSubtarget *STI)
cl::opt< bool > WasmDisableExplicitLocals
This file implements WebAssemblyException information analysis.
This file declares the WebAssembly-specific subclass of TargetMachine.
This file contains the entry points for global functions defined in the LLVM WebAssembly back-end.
This class provides access to building LLVM's passes.
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Context object for machine code objects.
Definition MCContext.h:84
This class provides access to building LLVM's passes.
This class manages callbacks registration, as well as provides a way for PassInstrumentation to pass ...
void registerPassBuilderCallbacks(PassBuilder &PbB) override
Allow the target to modify the pass pipeline.
Error buildCodeGenPipeline(ModulePassManager &MPM, ModuleAnalysisManager &MAM, raw_pwrite_stream &Out, raw_pwrite_stream *DwoOut, CodeGenFileType FileType, const CGPassBuilderOption &Opt, MCContext &Ctx, PassInstrumentationCallbacks *PIC) override
An abstract base class for streams implementations that also support a pwrite operation.
Interfaces for registering analysis passes, producing common pass manager configurations,...
cl::opt< bool > WasmDisableExplicitLocals
cl::opt< bool > WasmDisableExplicitLocals
This is an optimization pass for GlobalISel generic memory operations.
CodeGenFileType
These enums are meant to be passed into addPassesToEmitFile to indicate what type of file to emit,...
Definition CodeGen.h:309
PassManager< Module > ModulePassManager
Convenience typedef for a pass manager over modules.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39