14fc4e42dSDan Gohman //===-- WebAssemblyExplicitLocals.cpp - Make Locals Explicit --------------===//
24fc4e42dSDan Gohman //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
64fc4e42dSDan Gohman //
74fc4e42dSDan Gohman //===----------------------------------------------------------------------===//
84fc4e42dSDan Gohman ///
94fc4e42dSDan Gohman /// \file
105f8f34e4SAdrian Prantl /// This file converts any remaining registers into WebAssembly locals.
114fc4e42dSDan Gohman ///
124fc4e42dSDan Gohman /// After register stackification and register coloring, convert non-stackified
136a87ddacSThomas Lively /// registers into locals, inserting explicit local.get and local.set
144fc4e42dSDan Gohman /// instructions.
154fc4e42dSDan Gohman ///
164fc4e42dSDan Gohman //===----------------------------------------------------------------------===//
174fc4e42dSDan Gohman 
184fc4e42dSDan Gohman #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
19*0b2bc69bSHeejin Ahn #include "Utils/WebAssemblyUtilities.h"
204fc4e42dSDan Gohman #include "WebAssembly.h"
21adf7a0a5SYury Delendik #include "WebAssemblyDebugValueManager.h"
224fc4e42dSDan Gohman #include "WebAssemblyMachineFunctionInfo.h"
234fc4e42dSDan Gohman #include "WebAssemblySubtarget.h"
244fc4e42dSDan Gohman #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
254fc4e42dSDan Gohman #include "llvm/CodeGen/MachineInstrBuilder.h"
264fc4e42dSDan Gohman #include "llvm/CodeGen/MachineRegisterInfo.h"
274fc4e42dSDan Gohman #include "llvm/CodeGen/Passes.h"
284fc4e42dSDan Gohman #include "llvm/Support/Debug.h"
294fc4e42dSDan Gohman #include "llvm/Support/raw_ostream.h"
304fc4e42dSDan Gohman using namespace llvm;
314fc4e42dSDan Gohman 
324fc4e42dSDan Gohman #define DEBUG_TYPE "wasm-explicit-locals"
334fc4e42dSDan Gohman 
344fc4e42dSDan Gohman namespace {
354fc4e42dSDan Gohman class WebAssemblyExplicitLocals final : public MachineFunctionPass {
364fc4e42dSDan Gohman   StringRef getPassName() const override {
374fc4e42dSDan Gohman     return "WebAssembly Explicit Locals";
384fc4e42dSDan Gohman   }
394fc4e42dSDan Gohman 
404fc4e42dSDan Gohman   void getAnalysisUsage(AnalysisUsage &AU) const override {
414fc4e42dSDan Gohman     AU.setPreservesCFG();
424fc4e42dSDan Gohman     AU.addPreserved<MachineBlockFrequencyInfo>();
434fc4e42dSDan Gohman     MachineFunctionPass::getAnalysisUsage(AU);
444fc4e42dSDan Gohman   }
454fc4e42dSDan Gohman 
464fc4e42dSDan Gohman   bool runOnMachineFunction(MachineFunction &MF) override;
474fc4e42dSDan Gohman 
484fc4e42dSDan Gohman public:
494fc4e42dSDan Gohman   static char ID; // Pass identification, replacement for typeid
504fc4e42dSDan Gohman   WebAssemblyExplicitLocals() : MachineFunctionPass(ID) {}
514fc4e42dSDan Gohman };
524fc4e42dSDan Gohman } // end anonymous namespace
534fc4e42dSDan Gohman 
544fc4e42dSDan Gohman char WebAssemblyExplicitLocals::ID = 0;
5540926451SJacob Gravelle INITIALIZE_PASS(WebAssemblyExplicitLocals, DEBUG_TYPE,
5640926451SJacob Gravelle                 "Convert registers to WebAssembly locals", false, false)
5740926451SJacob Gravelle 
584fc4e42dSDan Gohman FunctionPass *llvm::createWebAssemblyExplicitLocals() {
594fc4e42dSDan Gohman   return new WebAssemblyExplicitLocals();
604fc4e42dSDan Gohman }
614fc4e42dSDan Gohman 
62a7a37517SWouter van Oortmerssen static void checkFrameBase(WebAssemblyFunctionInfo &MFI, unsigned Local,
63a7a37517SWouter van Oortmerssen                            unsigned Reg) {
64a7a37517SWouter van Oortmerssen   // Mark a local for the frame base vreg.
65a7a37517SWouter van Oortmerssen   if (MFI.isFrameBaseVirtual() && Reg == MFI.getFrameBaseVreg()) {
66a7a37517SWouter van Oortmerssen     LLVM_DEBUG({
67a7a37517SWouter van Oortmerssen       dbgs() << "Allocating local " << Local << "for VReg "
68a7a37517SWouter van Oortmerssen              << Register::virtReg2Index(Reg) << '\n';
69a7a37517SWouter van Oortmerssen     });
70a7a37517SWouter van Oortmerssen     MFI.setFrameBaseLocal(Local);
71a7a37517SWouter van Oortmerssen   }
72a7a37517SWouter van Oortmerssen }
73a7a37517SWouter van Oortmerssen 
744fc4e42dSDan Gohman /// Return a local id number for the given register, assigning it a new one
754fc4e42dSDan Gohman /// if it doesn't yet have one.
764fc4e42dSDan Gohman static unsigned getLocalId(DenseMap<unsigned, unsigned> &Reg2Local,
77ff171acfSDerek Schuff                            WebAssemblyFunctionInfo &MFI, unsigned &CurLocal,
78ff171acfSDerek Schuff                            unsigned Reg) {
79d934cb88SDan Gohman   auto P = Reg2Local.insert(std::make_pair(Reg, CurLocal));
80ff171acfSDerek Schuff   if (P.second) {
81a7a37517SWouter van Oortmerssen     checkFrameBase(MFI, CurLocal, Reg);
82d934cb88SDan Gohman     ++CurLocal;
83ff171acfSDerek Schuff   }
84d934cb88SDan Gohman   return P.first->second;
85d934cb88SDan Gohman }
86d934cb88SDan Gohman 
87d934cb88SDan Gohman /// Get the appropriate drop opcode for the given register class.
88d934cb88SDan Gohman static unsigned getDropOpcode(const TargetRegisterClass *RC) {
89d934cb88SDan Gohman   if (RC == &WebAssembly::I32RegClass)
90d934cb88SDan Gohman     return WebAssembly::DROP_I32;
91d934cb88SDan Gohman   if (RC == &WebAssembly::I64RegClass)
92d934cb88SDan Gohman     return WebAssembly::DROP_I64;
93d934cb88SDan Gohman   if (RC == &WebAssembly::F32RegClass)
94d934cb88SDan Gohman     return WebAssembly::DROP_F32;
95d934cb88SDan Gohman   if (RC == &WebAssembly::F64RegClass)
96d934cb88SDan Gohman     return WebAssembly::DROP_F64;
97d934cb88SDan Gohman   if (RC == &WebAssembly::V128RegClass)
98d934cb88SDan Gohman     return WebAssembly::DROP_V128;
9960653e24SHeejin Ahn   if (RC == &WebAssembly::FUNCREFRegClass)
10060653e24SHeejin Ahn     return WebAssembly::DROP_FUNCREF;
10160653e24SHeejin Ahn   if (RC == &WebAssembly::EXTERNREFRegClass)
10260653e24SHeejin Ahn     return WebAssembly::DROP_EXTERNREF;
103d934cb88SDan Gohman   llvm_unreachable("Unexpected register class");
1044fc4e42dSDan Gohman }
1054fc4e42dSDan Gohman 
1066a87ddacSThomas Lively /// Get the appropriate local.get opcode for the given register class.
10734dc1f24SHeejin Ahn static unsigned getLocalGetOpcode(const TargetRegisterClass *RC) {
1084fc4e42dSDan Gohman   if (RC == &WebAssembly::I32RegClass)
1096a87ddacSThomas Lively     return WebAssembly::LOCAL_GET_I32;
1104fc4e42dSDan Gohman   if (RC == &WebAssembly::I64RegClass)
1116a87ddacSThomas Lively     return WebAssembly::LOCAL_GET_I64;
1124fc4e42dSDan Gohman   if (RC == &WebAssembly::F32RegClass)
1136a87ddacSThomas Lively     return WebAssembly::LOCAL_GET_F32;
1144fc4e42dSDan Gohman   if (RC == &WebAssembly::F64RegClass)
1156a87ddacSThomas Lively     return WebAssembly::LOCAL_GET_F64;
1164fc4e42dSDan Gohman   if (RC == &WebAssembly::V128RegClass)
1176a87ddacSThomas Lively     return WebAssembly::LOCAL_GET_V128;
11869e2797eSPaulo Matos   if (RC == &WebAssembly::FUNCREFRegClass)
11969e2797eSPaulo Matos     return WebAssembly::LOCAL_GET_FUNCREF;
12069e2797eSPaulo Matos   if (RC == &WebAssembly::EXTERNREFRegClass)
12169e2797eSPaulo Matos     return WebAssembly::LOCAL_GET_EXTERNREF;
1224fc4e42dSDan Gohman   llvm_unreachable("Unexpected register class");
1234fc4e42dSDan Gohman }
1244fc4e42dSDan Gohman 
1256a87ddacSThomas Lively /// Get the appropriate local.set opcode for the given register class.
12634dc1f24SHeejin Ahn static unsigned getLocalSetOpcode(const TargetRegisterClass *RC) {
1274fc4e42dSDan Gohman   if (RC == &WebAssembly::I32RegClass)
1286a87ddacSThomas Lively     return WebAssembly::LOCAL_SET_I32;
1294fc4e42dSDan Gohman   if (RC == &WebAssembly::I64RegClass)
1306a87ddacSThomas Lively     return WebAssembly::LOCAL_SET_I64;
1314fc4e42dSDan Gohman   if (RC == &WebAssembly::F32RegClass)
1326a87ddacSThomas Lively     return WebAssembly::LOCAL_SET_F32;
1334fc4e42dSDan Gohman   if (RC == &WebAssembly::F64RegClass)
1346a87ddacSThomas Lively     return WebAssembly::LOCAL_SET_F64;
1354fc4e42dSDan Gohman   if (RC == &WebAssembly::V128RegClass)
1366a87ddacSThomas Lively     return WebAssembly::LOCAL_SET_V128;
13769e2797eSPaulo Matos   if (RC == &WebAssembly::FUNCREFRegClass)
13869e2797eSPaulo Matos     return WebAssembly::LOCAL_SET_FUNCREF;
13969e2797eSPaulo Matos   if (RC == &WebAssembly::EXTERNREFRegClass)
14069e2797eSPaulo Matos     return WebAssembly::LOCAL_SET_EXTERNREF;
1414fc4e42dSDan Gohman   llvm_unreachable("Unexpected register class");
1424fc4e42dSDan Gohman }
1434fc4e42dSDan Gohman 
1446a87ddacSThomas Lively /// Get the appropriate local.tee opcode for the given register class.
14534dc1f24SHeejin Ahn static unsigned getLocalTeeOpcode(const TargetRegisterClass *RC) {
1464fc4e42dSDan Gohman   if (RC == &WebAssembly::I32RegClass)
1476a87ddacSThomas Lively     return WebAssembly::LOCAL_TEE_I32;
1484fc4e42dSDan Gohman   if (RC == &WebAssembly::I64RegClass)
1496a87ddacSThomas Lively     return WebAssembly::LOCAL_TEE_I64;
1504fc4e42dSDan Gohman   if (RC == &WebAssembly::F32RegClass)
1516a87ddacSThomas Lively     return WebAssembly::LOCAL_TEE_F32;
1524fc4e42dSDan Gohman   if (RC == &WebAssembly::F64RegClass)
1536a87ddacSThomas Lively     return WebAssembly::LOCAL_TEE_F64;
1544fc4e42dSDan Gohman   if (RC == &WebAssembly::V128RegClass)
1556a87ddacSThomas Lively     return WebAssembly::LOCAL_TEE_V128;
15669e2797eSPaulo Matos   if (RC == &WebAssembly::FUNCREFRegClass)
15769e2797eSPaulo Matos     return WebAssembly::LOCAL_TEE_FUNCREF;
15869e2797eSPaulo Matos   if (RC == &WebAssembly::EXTERNREFRegClass)
15969e2797eSPaulo Matos     return WebAssembly::LOCAL_TEE_EXTERNREF;
1604fc4e42dSDan Gohman   llvm_unreachable("Unexpected register class");
1614fc4e42dSDan Gohman }
1624fc4e42dSDan Gohman 
1634fc4e42dSDan Gohman /// Get the type associated with the given register class.
1643acb187dSDan Gohman static MVT typeForRegClass(const TargetRegisterClass *RC) {
1654fc4e42dSDan Gohman   if (RC == &WebAssembly::I32RegClass)
1663acb187dSDan Gohman     return MVT::i32;
1674fc4e42dSDan Gohman   if (RC == &WebAssembly::I64RegClass)
1683acb187dSDan Gohman     return MVT::i64;
1694fc4e42dSDan Gohman   if (RC == &WebAssembly::F32RegClass)
1703acb187dSDan Gohman     return MVT::f32;
1714fc4e42dSDan Gohman   if (RC == &WebAssembly::F64RegClass)
1723acb187dSDan Gohman     return MVT::f64;
173409f5840SThomas Lively   if (RC == &WebAssembly::V128RegClass)
174409f5840SThomas Lively     return MVT::v16i8;
17569e2797eSPaulo Matos   if (RC == &WebAssembly::FUNCREFRegClass)
17669e2797eSPaulo Matos     return MVT::funcref;
17769e2797eSPaulo Matos   if (RC == &WebAssembly::EXTERNREFRegClass)
17869e2797eSPaulo Matos     return MVT::externref;
1794fc4e42dSDan Gohman   llvm_unreachable("unrecognized register class");
1804fc4e42dSDan Gohman }
1814fc4e42dSDan Gohman 
1824fc4e42dSDan Gohman /// Given a MachineOperand of a stackified vreg, return the instruction at the
1834fc4e42dSDan Gohman /// start of the expression tree.
1848a9cb242SWouter van Oortmerssen static MachineInstr *findStartOfTree(MachineOperand &MO,
1854fc4e42dSDan Gohman                                      MachineRegisterInfo &MRI,
18652861809SThomas Lively                                      const WebAssemblyFunctionInfo &MFI) {
18705c145d6SDaniel Sanders   Register Reg = MO.getReg();
1884fc4e42dSDan Gohman   assert(MFI.isVRegStackified(Reg));
1894fc4e42dSDan Gohman   MachineInstr *Def = MRI.getVRegDef(Reg);
1904fc4e42dSDan Gohman 
19152861809SThomas Lively   // If this instruction has any non-stackified defs, it is the start
19252861809SThomas Lively   for (auto DefReg : Def->defs()) {
19352861809SThomas Lively     if (!MFI.isVRegStackified(DefReg.getReg())) {
19452861809SThomas Lively       return Def;
19552861809SThomas Lively     }
19652861809SThomas Lively   }
19752861809SThomas Lively 
1984fc4e42dSDan Gohman   // Find the first stackified use and proceed from there.
1994fc4e42dSDan Gohman   for (MachineOperand &DefMO : Def->explicit_uses()) {
2004fc4e42dSDan Gohman     if (!DefMO.isReg())
2014fc4e42dSDan Gohman       continue;
2028a9cb242SWouter van Oortmerssen     return findStartOfTree(DefMO, MRI, MFI);
2034fc4e42dSDan Gohman   }
2044fc4e42dSDan Gohman 
2054fc4e42dSDan Gohman   // If there were no stackified uses, we've reached the start.
2064fc4e42dSDan Gohman   return Def;
2074fc4e42dSDan Gohman }
2084fc4e42dSDan Gohman 
2094fc4e42dSDan Gohman bool WebAssemblyExplicitLocals::runOnMachineFunction(MachineFunction &MF) {
210d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "********** Make Locals Explicit **********\n"
2114fc4e42dSDan Gohman                        "********** Function: "
2124fc4e42dSDan Gohman                     << MF.getName() << '\n');
2134fc4e42dSDan Gohman 
2144fc4e42dSDan Gohman   bool Changed = false;
2154fc4e42dSDan Gohman   MachineRegisterInfo &MRI = MF.getRegInfo();
2164fc4e42dSDan Gohman   WebAssemblyFunctionInfo &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
2174fc4e42dSDan Gohman   const auto *TII = MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
2184fc4e42dSDan Gohman 
2194fc4e42dSDan Gohman   // Map non-stackified virtual registers to their local ids.
2204fc4e42dSDan Gohman   DenseMap<unsigned, unsigned> Reg2Local;
2214fc4e42dSDan Gohman 
2224fc4e42dSDan Gohman   // Handle ARGUMENTS first to ensure that they get the designated numbers.
2234fc4e42dSDan Gohman   for (MachineBasicBlock::iterator I = MF.begin()->begin(),
2244fc4e42dSDan Gohman                                    E = MF.begin()->end();
2254fc4e42dSDan Gohman        I != E;) {
2264fc4e42dSDan Gohman     MachineInstr &MI = *I++;
227d8ddf839SWouter van Oortmerssen     if (!WebAssembly::isArgument(MI.getOpcode()))
2284fc4e42dSDan Gohman       break;
22905c145d6SDaniel Sanders     Register Reg = MI.getOperand(0).getReg();
2304fc4e42dSDan Gohman     assert(!MFI.isVRegStackified(Reg));
231a7a37517SWouter van Oortmerssen     auto Local = static_cast<unsigned>(MI.getOperand(1).getImm());
232a7a37517SWouter van Oortmerssen     Reg2Local[Reg] = Local;
233a7a37517SWouter van Oortmerssen     checkFrameBase(MFI, Local, Reg);
2345c38ae36SWouter van Oortmerssen 
2355c38ae36SWouter van Oortmerssen     // Update debug value to point to the local before removing.
2365c38ae36SWouter van Oortmerssen     WebAssemblyDebugValueManager(&MI).replaceWithLocal(Local);
2375c38ae36SWouter van Oortmerssen 
2384fc4e42dSDan Gohman     MI.eraseFromParent();
2394fc4e42dSDan Gohman     Changed = true;
2404fc4e42dSDan Gohman   }
2414fc4e42dSDan Gohman 
2424fc4e42dSDan Gohman   // Start assigning local numbers after the last parameter.
2438a9cb242SWouter van Oortmerssen   unsigned CurLocal = static_cast<unsigned>(MFI.getParams().size());
2444fc4e42dSDan Gohman 
245d934cb88SDan Gohman   // Precompute the set of registers that are unused, so that we can insert
246d934cb88SDan Gohman   // drops to their defs.
247d934cb88SDan Gohman   BitVector UseEmpty(MRI.getNumVirtRegs());
2488a9cb242SWouter van Oortmerssen   for (unsigned I = 0, E = MRI.getNumVirtRegs(); I < E; ++I)
2492bea69bfSDaniel Sanders     UseEmpty[I] = MRI.use_empty(Register::index2VirtReg(I));
250d934cb88SDan Gohman 
2514fc4e42dSDan Gohman   // Visit each instruction in the function.
2524fc4e42dSDan Gohman   for (MachineBasicBlock &MBB : MF) {
2534fc4e42dSDan Gohman     for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E;) {
2544fc4e42dSDan Gohman       MachineInstr &MI = *I++;
255d8ddf839SWouter van Oortmerssen       assert(!WebAssembly::isArgument(MI.getOpcode()));
2564fc4e42dSDan Gohman 
257801bf7ebSShiva Chen       if (MI.isDebugInstr() || MI.isLabel())
2584fc4e42dSDan Gohman         continue;
2594fc4e42dSDan Gohman 
26052861809SThomas Lively       if (MI.getOpcode() == WebAssembly::IMPLICIT_DEF) {
26152861809SThomas Lively         MI.eraseFromParent();
26252861809SThomas Lively         Changed = true;
26352861809SThomas Lively         continue;
26452861809SThomas Lively       }
26552861809SThomas Lively 
2666a87ddacSThomas Lively       // Replace tee instructions with local.tee. The difference is that tee
2676a87ddacSThomas Lively       // instructions have two defs, while local.tee instructions have one def
2684fc4e42dSDan Gohman       // and an index of a local to write to.
269d8ddf839SWouter van Oortmerssen       if (WebAssembly::isTee(MI.getOpcode())) {
2704fc4e42dSDan Gohman         assert(MFI.isVRegStackified(MI.getOperand(0).getReg()));
2714fc4e42dSDan Gohman         assert(!MFI.isVRegStackified(MI.getOperand(1).getReg()));
27205c145d6SDaniel Sanders         Register OldReg = MI.getOperand(2).getReg();
2734fc4e42dSDan Gohman         const TargetRegisterClass *RC = MRI.getRegClass(OldReg);
2744fc4e42dSDan Gohman 
2754fc4e42dSDan Gohman         // Stackify the input if it isn't stackified yet.
2764fc4e42dSDan Gohman         if (!MFI.isVRegStackified(OldReg)) {
277ff171acfSDerek Schuff           unsigned LocalId = getLocalId(Reg2Local, MFI, CurLocal, OldReg);
27805c145d6SDaniel Sanders           Register NewReg = MRI.createVirtualRegister(RC);
27934dc1f24SHeejin Ahn           unsigned Opc = getLocalGetOpcode(RC);
2804fc4e42dSDan Gohman           BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(Opc), NewReg)
2814fc4e42dSDan Gohman               .addImm(LocalId);
2824fc4e42dSDan Gohman           MI.getOperand(2).setReg(NewReg);
283c5d24009SMatt Arsenault           MFI.stackifyVReg(MRI, NewReg);
2844fc4e42dSDan Gohman         }
2854fc4e42dSDan Gohman 
2866a87ddacSThomas Lively         // Replace the TEE with a LOCAL_TEE.
2874fc4e42dSDan Gohman         unsigned LocalId =
288ff171acfSDerek Schuff             getLocalId(Reg2Local, MFI, CurLocal, MI.getOperand(1).getReg());
28934dc1f24SHeejin Ahn         unsigned Opc = getLocalTeeOpcode(RC);
2904fc4e42dSDan Gohman         BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(Opc),
2914fc4e42dSDan Gohman                 MI.getOperand(0).getReg())
2924fc4e42dSDan Gohman             .addImm(LocalId)
2934fc4e42dSDan Gohman             .addReg(MI.getOperand(2).getReg());
2944fc4e42dSDan Gohman 
295adf7a0a5SYury Delendik         WebAssemblyDebugValueManager(&MI).replaceWithLocal(LocalId);
296adf7a0a5SYury Delendik 
2974fc4e42dSDan Gohman         MI.eraseFromParent();
2984fc4e42dSDan Gohman         Changed = true;
2994fc4e42dSDan Gohman         continue;
3004fc4e42dSDan Gohman       }
3014fc4e42dSDan Gohman 
30252861809SThomas Lively       // Insert local.sets for any defs that aren't stackified yet.
30352861809SThomas Lively       for (auto &Def : MI.defs()) {
30452861809SThomas Lively         Register OldReg = Def.getReg();
305d934cb88SDan Gohman         if (!MFI.isVRegStackified(OldReg)) {
3064fc4e42dSDan Gohman           const TargetRegisterClass *RC = MRI.getRegClass(OldReg);
30705c145d6SDaniel Sanders           Register NewReg = MRI.createVirtualRegister(RC);
3085c644c9bSHeejin Ahn           auto InsertPt = std::next(MI.getIterator());
3092bea69bfSDaniel Sanders           if (UseEmpty[Register::virtReg2Index(OldReg)]) {
310d934cb88SDan Gohman             unsigned Opc = getDropOpcode(RC);
311891a7472SHeejin Ahn             MachineInstr *Drop =
312d934cb88SDan Gohman                 BuildMI(MBB, InsertPt, MI.getDebugLoc(), TII->get(Opc))
313d934cb88SDan Gohman                     .addReg(NewReg);
314891a7472SHeejin Ahn             // After the drop instruction, this reg operand will not be used
315891a7472SHeejin Ahn             Drop->getOperand(0).setIsKill();
316e110897eSDerek Schuff             if (MFI.isFrameBaseVirtual() && OldReg == MFI.getFrameBaseVreg())
317e110897eSDerek Schuff               MFI.clearFrameBaseVreg();
318d934cb88SDan Gohman           } else {
319ff171acfSDerek Schuff             unsigned LocalId = getLocalId(Reg2Local, MFI, CurLocal, OldReg);
32034dc1f24SHeejin Ahn             unsigned Opc = getLocalSetOpcode(RC);
321adf7a0a5SYury Delendik 
322adf7a0a5SYury Delendik             WebAssemblyDebugValueManager(&MI).replaceWithLocal(LocalId);
323adf7a0a5SYury Delendik 
3244fc4e42dSDan Gohman             BuildMI(MBB, InsertPt, MI.getDebugLoc(), TII->get(Opc))
3254fc4e42dSDan Gohman                 .addImm(LocalId)
3264fc4e42dSDan Gohman                 .addReg(NewReg);
327d934cb88SDan Gohman           }
3284d98dfb6SHeejin Ahn           // This register operand of the original instruction is now being used
3296a87ddacSThomas Lively           // by the inserted drop or local.set instruction, so make it not dead
3304d98dfb6SHeejin Ahn           // yet.
33152861809SThomas Lively           Def.setReg(NewReg);
33252861809SThomas Lively           Def.setIsDead(false);
333c5d24009SMatt Arsenault           MFI.stackifyVReg(MRI, NewReg);
3344fc4e42dSDan Gohman           Changed = true;
3354fc4e42dSDan Gohman         }
3364fc4e42dSDan Gohman       }
3374fc4e42dSDan Gohman 
3386a87ddacSThomas Lively       // Insert local.gets for any uses that aren't stackified yet.
3394fc4e42dSDan Gohman       MachineInstr *InsertPt = &MI;
3404fc4e42dSDan Gohman       for (MachineOperand &MO : reverse(MI.explicit_uses())) {
3414fc4e42dSDan Gohman         if (!MO.isReg())
3424fc4e42dSDan Gohman           continue;
3434fc4e42dSDan Gohman 
34405c145d6SDaniel Sanders         Register OldReg = MO.getReg();
3454fc4e42dSDan Gohman 
346b465aa05SDan Gohman         // Inline asm may have a def in the middle of the operands. Our contract
347b465aa05SDan Gohman         // with inline asm register operands is to provide local indices as
348b465aa05SDan Gohman         // immediates.
349b465aa05SDan Gohman         if (MO.isDef()) {
350c45e39b3SCraig Topper           assert(MI.isInlineAsm());
351ff171acfSDerek Schuff           unsigned LocalId = getLocalId(Reg2Local, MFI, CurLocal, OldReg);
352300f42fbSHeejin Ahn           // If this register operand is tied to another operand, we can't
353300f42fbSHeejin Ahn           // change it to an immediate. Untie it first.
354300f42fbSHeejin Ahn           MI.untieRegOperand(MI.getOperandNo(&MO));
355045a217bSDan Gohman           MO.ChangeToImmediate(LocalId);
356b465aa05SDan Gohman           continue;
357b465aa05SDan Gohman         }
358b465aa05SDan Gohman 
3594fc4e42dSDan Gohman         // If we see a stackified register, prepare to insert subsequent
3606a87ddacSThomas Lively         // local.gets before the start of its tree.
3614fc4e42dSDan Gohman         if (MFI.isVRegStackified(OldReg)) {
3628a9cb242SWouter van Oortmerssen           InsertPt = findStartOfTree(MO, MRI, MFI);
3634fc4e42dSDan Gohman           continue;
3644fc4e42dSDan Gohman         }
3654fc4e42dSDan Gohman 
366b465aa05SDan Gohman         // Our contract with inline asm register operands is to provide local
367b465aa05SDan Gohman         // indices as immediates.
368c45e39b3SCraig Topper         if (MI.isInlineAsm()) {
369ff171acfSDerek Schuff           unsigned LocalId = getLocalId(Reg2Local, MFI, CurLocal, OldReg);
370300f42fbSHeejin Ahn           // Untie it first if this reg operand is tied to another operand.
371300f42fbSHeejin Ahn           MI.untieRegOperand(MI.getOperandNo(&MO));
372045a217bSDan Gohman           MO.ChangeToImmediate(LocalId);
373b465aa05SDan Gohman           continue;
374b465aa05SDan Gohman         }
375b465aa05SDan Gohman 
3766a87ddacSThomas Lively         // Insert a local.get.
377ff171acfSDerek Schuff         unsigned LocalId = getLocalId(Reg2Local, MFI, CurLocal, OldReg);
3784fc4e42dSDan Gohman         const TargetRegisterClass *RC = MRI.getRegClass(OldReg);
37905c145d6SDaniel Sanders         Register NewReg = MRI.createVirtualRegister(RC);
38034dc1f24SHeejin Ahn         unsigned Opc = getLocalGetOpcode(RC);
3814fc4e42dSDan Gohman         InsertPt =
3824fc4e42dSDan Gohman             BuildMI(MBB, InsertPt, MI.getDebugLoc(), TII->get(Opc), NewReg)
3834fc4e42dSDan Gohman                 .addImm(LocalId);
3844fc4e42dSDan Gohman         MO.setReg(NewReg);
385c5d24009SMatt Arsenault         MFI.stackifyVReg(MRI, NewReg);
3864fc4e42dSDan Gohman         Changed = true;
3874fc4e42dSDan Gohman       }
3884fc4e42dSDan Gohman 
3894fc4e42dSDan Gohman       // Coalesce and eliminate COPY instructions.
390d8ddf839SWouter van Oortmerssen       if (WebAssembly::isCopy(MI.getOpcode())) {
3914fc4e42dSDan Gohman         MRI.replaceRegWith(MI.getOperand(1).getReg(),
3924fc4e42dSDan Gohman                            MI.getOperand(0).getReg());
3934fc4e42dSDan Gohman         MI.eraseFromParent();
3944fc4e42dSDan Gohman         Changed = true;
3954fc4e42dSDan Gohman       }
3964fc4e42dSDan Gohman     }
3974fc4e42dSDan Gohman   }
3984fc4e42dSDan Gohman 
3993acb187dSDan Gohman   // Define the locals.
400d934cb88SDan Gohman   // TODO: Sort the locals for better compression.
401d934cb88SDan Gohman   MFI.setNumLocals(CurLocal - MFI.getParams().size());
4028a9cb242SWouter van Oortmerssen   for (unsigned I = 0, E = MRI.getNumVirtRegs(); I < E; ++I) {
4032bea69bfSDaniel Sanders     unsigned Reg = Register::index2VirtReg(I);
4048a9cb242SWouter van Oortmerssen     auto RL = Reg2Local.find(Reg);
4058a9cb242SWouter van Oortmerssen     if (RL == Reg2Local.end() || RL->second < MFI.getParams().size())
4064fc4e42dSDan Gohman       continue;
4074fc4e42dSDan Gohman 
4088a9cb242SWouter van Oortmerssen     MFI.setLocal(RL->second - MFI.getParams().size(),
409d934cb88SDan Gohman                  typeForRegClass(MRI.getRegClass(Reg)));
4104fc4e42dSDan Gohman     Changed = true;
4114fc4e42dSDan Gohman   }
4124fc4e42dSDan Gohman 
413a7be3755SWouter van Oortmerssen #ifndef NDEBUG
414a7be3755SWouter van Oortmerssen   // Assert that all registers have been stackified at this point.
415a7be3755SWouter van Oortmerssen   for (const MachineBasicBlock &MBB : MF) {
416a7be3755SWouter van Oortmerssen     for (const MachineInstr &MI : MBB) {
417a7be3755SWouter van Oortmerssen       if (MI.isDebugInstr() || MI.isLabel())
418a7be3755SWouter van Oortmerssen         continue;
419a7be3755SWouter van Oortmerssen       for (const MachineOperand &MO : MI.explicit_operands()) {
420a7be3755SWouter van Oortmerssen         assert(
421a7be3755SWouter van Oortmerssen             (!MO.isReg() || MRI.use_empty(MO.getReg()) ||
422a7be3755SWouter van Oortmerssen              MFI.isVRegStackified(MO.getReg())) &&
423a7be3755SWouter van Oortmerssen             "WebAssemblyExplicitLocals failed to stackify a register operand");
424a67c4137SWouter van Oortmerssen       }
425a7be3755SWouter van Oortmerssen     }
426a7be3755SWouter van Oortmerssen   }
427a7be3755SWouter van Oortmerssen #endif
428ab26bd06SWouter van Oortmerssen 
429a7be3755SWouter van Oortmerssen   return Changed;
430ab26bd06SWouter van Oortmerssen }
431