xref: /freebsd-src/contrib/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyTargetMachine.cpp (revision 5e801ac66d24704442eba426ed13c3effb8a34e7)
1 //===- WebAssemblyTargetMachine.cpp - Define TargetMachine for WebAssembly -==//
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 /// \file
10 /// This file defines the WebAssembly-specific subclass of TargetMachine.
11 ///
12 //===----------------------------------------------------------------------===//
13 
14 #include "WebAssemblyTargetMachine.h"
15 #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
16 #include "TargetInfo/WebAssemblyTargetInfo.h"
17 #include "WebAssembly.h"
18 #include "WebAssemblyMachineFunctionInfo.h"
19 #include "WebAssemblyTargetObjectFile.h"
20 #include "WebAssemblyTargetTransformInfo.h"
21 #include "llvm/CodeGen/MIRParser/MIParser.h"
22 #include "llvm/CodeGen/MachineFunctionPass.h"
23 #include "llvm/CodeGen/Passes.h"
24 #include "llvm/CodeGen/RegAllocRegistry.h"
25 #include "llvm/CodeGen/TargetPassConfig.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/MC/TargetRegistry.h"
28 #include "llvm/Target/TargetOptions.h"
29 #include "llvm/Transforms/Scalar.h"
30 #include "llvm/Transforms/Scalar/LowerAtomic.h"
31 #include "llvm/Transforms/Utils.h"
32 using namespace llvm;
33 
34 #define DEBUG_TYPE "wasm"
35 
36 // Emscripten's asm.js-style exception handling
37 cl::opt<bool>
38     WasmEnableEmEH("enable-emscripten-cxx-exceptions",
39                    cl::desc("WebAssembly Emscripten-style exception handling"),
40                    cl::init(false));
41 
42 // Emscripten's asm.js-style setjmp/longjmp handling
43 cl::opt<bool> WasmEnableEmSjLj(
44     "enable-emscripten-sjlj",
45     cl::desc("WebAssembly Emscripten-style setjmp/longjmp handling"),
46     cl::init(false));
47 
48 // Exception handling using wasm EH instructions
49 cl::opt<bool> WasmEnableEH("wasm-enable-eh",
50                            cl::desc("WebAssembly exception handling"),
51                            cl::init(false));
52 
53 // setjmp/longjmp handling using wasm EH instrutions
54 cl::opt<bool> WasmEnableSjLj("wasm-enable-sjlj",
55                              cl::desc("WebAssembly setjmp/longjmp handling"),
56                              cl::init(false));
57 
58 // A command-line option to keep implicit locals
59 // for the purpose of testing with lit/llc ONLY.
60 // This produces output which is not valid WebAssembly, and is not supported
61 // by assemblers/disassemblers and other MC based tools.
62 static cl::opt<bool> WasmDisableExplicitLocals(
63     "wasm-disable-explicit-locals", cl::Hidden,
64     cl::desc("WebAssembly: output implicit locals in"
65              " instruction output for test purposes only."),
66     cl::init(false));
67 
68 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeWebAssemblyTarget() {
69   // Register the target.
70   RegisterTargetMachine<WebAssemblyTargetMachine> X(
71       getTheWebAssemblyTarget32());
72   RegisterTargetMachine<WebAssemblyTargetMachine> Y(
73       getTheWebAssemblyTarget64());
74 
75   // Register backend passes
76   auto &PR = *PassRegistry::getPassRegistry();
77   initializeWebAssemblyAddMissingPrototypesPass(PR);
78   initializeWebAssemblyLowerEmscriptenEHSjLjPass(PR);
79   initializeLowerGlobalDtorsPass(PR);
80   initializeFixFunctionBitcastsPass(PR);
81   initializeOptimizeReturnedPass(PR);
82   initializeWebAssemblyArgumentMovePass(PR);
83   initializeWebAssemblySetP2AlignOperandsPass(PR);
84   initializeWebAssemblyReplacePhysRegsPass(PR);
85   initializeWebAssemblyPrepareForLiveIntervalsPass(PR);
86   initializeWebAssemblyOptimizeLiveIntervalsPass(PR);
87   initializeWebAssemblyMemIntrinsicResultsPass(PR);
88   initializeWebAssemblyRegStackifyPass(PR);
89   initializeWebAssemblyRegColoringPass(PR);
90   initializeWebAssemblyNullifyDebugValueListsPass(PR);
91   initializeWebAssemblyFixIrreducibleControlFlowPass(PR);
92   initializeWebAssemblyLateEHPreparePass(PR);
93   initializeWebAssemblyExceptionInfoPass(PR);
94   initializeWebAssemblyCFGSortPass(PR);
95   initializeWebAssemblyCFGStackifyPass(PR);
96   initializeWebAssemblyExplicitLocalsPass(PR);
97   initializeWebAssemblyLowerBrUnlessPass(PR);
98   initializeWebAssemblyRegNumberingPass(PR);
99   initializeWebAssemblyDebugFixupPass(PR);
100   initializeWebAssemblyPeepholePass(PR);
101   initializeWebAssemblyMCLowerPrePassPass(PR);
102 }
103 
104 //===----------------------------------------------------------------------===//
105 // WebAssembly Lowering public interface.
106 //===----------------------------------------------------------------------===//
107 
108 static Reloc::Model getEffectiveRelocModel(Optional<Reloc::Model> RM,
109                                            const Triple &TT) {
110   if (!RM.hasValue()) {
111     // Default to static relocation model.  This should always be more optimial
112     // than PIC since the static linker can determine all global addresses and
113     // assume direct function calls.
114     return Reloc::Static;
115   }
116 
117   if (!TT.isOSEmscripten()) {
118     // Relocation modes other than static are currently implemented in a way
119     // that only works for Emscripten, so disable them if we aren't targeting
120     // Emscripten.
121     return Reloc::Static;
122   }
123 
124   return *RM;
125 }
126 
127 /// Create an WebAssembly architecture model.
128 ///
129 WebAssemblyTargetMachine::WebAssemblyTargetMachine(
130     const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
131     const TargetOptions &Options, Optional<Reloc::Model> RM,
132     Optional<CodeModel::Model> CM, CodeGenOpt::Level OL, bool JIT)
133     : LLVMTargetMachine(
134           T,
135           TT.isArch64Bit()
136               ? (TT.isOSEmscripten() ? "e-m:e-p:64:64-p10:8:8-p20:8:8-i64:64-"
137                                        "f128:64-n32:64-S128-ni:1:10:20"
138                                      : "e-m:e-p:64:64-p10:8:8-p20:8:8-i64:64-"
139                                        "n32:64-S128-ni:1:10:20")
140               : (TT.isOSEmscripten() ? "e-m:e-p:32:32-p10:8:8-p20:8:8-i64:64-"
141                                        "f128:64-n32:64-S128-ni:1:10:20"
142                                      : "e-m:e-p:32:32-p10:8:8-p20:8:8-i64:64-"
143                                        "n32:64-S128-ni:1:10:20"),
144           TT, CPU, FS, Options, getEffectiveRelocModel(RM, TT),
145           getEffectiveCodeModel(CM, CodeModel::Large), OL),
146       TLOF(new WebAssemblyTargetObjectFile()) {
147   // WebAssembly type-checks instructions, but a noreturn function with a return
148   // type that doesn't match the context will cause a check failure. So we lower
149   // LLVM 'unreachable' to ISD::TRAP and then lower that to WebAssembly's
150   // 'unreachable' instructions which is meant for that case.
151   this->Options.TrapUnreachable = true;
152 
153   // WebAssembly treats each function as an independent unit. Force
154   // -ffunction-sections, effectively, so that we can emit them independently.
155   this->Options.FunctionSections = true;
156   this->Options.DataSections = true;
157   this->Options.UniqueSectionNames = true;
158 
159   initAsmInfo();
160 
161   // Note that we don't use setRequiresStructuredCFG(true). It disables
162   // optimizations than we're ok with, and want, such as critical edge
163   // splitting and tail merging.
164 }
165 
166 WebAssemblyTargetMachine::~WebAssemblyTargetMachine() = default; // anchor.
167 
168 const WebAssemblySubtarget *WebAssemblyTargetMachine::getSubtargetImpl() const {
169   return getSubtargetImpl(std::string(getTargetCPU()),
170                           std::string(getTargetFeatureString()));
171 }
172 
173 const WebAssemblySubtarget *
174 WebAssemblyTargetMachine::getSubtargetImpl(std::string CPU,
175                                            std::string FS) const {
176   auto &I = SubtargetMap[CPU + FS];
177   if (!I) {
178     I = std::make_unique<WebAssemblySubtarget>(TargetTriple, CPU, FS, *this);
179   }
180   return I.get();
181 }
182 
183 const WebAssemblySubtarget *
184 WebAssemblyTargetMachine::getSubtargetImpl(const Function &F) const {
185   Attribute CPUAttr = F.getFnAttribute("target-cpu");
186   Attribute FSAttr = F.getFnAttribute("target-features");
187 
188   std::string CPU =
189       CPUAttr.isValid() ? CPUAttr.getValueAsString().str() : TargetCPU;
190   std::string FS =
191       FSAttr.isValid() ? FSAttr.getValueAsString().str() : TargetFS;
192 
193   // This needs to be done before we create a new subtarget since any
194   // creation will depend on the TM and the code generation flags on the
195   // function that reside in TargetOptions.
196   resetTargetOptions(F);
197 
198   return getSubtargetImpl(CPU, FS);
199 }
200 
201 namespace {
202 
203 class CoalesceFeaturesAndStripAtomics final : public ModulePass {
204   // Take the union of all features used in the module and use it for each
205   // function individually, since having multiple feature sets in one module
206   // currently does not make sense for WebAssembly. If atomics are not enabled,
207   // also strip atomic operations and thread local storage.
208   static char ID;
209   WebAssemblyTargetMachine *WasmTM;
210 
211 public:
212   CoalesceFeaturesAndStripAtomics(WebAssemblyTargetMachine *WasmTM)
213       : ModulePass(ID), WasmTM(WasmTM) {}
214 
215   bool runOnModule(Module &M) override {
216     FeatureBitset Features = coalesceFeatures(M);
217 
218     std::string FeatureStr = getFeatureString(Features);
219     WasmTM->setTargetFeatureString(FeatureStr);
220     for (auto &F : M)
221       replaceFeatures(F, FeatureStr);
222 
223     bool StrippedAtomics = false;
224     bool StrippedTLS = false;
225 
226     if (!Features[WebAssembly::FeatureAtomics])
227       StrippedAtomics = stripAtomics(M);
228 
229     if (!Features[WebAssembly::FeatureBulkMemory])
230       StrippedTLS = stripThreadLocals(M);
231 
232     if (StrippedAtomics && !StrippedTLS)
233       stripThreadLocals(M);
234     else if (StrippedTLS && !StrippedAtomics)
235       stripAtomics(M);
236 
237     recordFeatures(M, Features, StrippedAtomics || StrippedTLS);
238 
239     // Conservatively assume we have made some change
240     return true;
241   }
242 
243 private:
244   FeatureBitset coalesceFeatures(const Module &M) {
245     FeatureBitset Features =
246         WasmTM
247             ->getSubtargetImpl(std::string(WasmTM->getTargetCPU()),
248                                std::string(WasmTM->getTargetFeatureString()))
249             ->getFeatureBits();
250     for (auto &F : M)
251       Features |= WasmTM->getSubtargetImpl(F)->getFeatureBits();
252     return Features;
253   }
254 
255   std::string getFeatureString(const FeatureBitset &Features) {
256     std::string Ret;
257     for (const SubtargetFeatureKV &KV : WebAssemblyFeatureKV) {
258       if (Features[KV.Value])
259         Ret += (StringRef("+") + KV.Key + ",").str();
260     }
261     return Ret;
262   }
263 
264   void replaceFeatures(Function &F, const std::string &Features) {
265     F.removeFnAttr("target-features");
266     F.removeFnAttr("target-cpu");
267     F.addFnAttr("target-features", Features);
268   }
269 
270   bool stripAtomics(Module &M) {
271     // Detect whether any atomics will be lowered, since there is no way to tell
272     // whether the LowerAtomic pass lowers e.g. stores.
273     bool Stripped = false;
274     for (auto &F : M) {
275       for (auto &B : F) {
276         for (auto &I : B) {
277           if (I.isAtomic()) {
278             Stripped = true;
279             goto done;
280           }
281         }
282       }
283     }
284 
285   done:
286     if (!Stripped)
287       return false;
288 
289     LowerAtomicPass Lowerer;
290     FunctionAnalysisManager FAM;
291     for (auto &F : M)
292       Lowerer.run(F, FAM);
293 
294     return true;
295   }
296 
297   bool stripThreadLocals(Module &M) {
298     bool Stripped = false;
299     for (auto &GV : M.globals()) {
300       if (GV.isThreadLocal()) {
301         Stripped = true;
302         GV.setThreadLocal(false);
303       }
304     }
305     return Stripped;
306   }
307 
308   void recordFeatures(Module &M, const FeatureBitset &Features, bool Stripped) {
309     for (const SubtargetFeatureKV &KV : WebAssemblyFeatureKV) {
310       if (Features[KV.Value]) {
311         // Mark features as used
312         std::string MDKey = (StringRef("wasm-feature-") + KV.Key).str();
313         M.addModuleFlag(Module::ModFlagBehavior::Error, MDKey,
314                         wasm::WASM_FEATURE_PREFIX_USED);
315       }
316     }
317     // Code compiled without atomics or bulk-memory may have had its atomics or
318     // thread-local data lowered to nonatomic operations or non-thread-local
319     // data. In that case, we mark the pseudo-feature "shared-mem" as disallowed
320     // to tell the linker that it would be unsafe to allow this code ot be used
321     // in a module with shared memory.
322     if (Stripped) {
323       M.addModuleFlag(Module::ModFlagBehavior::Error, "wasm-feature-shared-mem",
324                       wasm::WASM_FEATURE_PREFIX_DISALLOWED);
325     }
326   }
327 };
328 char CoalesceFeaturesAndStripAtomics::ID = 0;
329 
330 /// WebAssembly Code Generator Pass Configuration Options.
331 class WebAssemblyPassConfig final : public TargetPassConfig {
332 public:
333   WebAssemblyPassConfig(WebAssemblyTargetMachine &TM, PassManagerBase &PM)
334       : TargetPassConfig(TM, PM) {}
335 
336   WebAssemblyTargetMachine &getWebAssemblyTargetMachine() const {
337     return getTM<WebAssemblyTargetMachine>();
338   }
339 
340   FunctionPass *createTargetRegisterAllocator(bool) override;
341 
342   void addIRPasses() override;
343   bool addInstSelector() override;
344   void addPostRegAlloc() override;
345   bool addGCPasses() override { return false; }
346   void addPreEmitPass() override;
347   bool addPreISel() override;
348 
349   // No reg alloc
350   bool addRegAssignAndRewriteFast() override { return false; }
351 
352   // No reg alloc
353   bool addRegAssignAndRewriteOptimized() override { return false; }
354 };
355 } // end anonymous namespace
356 
357 TargetTransformInfo
358 WebAssemblyTargetMachine::getTargetTransformInfo(const Function &F) {
359   return TargetTransformInfo(WebAssemblyTTIImpl(this, F));
360 }
361 
362 TargetPassConfig *
363 WebAssemblyTargetMachine::createPassConfig(PassManagerBase &PM) {
364   return new WebAssemblyPassConfig(*this, PM);
365 }
366 
367 FunctionPass *WebAssemblyPassConfig::createTargetRegisterAllocator(bool) {
368   return nullptr; // No reg alloc
369 }
370 
371 static void checkSanityForEHAndSjLj(const TargetMachine *TM) {
372   // Sanity checking related to -exception-model
373   if (TM->Options.ExceptionModel != ExceptionHandling::None &&
374       TM->Options.ExceptionModel != ExceptionHandling::Wasm)
375     report_fatal_error("-exception-model should be either 'none' or 'wasm'");
376   if (WasmEnableEmEH && TM->Options.ExceptionModel == ExceptionHandling::Wasm)
377     report_fatal_error("-exception-model=wasm not allowed with "
378                        "-enable-emscripten-cxx-exceptions");
379   if (WasmEnableEH && TM->Options.ExceptionModel != ExceptionHandling::Wasm)
380     report_fatal_error(
381         "-wasm-enable-eh only allowed with -exception-model=wasm");
382   if (WasmEnableSjLj && TM->Options.ExceptionModel != ExceptionHandling::Wasm)
383     report_fatal_error(
384         "-wasm-enable-sjlj only allowed with -exception-model=wasm");
385   if ((!WasmEnableEH && !WasmEnableSjLj) &&
386       TM->Options.ExceptionModel == ExceptionHandling::Wasm)
387     report_fatal_error(
388         "-exception-model=wasm only allowed with at least one of "
389         "-wasm-enable-eh or -wasm-enable-sjj");
390 
391   // You can't enable two modes of EH at the same time
392   if (WasmEnableEmEH && WasmEnableEH)
393     report_fatal_error(
394         "-enable-emscripten-cxx-exceptions not allowed with -wasm-enable-eh");
395   // You can't enable two modes of SjLj at the same time
396   if (WasmEnableEmSjLj && WasmEnableSjLj)
397     report_fatal_error(
398         "-enable-emscripten-sjlj not allowed with -wasm-enable-sjlj");
399   // You can't mix Emscripten EH with Wasm SjLj.
400   if (WasmEnableEmEH && WasmEnableSjLj)
401     report_fatal_error(
402         "-enable-emscripten-cxx-exceptions not allowed with -wasm-enable-sjlj");
403   // Currently it is allowed to mix Wasm EH with Emscripten SjLj as an interim
404   // measure, but some code will error out at compile time in this combination.
405   // See WebAssemblyLowerEmscriptenEHSjLj pass for details.
406 }
407 
408 //===----------------------------------------------------------------------===//
409 // The following functions are called from lib/CodeGen/Passes.cpp to modify
410 // the CodeGen pass sequence.
411 //===----------------------------------------------------------------------===//
412 
413 void WebAssemblyPassConfig::addIRPasses() {
414   // Lower atomics and TLS if necessary
415   addPass(new CoalesceFeaturesAndStripAtomics(&getWebAssemblyTargetMachine()));
416 
417   // This is a no-op if atomics are not used in the module
418   addPass(createAtomicExpandPass());
419 
420   // Add signatures to prototype-less function declarations
421   addPass(createWebAssemblyAddMissingPrototypes());
422 
423   // Lower .llvm.global_dtors into .llvm_global_ctors with __cxa_atexit calls.
424   addPass(createWebAssemblyLowerGlobalDtors());
425 
426   // Fix function bitcasts, as WebAssembly requires caller and callee signatures
427   // to match.
428   addPass(createWebAssemblyFixFunctionBitcasts());
429 
430   // Optimize "returned" function attributes.
431   if (getOptLevel() != CodeGenOpt::None)
432     addPass(createWebAssemblyOptimizeReturned());
433 
434   checkSanityForEHAndSjLj(TM);
435 
436   // If exception handling is not enabled and setjmp/longjmp handling is
437   // enabled, we lower invokes into calls and delete unreachable landingpad
438   // blocks. Lowering invokes when there is no EH support is done in
439   // TargetPassConfig::addPassesToHandleExceptions, but that runs after these IR
440   // passes and Emscripten SjLj handling expects all invokes to be lowered
441   // before.
442   if (!WasmEnableEmEH && !WasmEnableEH) {
443     addPass(createLowerInvokePass());
444     // The lower invoke pass may create unreachable code. Remove it in order not
445     // to process dead blocks in setjmp/longjmp handling.
446     addPass(createUnreachableBlockEliminationPass());
447   }
448 
449   // Handle exceptions and setjmp/longjmp if enabled. Unlike Wasm EH preparation
450   // done in WasmEHPrepare pass, Wasm SjLj preparation shares libraries and
451   // transformation algorithms with Emscripten SjLj, so we run
452   // LowerEmscriptenEHSjLj pass also when Wasm SjLj is enabled.
453   if (WasmEnableEmEH || WasmEnableEmSjLj || WasmEnableSjLj)
454     addPass(createWebAssemblyLowerEmscriptenEHSjLj());
455 
456   // Expand indirectbr instructions to switches.
457   addPass(createIndirectBrExpandPass());
458 
459   TargetPassConfig::addIRPasses();
460 }
461 
462 bool WebAssemblyPassConfig::addInstSelector() {
463   (void)TargetPassConfig::addInstSelector();
464   addPass(
465       createWebAssemblyISelDag(getWebAssemblyTargetMachine(), getOptLevel()));
466   // Run the argument-move pass immediately after the ScheduleDAG scheduler
467   // so that we can fix up the ARGUMENT instructions before anything else
468   // sees them in the wrong place.
469   addPass(createWebAssemblyArgumentMove());
470   // Set the p2align operands. This information is present during ISel, however
471   // it's inconvenient to collect. Collect it now, and update the immediate
472   // operands.
473   addPass(createWebAssemblySetP2AlignOperands());
474 
475   // Eliminate range checks and add default targets to br_table instructions.
476   addPass(createWebAssemblyFixBrTableDefaults());
477 
478   return false;
479 }
480 
481 void WebAssemblyPassConfig::addPostRegAlloc() {
482   // TODO: The following CodeGen passes don't currently support code containing
483   // virtual registers. Consider removing their restrictions and re-enabling
484   // them.
485 
486   // These functions all require the NoVRegs property.
487   disablePass(&MachineCopyPropagationID);
488   disablePass(&PostRAMachineSinkingID);
489   disablePass(&PostRASchedulerID);
490   disablePass(&FuncletLayoutID);
491   disablePass(&StackMapLivenessID);
492   disablePass(&LiveDebugValuesID);
493   disablePass(&PatchableFunctionID);
494   disablePass(&ShrinkWrapID);
495 
496   // This pass hurts code size for wasm because it can generate irreducible
497   // control flow.
498   disablePass(&MachineBlockPlacementID);
499 
500   TargetPassConfig::addPostRegAlloc();
501 }
502 
503 void WebAssemblyPassConfig::addPreEmitPass() {
504   TargetPassConfig::addPreEmitPass();
505 
506   // Nullify DBG_VALUE_LISTs that we cannot handle.
507   addPass(createWebAssemblyNullifyDebugValueLists());
508 
509   // Eliminate multiple-entry loops.
510   addPass(createWebAssemblyFixIrreducibleControlFlow());
511 
512   // Do various transformations for exception handling.
513   // Every CFG-changing optimizations should come before this.
514   if (TM->Options.ExceptionModel == ExceptionHandling::Wasm)
515     addPass(createWebAssemblyLateEHPrepare());
516 
517   // Now that we have a prologue and epilogue and all frame indices are
518   // rewritten, eliminate SP and FP. This allows them to be stackified,
519   // colored, and numbered with the rest of the registers.
520   addPass(createWebAssemblyReplacePhysRegs());
521 
522   // Preparations and optimizations related to register stackification.
523   if (getOptLevel() != CodeGenOpt::None) {
524     // LiveIntervals isn't commonly run this late. Re-establish preconditions.
525     addPass(createWebAssemblyPrepareForLiveIntervals());
526 
527     // Depend on LiveIntervals and perform some optimizations on it.
528     addPass(createWebAssemblyOptimizeLiveIntervals());
529 
530     // Prepare memory intrinsic calls for register stackifying.
531     addPass(createWebAssemblyMemIntrinsicResults());
532 
533     // Mark registers as representing wasm's value stack. This is a key
534     // code-compression technique in WebAssembly. We run this pass (and
535     // MemIntrinsicResults above) very late, so that it sees as much code as
536     // possible, including code emitted by PEI and expanded by late tail
537     // duplication.
538     addPass(createWebAssemblyRegStackify());
539 
540     // Run the register coloring pass to reduce the total number of registers.
541     // This runs after stackification so that it doesn't consider registers
542     // that become stackified.
543     addPass(createWebAssemblyRegColoring());
544   }
545 
546   // Sort the blocks of the CFG into topological order, a prerequisite for
547   // BLOCK and LOOP markers.
548   addPass(createWebAssemblyCFGSort());
549 
550   // Insert BLOCK and LOOP markers.
551   addPass(createWebAssemblyCFGStackify());
552 
553   // Insert explicit local.get and local.set operators.
554   if (!WasmDisableExplicitLocals)
555     addPass(createWebAssemblyExplicitLocals());
556 
557   // Lower br_unless into br_if.
558   addPass(createWebAssemblyLowerBrUnless());
559 
560   // Perform the very last peephole optimizations on the code.
561   if (getOptLevel() != CodeGenOpt::None)
562     addPass(createWebAssemblyPeephole());
563 
564   // Create a mapping from LLVM CodeGen virtual registers to wasm registers.
565   addPass(createWebAssemblyRegNumbering());
566 
567   // Fix debug_values whose defs have been stackified.
568   if (!WasmDisableExplicitLocals)
569     addPass(createWebAssemblyDebugFixup());
570 
571   // Collect information to prepare for MC lowering / asm printing.
572   addPass(createWebAssemblyMCLowerPrePass());
573 }
574 
575 bool WebAssemblyPassConfig::addPreISel() {
576   TargetPassConfig::addPreISel();
577   addPass(createWebAssemblyLowerRefTypesIntPtrConv());
578   return false;
579 }
580 
581 yaml::MachineFunctionInfo *
582 WebAssemblyTargetMachine::createDefaultFuncInfoYAML() const {
583   return new yaml::WebAssemblyFunctionInfo();
584 }
585 
586 yaml::MachineFunctionInfo *WebAssemblyTargetMachine::convertFuncInfoToYAML(
587     const MachineFunction &MF) const {
588   const auto *MFI = MF.getInfo<WebAssemblyFunctionInfo>();
589   return new yaml::WebAssemblyFunctionInfo(*MFI);
590 }
591 
592 bool WebAssemblyTargetMachine::parseMachineFunctionInfo(
593     const yaml::MachineFunctionInfo &MFI, PerFunctionMIParsingState &PFS,
594     SMDiagnostic &Error, SMRange &SourceRange) const {
595   const auto &YamlMFI =
596       reinterpret_cast<const yaml::WebAssemblyFunctionInfo &>(MFI);
597   MachineFunction &MF = PFS.MF;
598   MF.getInfo<WebAssemblyFunctionInfo>()->initializeBaseYamlFields(YamlMFI);
599   return false;
600 }
601