17d523365SDimitry Andric //===-- WebAssemblyRegStackify.cpp - Register Stackification --------------===//
27d523365SDimitry Andric //
37d523365SDimitry Andric //                     The LLVM Compiler Infrastructure
47d523365SDimitry Andric //
57d523365SDimitry Andric // This file is distributed under the University of Illinois Open Source
67d523365SDimitry Andric // License. See LICENSE.TXT for details.
77d523365SDimitry Andric //
87d523365SDimitry Andric //===----------------------------------------------------------------------===//
97d523365SDimitry Andric ///
107d523365SDimitry Andric /// \file
114ba319b5SDimitry Andric /// This file implements a register stacking pass.
127d523365SDimitry Andric ///
137d523365SDimitry Andric /// This pass reorders instructions to put register uses and defs in an order
147d523365SDimitry Andric /// such that they form single-use expression trees. Registers fitting this form
157d523365SDimitry Andric /// are then marked as "stackified", meaning references to them are replaced by
16d88c1a5aSDimitry Andric /// "push" and "pop" from the value stack.
177d523365SDimitry Andric ///
187d523365SDimitry Andric /// This is primarily a code size optimization, since temporary values on the
19d88c1a5aSDimitry Andric /// value stack don't need to be named.
207d523365SDimitry Andric ///
217d523365SDimitry Andric //===----------------------------------------------------------------------===//
227d523365SDimitry Andric 
237d523365SDimitry Andric #include "MCTargetDesc/WebAssemblyMCTargetDesc.h" // for WebAssembly::ARGUMENT_*
24db17bf38SDimitry Andric #include "WebAssembly.h"
25*b5893f02SDimitry Andric #include "WebAssemblyDebugValueManager.h"
267d523365SDimitry Andric #include "WebAssemblyMachineFunctionInfo.h"
273ca95b02SDimitry Andric #include "WebAssemblySubtarget.h"
28d88c1a5aSDimitry Andric #include "WebAssemblyUtilities.h"
29*b5893f02SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
307d523365SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
312cab237bSDimitry Andric #include "llvm/CodeGen/LiveIntervals.h"
327d523365SDimitry Andric #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
333ca95b02SDimitry Andric #include "llvm/CodeGen/MachineDominators.h"
343ca95b02SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
357a7e6055SDimitry Andric #include "llvm/CodeGen/MachineModuleInfoImpls.h"
367d523365SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
377d523365SDimitry Andric #include "llvm/CodeGen/Passes.h"
387d523365SDimitry Andric #include "llvm/Support/Debug.h"
397d523365SDimitry Andric #include "llvm/Support/raw_ostream.h"
407d523365SDimitry Andric using namespace llvm;
417d523365SDimitry Andric 
427d523365SDimitry Andric #define DEBUG_TYPE "wasm-reg-stackify"
437d523365SDimitry Andric 
447d523365SDimitry Andric namespace {
457d523365SDimitry Andric class WebAssemblyRegStackify final : public MachineFunctionPass {
getPassName() const46d88c1a5aSDimitry Andric   StringRef getPassName() const override {
477d523365SDimitry Andric     return "WebAssembly Register Stackify";
487d523365SDimitry Andric   }
497d523365SDimitry Andric 
getAnalysisUsage(AnalysisUsage & AU) const507d523365SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
517d523365SDimitry Andric     AU.setPreservesCFG();
527d523365SDimitry Andric     AU.addRequired<AAResultsWrapperPass>();
533ca95b02SDimitry Andric     AU.addRequired<MachineDominatorTree>();
547d523365SDimitry Andric     AU.addRequired<LiveIntervals>();
557d523365SDimitry Andric     AU.addPreserved<MachineBlockFrequencyInfo>();
567d523365SDimitry Andric     AU.addPreserved<SlotIndexes>();
577d523365SDimitry Andric     AU.addPreserved<LiveIntervals>();
587d523365SDimitry Andric     AU.addPreservedID(LiveVariablesID);
593ca95b02SDimitry Andric     AU.addPreserved<MachineDominatorTree>();
607d523365SDimitry Andric     MachineFunctionPass::getAnalysisUsage(AU);
617d523365SDimitry Andric   }
627d523365SDimitry Andric 
637d523365SDimitry Andric   bool runOnMachineFunction(MachineFunction &MF) override;
647d523365SDimitry Andric 
657d523365SDimitry Andric public:
667d523365SDimitry Andric   static char ID; // Pass identification, replacement for typeid
WebAssemblyRegStackify()677d523365SDimitry Andric   WebAssemblyRegStackify() : MachineFunctionPass(ID) {}
687d523365SDimitry Andric };
697d523365SDimitry Andric } // end anonymous namespace
707d523365SDimitry Andric 
717d523365SDimitry Andric char WebAssemblyRegStackify::ID = 0;
724ba319b5SDimitry Andric INITIALIZE_PASS(WebAssemblyRegStackify, DEBUG_TYPE,
734ba319b5SDimitry Andric                 "Reorder instructions to use the WebAssembly value stack",
744ba319b5SDimitry Andric                 false, false)
754ba319b5SDimitry Andric 
createWebAssemblyRegStackify()767d523365SDimitry Andric FunctionPass *llvm::createWebAssemblyRegStackify() {
777d523365SDimitry Andric   return new WebAssemblyRegStackify();
787d523365SDimitry Andric }
797d523365SDimitry Andric 
807d523365SDimitry Andric // Decorate the given instruction with implicit operands that enforce the
817d523365SDimitry Andric // expression stack ordering constraints for an instruction which is on
827d523365SDimitry Andric // the expression stack.
ImposeStackOrdering(MachineInstr * MI)837d523365SDimitry Andric static void ImposeStackOrdering(MachineInstr *MI) {
84d88c1a5aSDimitry Andric   // Write the opaque VALUE_STACK register.
85d88c1a5aSDimitry Andric   if (!MI->definesRegister(WebAssembly::VALUE_STACK))
86d88c1a5aSDimitry Andric     MI->addOperand(MachineOperand::CreateReg(WebAssembly::VALUE_STACK,
877d523365SDimitry Andric                                              /*isDef=*/true,
887d523365SDimitry Andric                                              /*isImp=*/true));
897d523365SDimitry Andric 
90d88c1a5aSDimitry Andric   // Also read the opaque VALUE_STACK register.
91d88c1a5aSDimitry Andric   if (!MI->readsRegister(WebAssembly::VALUE_STACK))
92d88c1a5aSDimitry Andric     MI->addOperand(MachineOperand::CreateReg(WebAssembly::VALUE_STACK,
937d523365SDimitry Andric                                              /*isDef=*/false,
947d523365SDimitry Andric                                              /*isImp=*/true));
957d523365SDimitry Andric }
967d523365SDimitry Andric 
97d88c1a5aSDimitry Andric // Convert an IMPLICIT_DEF instruction into an instruction which defines
98d88c1a5aSDimitry Andric // a constant zero value.
ConvertImplicitDefToConstZero(MachineInstr * MI,MachineRegisterInfo & MRI,const TargetInstrInfo * TII,MachineFunction & MF,LiveIntervals & LIS)99d88c1a5aSDimitry Andric static void ConvertImplicitDefToConstZero(MachineInstr *MI,
100d88c1a5aSDimitry Andric                                           MachineRegisterInfo &MRI,
101d88c1a5aSDimitry Andric                                           const TargetInstrInfo *TII,
102*b5893f02SDimitry Andric                                           MachineFunction &MF,
103*b5893f02SDimitry Andric                                           LiveIntervals &LIS) {
104d88c1a5aSDimitry Andric   assert(MI->getOpcode() == TargetOpcode::IMPLICIT_DEF);
105d88c1a5aSDimitry Andric 
106*b5893f02SDimitry Andric   const auto *RegClass = MRI.getRegClass(MI->getOperand(0).getReg());
107d88c1a5aSDimitry Andric   if (RegClass == &WebAssembly::I32RegClass) {
108d88c1a5aSDimitry Andric     MI->setDesc(TII->get(WebAssembly::CONST_I32));
109d88c1a5aSDimitry Andric     MI->addOperand(MachineOperand::CreateImm(0));
110d88c1a5aSDimitry Andric   } else if (RegClass == &WebAssembly::I64RegClass) {
111d88c1a5aSDimitry Andric     MI->setDesc(TII->get(WebAssembly::CONST_I64));
112d88c1a5aSDimitry Andric     MI->addOperand(MachineOperand::CreateImm(0));
113d88c1a5aSDimitry Andric   } else if (RegClass == &WebAssembly::F32RegClass) {
114d88c1a5aSDimitry Andric     MI->setDesc(TII->get(WebAssembly::CONST_F32));
115d88c1a5aSDimitry Andric     ConstantFP *Val = cast<ConstantFP>(Constant::getNullValue(
1162cab237bSDimitry Andric         Type::getFloatTy(MF.getFunction().getContext())));
117d88c1a5aSDimitry Andric     MI->addOperand(MachineOperand::CreateFPImm(Val));
118d88c1a5aSDimitry Andric   } else if (RegClass == &WebAssembly::F64RegClass) {
119d88c1a5aSDimitry Andric     MI->setDesc(TII->get(WebAssembly::CONST_F64));
120d88c1a5aSDimitry Andric     ConstantFP *Val = cast<ConstantFP>(Constant::getNullValue(
1212cab237bSDimitry Andric         Type::getDoubleTy(MF.getFunction().getContext())));
122d88c1a5aSDimitry Andric     MI->addOperand(MachineOperand::CreateFPImm(Val));
123*b5893f02SDimitry Andric   } else if (RegClass == &WebAssembly::V128RegClass) {
124*b5893f02SDimitry Andric     unsigned TempReg = MRI.createVirtualRegister(&WebAssembly::I32RegClass);
125*b5893f02SDimitry Andric     MI->setDesc(TII->get(WebAssembly::SPLAT_v4i32));
126*b5893f02SDimitry Andric     MI->addOperand(MachineOperand::CreateReg(TempReg, false));
127*b5893f02SDimitry Andric     MachineInstr *Const = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
128*b5893f02SDimitry Andric                                   TII->get(WebAssembly::CONST_I32), TempReg)
129*b5893f02SDimitry Andric                               .addImm(0);
130*b5893f02SDimitry Andric     LIS.InsertMachineInstrInMaps(*Const);
131d88c1a5aSDimitry Andric   } else {
132d88c1a5aSDimitry Andric     llvm_unreachable("Unexpected reg class");
133d88c1a5aSDimitry Andric   }
134d88c1a5aSDimitry Andric }
135d88c1a5aSDimitry Andric 
1363ca95b02SDimitry Andric // Determine whether a call to the callee referenced by
1373ca95b02SDimitry Andric // MI->getOperand(CalleeOpNo) reads memory, writes memory, and/or has side
1383ca95b02SDimitry Andric // effects.
QueryCallee(const MachineInstr & MI,unsigned CalleeOpNo,bool & Read,bool & Write,bool & Effects,bool & StackPointer)1393ca95b02SDimitry Andric static void QueryCallee(const MachineInstr &MI, unsigned CalleeOpNo, bool &Read,
1403ca95b02SDimitry Andric                         bool &Write, bool &Effects, bool &StackPointer) {
1413ca95b02SDimitry Andric   // All calls can use the stack pointer.
1423ca95b02SDimitry Andric   StackPointer = true;
1433ca95b02SDimitry Andric 
1443ca95b02SDimitry Andric   const MachineOperand &MO = MI.getOperand(CalleeOpNo);
1453ca95b02SDimitry Andric   if (MO.isGlobal()) {
1463ca95b02SDimitry Andric     const Constant *GV = MO.getGlobal();
1473ca95b02SDimitry Andric     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
1483ca95b02SDimitry Andric       if (!GA->isInterposable())
1493ca95b02SDimitry Andric         GV = GA->getAliasee();
1503ca95b02SDimitry Andric 
1513ca95b02SDimitry Andric     if (const Function *F = dyn_cast<Function>(GV)) {
1523ca95b02SDimitry Andric       if (!F->doesNotThrow())
1533ca95b02SDimitry Andric         Effects = true;
1543ca95b02SDimitry Andric       if (F->doesNotAccessMemory())
1553ca95b02SDimitry Andric         return;
1563ca95b02SDimitry Andric       if (F->onlyReadsMemory()) {
1573ca95b02SDimitry Andric         Read = true;
1583ca95b02SDimitry Andric         return;
1593ca95b02SDimitry Andric       }
1603ca95b02SDimitry Andric     }
1613ca95b02SDimitry Andric   }
1623ca95b02SDimitry Andric 
1633ca95b02SDimitry Andric   // Assume the worst.
1643ca95b02SDimitry Andric   Write = true;
1653ca95b02SDimitry Andric   Read = true;
1663ca95b02SDimitry Andric   Effects = true;
1673ca95b02SDimitry Andric }
1683ca95b02SDimitry Andric 
1693ca95b02SDimitry Andric // Determine whether MI reads memory, writes memory, has side effects,
1707a7e6055SDimitry Andric // and/or uses the stack pointer value.
Query(const MachineInstr & MI,AliasAnalysis & AA,bool & Read,bool & Write,bool & Effects,bool & StackPointer)1713ca95b02SDimitry Andric static void Query(const MachineInstr &MI, AliasAnalysis &AA, bool &Read,
1723ca95b02SDimitry Andric                   bool &Write, bool &Effects, bool &StackPointer) {
1733ca95b02SDimitry Andric   assert(!MI.isTerminator());
1743ca95b02SDimitry Andric 
1754ba319b5SDimitry Andric   if (MI.isDebugInstr() || MI.isPosition())
1763ca95b02SDimitry Andric     return;
1773ca95b02SDimitry Andric 
1783ca95b02SDimitry Andric   // Check for loads.
179d88c1a5aSDimitry Andric   if (MI.mayLoad() && !MI.isDereferenceableInvariantLoad(&AA))
1803ca95b02SDimitry Andric     Read = true;
1813ca95b02SDimitry Andric 
1823ca95b02SDimitry Andric   // Check for stores.
1833ca95b02SDimitry Andric   if (MI.mayStore()) {
1843ca95b02SDimitry Andric     Write = true;
1853ca95b02SDimitry Andric   } else if (MI.hasOrderedMemoryRef()) {
1863ca95b02SDimitry Andric     switch (MI.getOpcode()) {
187*b5893f02SDimitry Andric     case WebAssembly::DIV_S_I32:
188*b5893f02SDimitry Andric     case WebAssembly::DIV_S_I64:
189*b5893f02SDimitry Andric     case WebAssembly::REM_S_I32:
190*b5893f02SDimitry Andric     case WebAssembly::REM_S_I64:
191*b5893f02SDimitry Andric     case WebAssembly::DIV_U_I32:
192*b5893f02SDimitry Andric     case WebAssembly::DIV_U_I64:
193*b5893f02SDimitry Andric     case WebAssembly::REM_U_I32:
194*b5893f02SDimitry Andric     case WebAssembly::REM_U_I64:
195*b5893f02SDimitry Andric     case WebAssembly::I32_TRUNC_S_F32:
196*b5893f02SDimitry Andric     case WebAssembly::I64_TRUNC_S_F32:
197*b5893f02SDimitry Andric     case WebAssembly::I32_TRUNC_S_F64:
198*b5893f02SDimitry Andric     case WebAssembly::I64_TRUNC_S_F64:
199*b5893f02SDimitry Andric     case WebAssembly::I32_TRUNC_U_F32:
200*b5893f02SDimitry Andric     case WebAssembly::I64_TRUNC_U_F32:
201*b5893f02SDimitry Andric     case WebAssembly::I32_TRUNC_U_F64:
202*b5893f02SDimitry Andric     case WebAssembly::I64_TRUNC_U_F64:
2033ca95b02SDimitry Andric       // These instruction have hasUnmodeledSideEffects() returning true
2043ca95b02SDimitry Andric       // because they trap on overflow and invalid so they can't be arbitrarily
2053ca95b02SDimitry Andric       // moved, however hasOrderedMemoryRef() interprets this plus their lack
2063ca95b02SDimitry Andric       // of memoperands as having a potential unknown memory reference.
2073ca95b02SDimitry Andric       break;
2083ca95b02SDimitry Andric     default:
2093ca95b02SDimitry Andric       // Record volatile accesses, unless it's a call, as calls are handled
2103ca95b02SDimitry Andric       // specially below.
2113ca95b02SDimitry Andric       if (!MI.isCall()) {
2123ca95b02SDimitry Andric         Write = true;
2133ca95b02SDimitry Andric         Effects = true;
2143ca95b02SDimitry Andric       }
2153ca95b02SDimitry Andric       break;
2163ca95b02SDimitry Andric     }
2173ca95b02SDimitry Andric   }
2183ca95b02SDimitry Andric 
2193ca95b02SDimitry Andric   // Check for side effects.
2203ca95b02SDimitry Andric   if (MI.hasUnmodeledSideEffects()) {
2213ca95b02SDimitry Andric     switch (MI.getOpcode()) {
222*b5893f02SDimitry Andric     case WebAssembly::DIV_S_I32:
223*b5893f02SDimitry Andric     case WebAssembly::DIV_S_I64:
224*b5893f02SDimitry Andric     case WebAssembly::REM_S_I32:
225*b5893f02SDimitry Andric     case WebAssembly::REM_S_I64:
226*b5893f02SDimitry Andric     case WebAssembly::DIV_U_I32:
227*b5893f02SDimitry Andric     case WebAssembly::DIV_U_I64:
228*b5893f02SDimitry Andric     case WebAssembly::REM_U_I32:
229*b5893f02SDimitry Andric     case WebAssembly::REM_U_I64:
230*b5893f02SDimitry Andric     case WebAssembly::I32_TRUNC_S_F32:
231*b5893f02SDimitry Andric     case WebAssembly::I64_TRUNC_S_F32:
232*b5893f02SDimitry Andric     case WebAssembly::I32_TRUNC_S_F64:
233*b5893f02SDimitry Andric     case WebAssembly::I64_TRUNC_S_F64:
234*b5893f02SDimitry Andric     case WebAssembly::I32_TRUNC_U_F32:
235*b5893f02SDimitry Andric     case WebAssembly::I64_TRUNC_U_F32:
236*b5893f02SDimitry Andric     case WebAssembly::I32_TRUNC_U_F64:
237*b5893f02SDimitry Andric     case WebAssembly::I64_TRUNC_U_F64:
2383ca95b02SDimitry Andric       // These instructions have hasUnmodeledSideEffects() returning true
2393ca95b02SDimitry Andric       // because they trap on overflow and invalid so they can't be arbitrarily
2403ca95b02SDimitry Andric       // moved, however in the specific case of register stackifying, it is safe
2413ca95b02SDimitry Andric       // to move them because overflow and invalid are Undefined Behavior.
2423ca95b02SDimitry Andric       break;
2433ca95b02SDimitry Andric     default:
2443ca95b02SDimitry Andric       Effects = true;
2453ca95b02SDimitry Andric       break;
2463ca95b02SDimitry Andric     }
2473ca95b02SDimitry Andric   }
2483ca95b02SDimitry Andric 
249*b5893f02SDimitry Andric   // Check for writes to __stack_pointer global.
250*b5893f02SDimitry Andric   if (MI.getOpcode() == WebAssembly::GLOBAL_SET_I32 &&
251*b5893f02SDimitry Andric       strcmp(MI.getOperand(0).getSymbolName(), "__stack_pointer") == 0)
252*b5893f02SDimitry Andric     StackPointer = true;
253*b5893f02SDimitry Andric 
2543ca95b02SDimitry Andric   // Analyze calls.
2553ca95b02SDimitry Andric   if (MI.isCall()) {
256*b5893f02SDimitry Andric     unsigned CalleeOpNo = WebAssembly::getCalleeOpNo(MI);
257*b5893f02SDimitry Andric     QueryCallee(MI, CalleeOpNo, Read, Write, Effects, StackPointer);
2583ca95b02SDimitry Andric   }
2593ca95b02SDimitry Andric }
2603ca95b02SDimitry Andric 
2613ca95b02SDimitry Andric // Test whether Def is safe and profitable to rematerialize.
ShouldRematerialize(const MachineInstr & Def,AliasAnalysis & AA,const WebAssemblyInstrInfo * TII)2623ca95b02SDimitry Andric static bool ShouldRematerialize(const MachineInstr &Def, AliasAnalysis &AA,
2633ca95b02SDimitry Andric                                 const WebAssemblyInstrInfo *TII) {
2643ca95b02SDimitry Andric   return Def.isAsCheapAsAMove() && TII->isTriviallyReMaterializable(Def, &AA);
2653ca95b02SDimitry Andric }
2663ca95b02SDimitry Andric 
2673ca95b02SDimitry Andric // Identify the definition for this register at this point. This is a
2683ca95b02SDimitry Andric // generalization of MachineRegisterInfo::getUniqueVRegDef that uses
2693ca95b02SDimitry Andric // LiveIntervals to handle complex cases.
GetVRegDef(unsigned Reg,const MachineInstr * Insert,const MachineRegisterInfo & MRI,const LiveIntervals & LIS)2703ca95b02SDimitry Andric static MachineInstr *GetVRegDef(unsigned Reg, const MachineInstr *Insert,
2713ca95b02SDimitry Andric                                 const MachineRegisterInfo &MRI,
272*b5893f02SDimitry Andric                                 const LiveIntervals &LIS) {
2733ca95b02SDimitry Andric   // Most registers are in SSA form here so we try a quick MRI query first.
2743ca95b02SDimitry Andric   if (MachineInstr *Def = MRI.getUniqueVRegDef(Reg))
2753ca95b02SDimitry Andric     return Def;
2763ca95b02SDimitry Andric 
2773ca95b02SDimitry Andric   // MRI doesn't know what the Def is. Try asking LIS.
2783ca95b02SDimitry Andric   if (const VNInfo *ValNo = LIS.getInterval(Reg).getVNInfoBefore(
2793ca95b02SDimitry Andric           LIS.getInstructionIndex(*Insert)))
2803ca95b02SDimitry Andric     return LIS.getInstructionFromIndex(ValNo->def);
2813ca95b02SDimitry Andric 
2823ca95b02SDimitry Andric   return nullptr;
2833ca95b02SDimitry Andric }
2843ca95b02SDimitry Andric 
2853ca95b02SDimitry Andric // Test whether Reg, as defined at Def, has exactly one use. This is a
2863ca95b02SDimitry Andric // generalization of MachineRegisterInfo::hasOneUse that uses LiveIntervals
2873ca95b02SDimitry Andric // to handle complex cases.
HasOneUse(unsigned Reg,MachineInstr * Def,MachineRegisterInfo & MRI,MachineDominatorTree & MDT,LiveIntervals & LIS)288*b5893f02SDimitry Andric static bool HasOneUse(unsigned Reg, MachineInstr *Def, MachineRegisterInfo &MRI,
289*b5893f02SDimitry Andric                       MachineDominatorTree &MDT, LiveIntervals &LIS) {
2903ca95b02SDimitry Andric   // Most registers are in SSA form here so we try a quick MRI query first.
2913ca95b02SDimitry Andric   if (MRI.hasOneUse(Reg))
2923ca95b02SDimitry Andric     return true;
2933ca95b02SDimitry Andric 
2943ca95b02SDimitry Andric   bool HasOne = false;
2953ca95b02SDimitry Andric   const LiveInterval &LI = LIS.getInterval(Reg);
296*b5893f02SDimitry Andric   const VNInfo *DefVNI =
297*b5893f02SDimitry Andric       LI.getVNInfoAt(LIS.getInstructionIndex(*Def).getRegSlot());
2983ca95b02SDimitry Andric   assert(DefVNI);
299d88c1a5aSDimitry Andric   for (auto &I : MRI.use_nodbg_operands(Reg)) {
3003ca95b02SDimitry Andric     const auto &Result = LI.Query(LIS.getInstructionIndex(*I.getParent()));
3013ca95b02SDimitry Andric     if (Result.valueIn() == DefVNI) {
3023ca95b02SDimitry Andric       if (!Result.isKill())
3033ca95b02SDimitry Andric         return false;
3043ca95b02SDimitry Andric       if (HasOne)
3053ca95b02SDimitry Andric         return false;
3063ca95b02SDimitry Andric       HasOne = true;
3073ca95b02SDimitry Andric     }
3083ca95b02SDimitry Andric   }
3093ca95b02SDimitry Andric   return HasOne;
3103ca95b02SDimitry Andric }
3113ca95b02SDimitry Andric 
3127d523365SDimitry Andric // Test whether it's safe to move Def to just before Insert.
3137d523365SDimitry Andric // TODO: Compute memory dependencies in a way that doesn't require always
3147d523365SDimitry Andric // walking the block.
3157d523365SDimitry Andric // TODO: Compute memory dependencies in a way that uses AliasAnalysis to be
3167d523365SDimitry Andric // more precise.
IsSafeToMove(const MachineInstr * Def,const MachineInstr * Insert,AliasAnalysis & AA,const MachineRegisterInfo & MRI)3177d523365SDimitry Andric static bool IsSafeToMove(const MachineInstr *Def, const MachineInstr *Insert,
318d88c1a5aSDimitry Andric                          AliasAnalysis &AA, const MachineRegisterInfo &MRI) {
3197d523365SDimitry Andric   assert(Def->getParent() == Insert->getParent());
3207d523365SDimitry Andric 
3217d523365SDimitry Andric   // Check for register dependencies.
322d88c1a5aSDimitry Andric   SmallVector<unsigned, 4> MutableRegisters;
3237d523365SDimitry Andric   for (const MachineOperand &MO : Def->operands()) {
3247d523365SDimitry Andric     if (!MO.isReg() || MO.isUndef())
3257d523365SDimitry Andric       continue;
3267d523365SDimitry Andric     unsigned Reg = MO.getReg();
3277d523365SDimitry Andric 
3287d523365SDimitry Andric     // If the register is dead here and at Insert, ignore it.
3297d523365SDimitry Andric     if (MO.isDead() && Insert->definesRegister(Reg) &&
3307d523365SDimitry Andric         !Insert->readsRegister(Reg))
3317d523365SDimitry Andric       continue;
3327d523365SDimitry Andric 
3337d523365SDimitry Andric     if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
3343ca95b02SDimitry Andric       // Ignore ARGUMENTS; it's just used to keep the ARGUMENT_* instructions
3353ca95b02SDimitry Andric       // from moving down, and we've already checked for that.
3363ca95b02SDimitry Andric       if (Reg == WebAssembly::ARGUMENTS)
3373ca95b02SDimitry Andric         continue;
3387d523365SDimitry Andric       // If the physical register is never modified, ignore it.
3397d523365SDimitry Andric       if (!MRI.isPhysRegModified(Reg))
3407d523365SDimitry Andric         continue;
3417d523365SDimitry Andric       // Otherwise, it's a physical register with unknown liveness.
3427d523365SDimitry Andric       return false;
3437d523365SDimitry Andric     }
3447d523365SDimitry Andric 
345d88c1a5aSDimitry Andric     // If one of the operands isn't in SSA form, it has different values at
346d88c1a5aSDimitry Andric     // different times, and we need to make sure we don't move our use across
347d88c1a5aSDimitry Andric     // a different def.
348d88c1a5aSDimitry Andric     if (!MO.isDef() && !MRI.hasOneDef(Reg))
349d88c1a5aSDimitry Andric       MutableRegisters.push_back(Reg);
3507d523365SDimitry Andric   }
3517d523365SDimitry Andric 
3523ca95b02SDimitry Andric   bool Read = false, Write = false, Effects = false, StackPointer = false;
3533ca95b02SDimitry Andric   Query(*Def, AA, Read, Write, Effects, StackPointer);
3543ca95b02SDimitry Andric 
3553ca95b02SDimitry Andric   // If the instruction does not access memory and has no side effects, it has
3563ca95b02SDimitry Andric   // no additional dependencies.
357d88c1a5aSDimitry Andric   bool HasMutableRegisters = !MutableRegisters.empty();
358d88c1a5aSDimitry Andric   if (!Read && !Write && !Effects && !StackPointer && !HasMutableRegisters)
3593ca95b02SDimitry Andric     return true;
3603ca95b02SDimitry Andric 
3613ca95b02SDimitry Andric   // Scan through the intervening instructions between Def and Insert.
3623ca95b02SDimitry Andric   MachineBasicBlock::const_iterator D(Def), I(Insert);
3633ca95b02SDimitry Andric   for (--I; I != D; --I) {
3643ca95b02SDimitry Andric     bool InterveningRead = false;
3653ca95b02SDimitry Andric     bool InterveningWrite = false;
3663ca95b02SDimitry Andric     bool InterveningEffects = false;
3673ca95b02SDimitry Andric     bool InterveningStackPointer = false;
3683ca95b02SDimitry Andric     Query(*I, AA, InterveningRead, InterveningWrite, InterveningEffects,
3693ca95b02SDimitry Andric           InterveningStackPointer);
3703ca95b02SDimitry Andric     if (Effects && InterveningEffects)
3713ca95b02SDimitry Andric       return false;
3723ca95b02SDimitry Andric     if (Read && InterveningWrite)
3733ca95b02SDimitry Andric       return false;
3743ca95b02SDimitry Andric     if (Write && (InterveningRead || InterveningWrite))
3753ca95b02SDimitry Andric       return false;
3763ca95b02SDimitry Andric     if (StackPointer && InterveningStackPointer)
3773ca95b02SDimitry Andric       return false;
378d88c1a5aSDimitry Andric 
379d88c1a5aSDimitry Andric     for (unsigned Reg : MutableRegisters)
380d88c1a5aSDimitry Andric       for (const MachineOperand &MO : I->operands())
381d88c1a5aSDimitry Andric         if (MO.isReg() && MO.isDef() && MO.getReg() == Reg)
382d88c1a5aSDimitry Andric           return false;
3837d523365SDimitry Andric   }
3847d523365SDimitry Andric 
3853ca95b02SDimitry Andric   return true;
3863ca95b02SDimitry Andric }
3873ca95b02SDimitry Andric 
3883ca95b02SDimitry Andric /// Test whether OneUse, a use of Reg, dominates all of Reg's other uses.
OneUseDominatesOtherUses(unsigned Reg,const MachineOperand & OneUse,const MachineBasicBlock & MBB,const MachineRegisterInfo & MRI,const MachineDominatorTree & MDT,LiveIntervals & LIS,WebAssemblyFunctionInfo & MFI)3893ca95b02SDimitry Andric static bool OneUseDominatesOtherUses(unsigned Reg, const MachineOperand &OneUse,
3903ca95b02SDimitry Andric                                      const MachineBasicBlock &MBB,
3913ca95b02SDimitry Andric                                      const MachineRegisterInfo &MRI,
3923ca95b02SDimitry Andric                                      const MachineDominatorTree &MDT,
3933ca95b02SDimitry Andric                                      LiveIntervals &LIS,
3943ca95b02SDimitry Andric                                      WebAssemblyFunctionInfo &MFI) {
3953ca95b02SDimitry Andric   const LiveInterval &LI = LIS.getInterval(Reg);
3963ca95b02SDimitry Andric 
3973ca95b02SDimitry Andric   const MachineInstr *OneUseInst = OneUse.getParent();
3983ca95b02SDimitry Andric   VNInfo *OneUseVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*OneUseInst));
3993ca95b02SDimitry Andric 
400d88c1a5aSDimitry Andric   for (const MachineOperand &Use : MRI.use_nodbg_operands(Reg)) {
4013ca95b02SDimitry Andric     if (&Use == &OneUse)
4023ca95b02SDimitry Andric       continue;
4033ca95b02SDimitry Andric 
4043ca95b02SDimitry Andric     const MachineInstr *UseInst = Use.getParent();
4053ca95b02SDimitry Andric     VNInfo *UseVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*UseInst));
4063ca95b02SDimitry Andric 
4073ca95b02SDimitry Andric     if (UseVNI != OneUseVNI)
4083ca95b02SDimitry Andric       continue;
4093ca95b02SDimitry Andric 
4103ca95b02SDimitry Andric     if (UseInst == OneUseInst) {
4113ca95b02SDimitry Andric       // Another use in the same instruction. We need to ensure that the one
4123ca95b02SDimitry Andric       // selected use happens "before" it.
4133ca95b02SDimitry Andric       if (&OneUse > &Use)
4143ca95b02SDimitry Andric         return false;
4153ca95b02SDimitry Andric     } else {
4163ca95b02SDimitry Andric       // Test that the use is dominated by the one selected use.
4173ca95b02SDimitry Andric       while (!MDT.dominates(OneUseInst, UseInst)) {
4183ca95b02SDimitry Andric         // Actually, dominating is over-conservative. Test that the use would
4193ca95b02SDimitry Andric         // happen after the one selected use in the stack evaluation order.
4203ca95b02SDimitry Andric         //
421*b5893f02SDimitry Andric         // This is needed as a consequence of using implicit local.gets for
422*b5893f02SDimitry Andric         // uses and implicit local.sets for defs.
4233ca95b02SDimitry Andric         if (UseInst->getDesc().getNumDefs() == 0)
4243ca95b02SDimitry Andric           return false;
4253ca95b02SDimitry Andric         const MachineOperand &MO = UseInst->getOperand(0);
4263ca95b02SDimitry Andric         if (!MO.isReg())
4273ca95b02SDimitry Andric           return false;
4283ca95b02SDimitry Andric         unsigned DefReg = MO.getReg();
4293ca95b02SDimitry Andric         if (!TargetRegisterInfo::isVirtualRegister(DefReg) ||
4303ca95b02SDimitry Andric             !MFI.isVRegStackified(DefReg))
4313ca95b02SDimitry Andric           return false;
432*b5893f02SDimitry Andric         assert(MRI.hasOneNonDBGUse(DefReg));
433*b5893f02SDimitry Andric         const MachineOperand &NewUse = *MRI.use_nodbg_begin(DefReg);
4343ca95b02SDimitry Andric         const MachineInstr *NewUseInst = NewUse.getParent();
4353ca95b02SDimitry Andric         if (NewUseInst == OneUseInst) {
4363ca95b02SDimitry Andric           if (&OneUse > &NewUse)
4373ca95b02SDimitry Andric             return false;
4383ca95b02SDimitry Andric           break;
4393ca95b02SDimitry Andric         }
4403ca95b02SDimitry Andric         UseInst = NewUseInst;
4413ca95b02SDimitry Andric       }
4423ca95b02SDimitry Andric     }
4433ca95b02SDimitry Andric   }
4443ca95b02SDimitry Andric   return true;
4453ca95b02SDimitry Andric }
4463ca95b02SDimitry Andric 
447d88c1a5aSDimitry Andric /// Get the appropriate tee opcode for the given register class.
GetTeeOpcode(const TargetRegisterClass * RC)448d88c1a5aSDimitry Andric static unsigned GetTeeOpcode(const TargetRegisterClass *RC) {
4493ca95b02SDimitry Andric   if (RC == &WebAssembly::I32RegClass)
450d88c1a5aSDimitry Andric     return WebAssembly::TEE_I32;
4513ca95b02SDimitry Andric   if (RC == &WebAssembly::I64RegClass)
452d88c1a5aSDimitry Andric     return WebAssembly::TEE_I64;
4533ca95b02SDimitry Andric   if (RC == &WebAssembly::F32RegClass)
454d88c1a5aSDimitry Andric     return WebAssembly::TEE_F32;
4553ca95b02SDimitry Andric   if (RC == &WebAssembly::F64RegClass)
456d88c1a5aSDimitry Andric     return WebAssembly::TEE_F64;
457d88c1a5aSDimitry Andric   if (RC == &WebAssembly::V128RegClass)
458d88c1a5aSDimitry Andric     return WebAssembly::TEE_V128;
4593ca95b02SDimitry Andric   llvm_unreachable("Unexpected register class");
4603ca95b02SDimitry Andric }
4613ca95b02SDimitry Andric 
4623ca95b02SDimitry Andric // Shrink LI to its uses, cleaning up LI.
ShrinkToUses(LiveInterval & LI,LiveIntervals & LIS)4633ca95b02SDimitry Andric static void ShrinkToUses(LiveInterval &LI, LiveIntervals &LIS) {
4643ca95b02SDimitry Andric   if (LIS.shrinkToUses(&LI)) {
4653ca95b02SDimitry Andric     SmallVector<LiveInterval *, 4> SplitLIs;
4663ca95b02SDimitry Andric     LIS.splitSeparateComponents(LI, SplitLIs);
4673ca95b02SDimitry Andric   }
4683ca95b02SDimitry Andric }
4693ca95b02SDimitry Andric 
4703ca95b02SDimitry Andric /// A single-use def in the same block with no intervening memory or register
4713ca95b02SDimitry Andric /// dependencies; move the def down and nest it with the current instruction.
MoveForSingleUse(unsigned Reg,MachineOperand & Op,MachineInstr * Def,MachineBasicBlock & MBB,MachineInstr * Insert,LiveIntervals & LIS,WebAssemblyFunctionInfo & MFI,MachineRegisterInfo & MRI)4723ca95b02SDimitry Andric static MachineInstr *MoveForSingleUse(unsigned Reg, MachineOperand &Op,
473*b5893f02SDimitry Andric                                       MachineInstr *Def, MachineBasicBlock &MBB,
4743ca95b02SDimitry Andric                                       MachineInstr *Insert, LiveIntervals &LIS,
4753ca95b02SDimitry Andric                                       WebAssemblyFunctionInfo &MFI,
4763ca95b02SDimitry Andric                                       MachineRegisterInfo &MRI) {
4774ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Move for single use: "; Def->dump());
4783ca95b02SDimitry Andric 
479*b5893f02SDimitry Andric   WebAssemblyDebugValueManager DefDIs(Def);
4803ca95b02SDimitry Andric   MBB.splice(Insert, &MBB, Def);
481*b5893f02SDimitry Andric   DefDIs.move(Insert);
4823ca95b02SDimitry Andric   LIS.handleMove(*Def);
4833ca95b02SDimitry Andric 
4843ca95b02SDimitry Andric   if (MRI.hasOneDef(Reg) && MRI.hasOneUse(Reg)) {
4853ca95b02SDimitry Andric     // No one else is using this register for anything so we can just stackify
4863ca95b02SDimitry Andric     // it in place.
4873ca95b02SDimitry Andric     MFI.stackifyVReg(Reg);
4883ca95b02SDimitry Andric   } else {
4893ca95b02SDimitry Andric     // The register may have unrelated uses or defs; create a new register for
4903ca95b02SDimitry Andric     // just our one def and use so that we can stackify it.
4913ca95b02SDimitry Andric     unsigned NewReg = MRI.createVirtualRegister(MRI.getRegClass(Reg));
4923ca95b02SDimitry Andric     Def->getOperand(0).setReg(NewReg);
4933ca95b02SDimitry Andric     Op.setReg(NewReg);
4943ca95b02SDimitry Andric 
4953ca95b02SDimitry Andric     // Tell LiveIntervals about the new register.
4963ca95b02SDimitry Andric     LIS.createAndComputeVirtRegInterval(NewReg);
4973ca95b02SDimitry Andric 
4983ca95b02SDimitry Andric     // Tell LiveIntervals about the changes to the old register.
4993ca95b02SDimitry Andric     LiveInterval &LI = LIS.getInterval(Reg);
5003ca95b02SDimitry Andric     LI.removeSegment(LIS.getInstructionIndex(*Def).getRegSlot(),
5013ca95b02SDimitry Andric                      LIS.getInstructionIndex(*Op.getParent()).getRegSlot(),
5023ca95b02SDimitry Andric                      /*RemoveDeadValNo=*/true);
5033ca95b02SDimitry Andric 
5043ca95b02SDimitry Andric     MFI.stackifyVReg(NewReg);
5053ca95b02SDimitry Andric 
506*b5893f02SDimitry Andric     DefDIs.updateReg(NewReg);
507*b5893f02SDimitry Andric 
5084ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << " - Replaced register: "; Def->dump());
5093ca95b02SDimitry Andric   }
5103ca95b02SDimitry Andric 
5113ca95b02SDimitry Andric   ImposeStackOrdering(Def);
5123ca95b02SDimitry Andric   return Def;
5133ca95b02SDimitry Andric }
5143ca95b02SDimitry Andric 
5153ca95b02SDimitry Andric /// A trivially cloneable instruction; clone it and nest the new copy with the
5163ca95b02SDimitry Andric /// current instruction.
RematerializeCheapDef(unsigned Reg,MachineOperand & Op,MachineInstr & Def,MachineBasicBlock & MBB,MachineBasicBlock::instr_iterator Insert,LiveIntervals & LIS,WebAssemblyFunctionInfo & MFI,MachineRegisterInfo & MRI,const WebAssemblyInstrInfo * TII,const WebAssemblyRegisterInfo * TRI)5173ca95b02SDimitry Andric static MachineInstr *RematerializeCheapDef(
5183ca95b02SDimitry Andric     unsigned Reg, MachineOperand &Op, MachineInstr &Def, MachineBasicBlock &MBB,
5193ca95b02SDimitry Andric     MachineBasicBlock::instr_iterator Insert, LiveIntervals &LIS,
5203ca95b02SDimitry Andric     WebAssemblyFunctionInfo &MFI, MachineRegisterInfo &MRI,
5213ca95b02SDimitry Andric     const WebAssemblyInstrInfo *TII, const WebAssemblyRegisterInfo *TRI) {
5224ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Rematerializing cheap def: "; Def.dump());
5234ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << " - for use in "; Op.getParent()->dump());
5243ca95b02SDimitry Andric 
525*b5893f02SDimitry Andric   WebAssemblyDebugValueManager DefDIs(&Def);
526*b5893f02SDimitry Andric 
5273ca95b02SDimitry Andric   unsigned NewReg = MRI.createVirtualRegister(MRI.getRegClass(Reg));
5283ca95b02SDimitry Andric   TII->reMaterialize(MBB, Insert, NewReg, 0, Def, *TRI);
5293ca95b02SDimitry Andric   Op.setReg(NewReg);
5303ca95b02SDimitry Andric   MachineInstr *Clone = &*std::prev(Insert);
5313ca95b02SDimitry Andric   LIS.InsertMachineInstrInMaps(*Clone);
5323ca95b02SDimitry Andric   LIS.createAndComputeVirtRegInterval(NewReg);
5333ca95b02SDimitry Andric   MFI.stackifyVReg(NewReg);
5343ca95b02SDimitry Andric   ImposeStackOrdering(Clone);
5353ca95b02SDimitry Andric 
5364ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << " - Cloned to "; Clone->dump());
5373ca95b02SDimitry Andric 
5383ca95b02SDimitry Andric   // Shrink the interval.
5393ca95b02SDimitry Andric   bool IsDead = MRI.use_empty(Reg);
5403ca95b02SDimitry Andric   if (!IsDead) {
5413ca95b02SDimitry Andric     LiveInterval &LI = LIS.getInterval(Reg);
5423ca95b02SDimitry Andric     ShrinkToUses(LI, LIS);
5433ca95b02SDimitry Andric     IsDead = !LI.liveAt(LIS.getInstructionIndex(Def).getDeadSlot());
5443ca95b02SDimitry Andric   }
5453ca95b02SDimitry Andric 
5463ca95b02SDimitry Andric   // If that was the last use of the original, delete the original.
547*b5893f02SDimitry Andric   // Move or clone corresponding DBG_VALUEs to the 'Insert' location.
5483ca95b02SDimitry Andric   if (IsDead) {
5494ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << " - Deleting original\n");
5503ca95b02SDimitry Andric     SlotIndex Idx = LIS.getInstructionIndex(Def).getRegSlot();
5513ca95b02SDimitry Andric     LIS.removePhysRegDefAt(WebAssembly::ARGUMENTS, Idx);
5523ca95b02SDimitry Andric     LIS.removeInterval(Reg);
5533ca95b02SDimitry Andric     LIS.RemoveMachineInstrFromMaps(Def);
5543ca95b02SDimitry Andric     Def.eraseFromParent();
555*b5893f02SDimitry Andric 
556*b5893f02SDimitry Andric     DefDIs.move(&*Insert);
557*b5893f02SDimitry Andric     DefDIs.updateReg(NewReg);
558*b5893f02SDimitry Andric   } else {
559*b5893f02SDimitry Andric     DefDIs.clone(&*Insert, NewReg);
5603ca95b02SDimitry Andric   }
5613ca95b02SDimitry Andric 
5623ca95b02SDimitry Andric   return Clone;
5633ca95b02SDimitry Andric }
5643ca95b02SDimitry Andric 
5653ca95b02SDimitry Andric /// A multiple-use def in the same block with no intervening memory or register
5663ca95b02SDimitry Andric /// dependencies; move the def down, nest it with the current instruction, and
567d88c1a5aSDimitry Andric /// insert a tee to satisfy the rest of the uses. As an illustration, rewrite
568d88c1a5aSDimitry Andric /// this:
5693ca95b02SDimitry Andric ///
5703ca95b02SDimitry Andric ///    Reg = INST ...        // Def
5713ca95b02SDimitry Andric ///    INST ..., Reg, ...    // Insert
5723ca95b02SDimitry Andric ///    INST ..., Reg, ...
5733ca95b02SDimitry Andric ///    INST ..., Reg, ...
5743ca95b02SDimitry Andric ///
5753ca95b02SDimitry Andric /// to this:
5763ca95b02SDimitry Andric ///
5773ca95b02SDimitry Andric ///    DefReg = INST ...     // Def (to become the new Insert)
578d88c1a5aSDimitry Andric ///    TeeReg, Reg = TEE_... DefReg
5793ca95b02SDimitry Andric ///    INST ..., TeeReg, ... // Insert
5803ca95b02SDimitry Andric ///    INST ..., Reg, ...
5813ca95b02SDimitry Andric ///    INST ..., Reg, ...
5823ca95b02SDimitry Andric ///
583*b5893f02SDimitry Andric /// with DefReg and TeeReg stackified. This eliminates a local.get from the
5843ca95b02SDimitry Andric /// resulting code.
MoveAndTeeForMultiUse(unsigned Reg,MachineOperand & Op,MachineInstr * Def,MachineBasicBlock & MBB,MachineInstr * Insert,LiveIntervals & LIS,WebAssemblyFunctionInfo & MFI,MachineRegisterInfo & MRI,const WebAssemblyInstrInfo * TII)5853ca95b02SDimitry Andric static MachineInstr *MoveAndTeeForMultiUse(
5863ca95b02SDimitry Andric     unsigned Reg, MachineOperand &Op, MachineInstr *Def, MachineBasicBlock &MBB,
5873ca95b02SDimitry Andric     MachineInstr *Insert, LiveIntervals &LIS, WebAssemblyFunctionInfo &MFI,
5883ca95b02SDimitry Andric     MachineRegisterInfo &MRI, const WebAssemblyInstrInfo *TII) {
5894ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Move and tee for multi-use:"; Def->dump());
5903ca95b02SDimitry Andric 
591*b5893f02SDimitry Andric   WebAssemblyDebugValueManager DefDIs(Def);
592*b5893f02SDimitry Andric 
5933ca95b02SDimitry Andric   // Move Def into place.
5943ca95b02SDimitry Andric   MBB.splice(Insert, &MBB, Def);
5953ca95b02SDimitry Andric   LIS.handleMove(*Def);
5963ca95b02SDimitry Andric 
5973ca95b02SDimitry Andric   // Create the Tee and attach the registers.
5983ca95b02SDimitry Andric   const auto *RegClass = MRI.getRegClass(Reg);
5993ca95b02SDimitry Andric   unsigned TeeReg = MRI.createVirtualRegister(RegClass);
6003ca95b02SDimitry Andric   unsigned DefReg = MRI.createVirtualRegister(RegClass);
6013ca95b02SDimitry Andric   MachineOperand &DefMO = Def->getOperand(0);
6023ca95b02SDimitry Andric   MachineInstr *Tee = BuildMI(MBB, Insert, Insert->getDebugLoc(),
603d88c1a5aSDimitry Andric                               TII->get(GetTeeOpcode(RegClass)), TeeReg)
6043ca95b02SDimitry Andric                           .addReg(Reg, RegState::Define)
6053ca95b02SDimitry Andric                           .addReg(DefReg, getUndefRegState(DefMO.isDead()));
6063ca95b02SDimitry Andric   Op.setReg(TeeReg);
6073ca95b02SDimitry Andric   DefMO.setReg(DefReg);
6083ca95b02SDimitry Andric   SlotIndex TeeIdx = LIS.InsertMachineInstrInMaps(*Tee).getRegSlot();
6093ca95b02SDimitry Andric   SlotIndex DefIdx = LIS.getInstructionIndex(*Def).getRegSlot();
6103ca95b02SDimitry Andric 
611*b5893f02SDimitry Andric   DefDIs.move(Insert);
612*b5893f02SDimitry Andric 
6133ca95b02SDimitry Andric   // Tell LiveIntervals we moved the original vreg def from Def to Tee.
6143ca95b02SDimitry Andric   LiveInterval &LI = LIS.getInterval(Reg);
6153ca95b02SDimitry Andric   LiveInterval::iterator I = LI.FindSegmentContaining(DefIdx);
6163ca95b02SDimitry Andric   VNInfo *ValNo = LI.getVNInfoAt(DefIdx);
6173ca95b02SDimitry Andric   I->start = TeeIdx;
6183ca95b02SDimitry Andric   ValNo->def = TeeIdx;
6193ca95b02SDimitry Andric   ShrinkToUses(LI, LIS);
6203ca95b02SDimitry Andric 
6213ca95b02SDimitry Andric   // Finish stackifying the new regs.
6223ca95b02SDimitry Andric   LIS.createAndComputeVirtRegInterval(TeeReg);
6233ca95b02SDimitry Andric   LIS.createAndComputeVirtRegInterval(DefReg);
6243ca95b02SDimitry Andric   MFI.stackifyVReg(DefReg);
6253ca95b02SDimitry Andric   MFI.stackifyVReg(TeeReg);
6263ca95b02SDimitry Andric   ImposeStackOrdering(Def);
6273ca95b02SDimitry Andric   ImposeStackOrdering(Tee);
6283ca95b02SDimitry Andric 
629*b5893f02SDimitry Andric   DefDIs.clone(Tee, DefReg);
630*b5893f02SDimitry Andric   DefDIs.clone(Insert, TeeReg);
631*b5893f02SDimitry Andric 
6324ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << " - Replaced register: "; Def->dump());
6334ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << " - Tee instruction: "; Tee->dump());
6343ca95b02SDimitry Andric   return Def;
6353ca95b02SDimitry Andric }
6363ca95b02SDimitry Andric 
6373ca95b02SDimitry Andric namespace {
6383ca95b02SDimitry Andric /// A stack for walking the tree of instructions being built, visiting the
6393ca95b02SDimitry Andric /// MachineOperands in DFS order.
6403ca95b02SDimitry Andric class TreeWalkerState {
6413ca95b02SDimitry Andric   typedef MachineInstr::mop_iterator mop_iterator;
6423ca95b02SDimitry Andric   typedef std::reverse_iterator<mop_iterator> mop_reverse_iterator;
6433ca95b02SDimitry Andric   typedef iterator_range<mop_reverse_iterator> RangeTy;
6443ca95b02SDimitry Andric   SmallVector<RangeTy, 4> Worklist;
6453ca95b02SDimitry Andric 
6463ca95b02SDimitry Andric public:
TreeWalkerState(MachineInstr * Insert)6473ca95b02SDimitry Andric   explicit TreeWalkerState(MachineInstr *Insert) {
6483ca95b02SDimitry Andric     const iterator_range<mop_iterator> &Range = Insert->explicit_uses();
6493ca95b02SDimitry Andric     if (Range.begin() != Range.end())
6503ca95b02SDimitry Andric       Worklist.push_back(reverse(Range));
6513ca95b02SDimitry Andric   }
6523ca95b02SDimitry Andric 
Done() const6533ca95b02SDimitry Andric   bool Done() const { return Worklist.empty(); }
6543ca95b02SDimitry Andric 
Pop()6553ca95b02SDimitry Andric   MachineOperand &Pop() {
6563ca95b02SDimitry Andric     RangeTy &Range = Worklist.back();
6573ca95b02SDimitry Andric     MachineOperand &Op = *Range.begin();
6583ca95b02SDimitry Andric     Range = drop_begin(Range, 1);
6593ca95b02SDimitry Andric     if (Range.begin() == Range.end())
6603ca95b02SDimitry Andric       Worklist.pop_back();
6613ca95b02SDimitry Andric     assert((Worklist.empty() ||
6623ca95b02SDimitry Andric             Worklist.back().begin() != Worklist.back().end()) &&
6633ca95b02SDimitry Andric            "Empty ranges shouldn't remain in the worklist");
6643ca95b02SDimitry Andric     return Op;
6653ca95b02SDimitry Andric   }
6663ca95b02SDimitry Andric 
6673ca95b02SDimitry Andric   /// Push Instr's operands onto the stack to be visited.
PushOperands(MachineInstr * Instr)6683ca95b02SDimitry Andric   void PushOperands(MachineInstr *Instr) {
6693ca95b02SDimitry Andric     const iterator_range<mop_iterator> &Range(Instr->explicit_uses());
6703ca95b02SDimitry Andric     if (Range.begin() != Range.end())
6713ca95b02SDimitry Andric       Worklist.push_back(reverse(Range));
6723ca95b02SDimitry Andric   }
6733ca95b02SDimitry Andric 
6743ca95b02SDimitry Andric   /// Some of Instr's operands are on the top of the stack; remove them and
6753ca95b02SDimitry Andric   /// re-insert them starting from the beginning (because we've commuted them).
ResetTopOperands(MachineInstr * Instr)6763ca95b02SDimitry Andric   void ResetTopOperands(MachineInstr *Instr) {
6773ca95b02SDimitry Andric     assert(HasRemainingOperands(Instr) &&
6783ca95b02SDimitry Andric            "Reseting operands should only be done when the instruction has "
6793ca95b02SDimitry Andric            "an operand still on the stack");
6803ca95b02SDimitry Andric     Worklist.back() = reverse(Instr->explicit_uses());
6813ca95b02SDimitry Andric   }
6823ca95b02SDimitry Andric 
6833ca95b02SDimitry Andric   /// Test whether Instr has operands remaining to be visited at the top of
6843ca95b02SDimitry Andric   /// the stack.
HasRemainingOperands(const MachineInstr * Instr) const6853ca95b02SDimitry Andric   bool HasRemainingOperands(const MachineInstr *Instr) const {
6863ca95b02SDimitry Andric     if (Worklist.empty())
6873ca95b02SDimitry Andric       return false;
6883ca95b02SDimitry Andric     const RangeTy &Range = Worklist.back();
6893ca95b02SDimitry Andric     return Range.begin() != Range.end() && Range.begin()->getParent() == Instr;
6903ca95b02SDimitry Andric   }
6913ca95b02SDimitry Andric 
6923ca95b02SDimitry Andric   /// Test whether the given register is present on the stack, indicating an
6933ca95b02SDimitry Andric   /// operand in the tree that we haven't visited yet. Moving a definition of
6943ca95b02SDimitry Andric   /// Reg to a point in the tree after that would change its value.
6953ca95b02SDimitry Andric   ///
696*b5893f02SDimitry Andric   /// This is needed as a consequence of using implicit local.gets for
697*b5893f02SDimitry Andric   /// uses and implicit local.sets for defs.
IsOnStack(unsigned Reg) const6983ca95b02SDimitry Andric   bool IsOnStack(unsigned Reg) const {
6993ca95b02SDimitry Andric     for (const RangeTy &Range : Worklist)
7003ca95b02SDimitry Andric       for (const MachineOperand &MO : Range)
7013ca95b02SDimitry Andric         if (MO.isReg() && MO.getReg() == Reg)
7023ca95b02SDimitry Andric           return true;
7033ca95b02SDimitry Andric     return false;
7043ca95b02SDimitry Andric   }
7053ca95b02SDimitry Andric };
7063ca95b02SDimitry Andric 
7073ca95b02SDimitry Andric /// State to keep track of whether commuting is in flight or whether it's been
7083ca95b02SDimitry Andric /// tried for the current instruction and didn't work.
7093ca95b02SDimitry Andric class CommutingState {
7103ca95b02SDimitry Andric   /// There are effectively three states: the initial state where we haven't
711*b5893f02SDimitry Andric   /// started commuting anything and we don't know anything yet, the tentative
7123ca95b02SDimitry Andric   /// state where we've commuted the operands of the current instruction and are
713*b5893f02SDimitry Andric   /// revisiting it, and the declined state where we've reverted the operands
7143ca95b02SDimitry Andric   /// back to their original order and will no longer commute it further.
7153ca95b02SDimitry Andric   bool TentativelyCommuting;
7163ca95b02SDimitry Andric   bool Declined;
7173ca95b02SDimitry Andric 
7183ca95b02SDimitry Andric   /// During the tentative state, these hold the operand indices of the commuted
7193ca95b02SDimitry Andric   /// operands.
7203ca95b02SDimitry Andric   unsigned Operand0, Operand1;
7213ca95b02SDimitry Andric 
7223ca95b02SDimitry Andric public:
CommutingState()7233ca95b02SDimitry Andric   CommutingState() : TentativelyCommuting(false), Declined(false) {}
7243ca95b02SDimitry Andric 
7253ca95b02SDimitry Andric   /// Stackification for an operand was not successful due to ordering
7263ca95b02SDimitry Andric   /// constraints. If possible, and if we haven't already tried it and declined
7273ca95b02SDimitry Andric   /// it, commute Insert's operands and prepare to revisit it.
MaybeCommute(MachineInstr * Insert,TreeWalkerState & TreeWalker,const WebAssemblyInstrInfo * TII)7283ca95b02SDimitry Andric   void MaybeCommute(MachineInstr *Insert, TreeWalkerState &TreeWalker,
7293ca95b02SDimitry Andric                     const WebAssemblyInstrInfo *TII) {
7303ca95b02SDimitry Andric     if (TentativelyCommuting) {
7313ca95b02SDimitry Andric       assert(!Declined &&
7323ca95b02SDimitry Andric              "Don't decline commuting until you've finished trying it");
7333ca95b02SDimitry Andric       // Commuting didn't help. Revert it.
7343ca95b02SDimitry Andric       TII->commuteInstruction(*Insert, /*NewMI=*/false, Operand0, Operand1);
7353ca95b02SDimitry Andric       TentativelyCommuting = false;
7363ca95b02SDimitry Andric       Declined = true;
7373ca95b02SDimitry Andric     } else if (!Declined && TreeWalker.HasRemainingOperands(Insert)) {
7383ca95b02SDimitry Andric       Operand0 = TargetInstrInfo::CommuteAnyOperandIndex;
7393ca95b02SDimitry Andric       Operand1 = TargetInstrInfo::CommuteAnyOperandIndex;
7403ca95b02SDimitry Andric       if (TII->findCommutedOpIndices(*Insert, Operand0, Operand1)) {
7413ca95b02SDimitry Andric         // Tentatively commute the operands and try again.
7423ca95b02SDimitry Andric         TII->commuteInstruction(*Insert, /*NewMI=*/false, Operand0, Operand1);
7433ca95b02SDimitry Andric         TreeWalker.ResetTopOperands(Insert);
7443ca95b02SDimitry Andric         TentativelyCommuting = true;
7453ca95b02SDimitry Andric         Declined = false;
7463ca95b02SDimitry Andric       }
7473ca95b02SDimitry Andric     }
7483ca95b02SDimitry Andric   }
7493ca95b02SDimitry Andric 
7503ca95b02SDimitry Andric   /// Stackification for some operand was successful. Reset to the default
7513ca95b02SDimitry Andric   /// state.
Reset()7523ca95b02SDimitry Andric   void Reset() {
7533ca95b02SDimitry Andric     TentativelyCommuting = false;
7543ca95b02SDimitry Andric     Declined = false;
7553ca95b02SDimitry Andric   }
7563ca95b02SDimitry Andric };
7573ca95b02SDimitry Andric } // end anonymous namespace
7583ca95b02SDimitry Andric 
runOnMachineFunction(MachineFunction & MF)7597d523365SDimitry Andric bool WebAssemblyRegStackify::runOnMachineFunction(MachineFunction &MF) {
7604ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "********** Register Stackifying **********\n"
7617d523365SDimitry Andric                        "********** Function: "
7627d523365SDimitry Andric                     << MF.getName() << '\n');
7637d523365SDimitry Andric 
7647d523365SDimitry Andric   bool Changed = false;
7657d523365SDimitry Andric   MachineRegisterInfo &MRI = MF.getRegInfo();
7667d523365SDimitry Andric   WebAssemblyFunctionInfo &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
7673ca95b02SDimitry Andric   const auto *TII = MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
7683ca95b02SDimitry Andric   const auto *TRI = MF.getSubtarget<WebAssemblySubtarget>().getRegisterInfo();
7697d523365SDimitry Andric   AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
7703ca95b02SDimitry Andric   MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
7717d523365SDimitry Andric   LiveIntervals &LIS = getAnalysis<LiveIntervals>();
7727d523365SDimitry Andric 
7737d523365SDimitry Andric   // Walk the instructions from the bottom up. Currently we don't look past
7747d523365SDimitry Andric   // block boundaries, and the blocks aren't ordered so the block visitation
7757d523365SDimitry Andric   // order isn't significant, but we may want to change this in the future.
7767d523365SDimitry Andric   for (MachineBasicBlock &MBB : MF) {
777444ed5c5SDimitry Andric     // Don't use a range-based for loop, because we modify the list as we're
778444ed5c5SDimitry Andric     // iterating over it and the end iterator may change.
779444ed5c5SDimitry Andric     for (auto MII = MBB.rbegin(); MII != MBB.rend(); ++MII) {
780444ed5c5SDimitry Andric       MachineInstr *Insert = &*MII;
7817d523365SDimitry Andric       // Don't nest anything inside an inline asm, because we don't have
7827d523365SDimitry Andric       // constraints for $push inputs.
7837d523365SDimitry Andric       if (Insert->getOpcode() == TargetOpcode::INLINEASM)
7843ca95b02SDimitry Andric         continue;
7853ca95b02SDimitry Andric 
7863ca95b02SDimitry Andric       // Ignore debugging intrinsics.
7873ca95b02SDimitry Andric       if (Insert->getOpcode() == TargetOpcode::DBG_VALUE)
7883ca95b02SDimitry Andric         continue;
7897d523365SDimitry Andric 
7907d523365SDimitry Andric       // Iterate through the inputs in reverse order, since we'll be pulling
7917d523365SDimitry Andric       // operands off the stack in LIFO order.
7923ca95b02SDimitry Andric       CommutingState Commuting;
7933ca95b02SDimitry Andric       TreeWalkerState TreeWalker(Insert);
7943ca95b02SDimitry Andric       while (!TreeWalker.Done()) {
7953ca95b02SDimitry Andric         MachineOperand &Op = TreeWalker.Pop();
7963ca95b02SDimitry Andric 
7977d523365SDimitry Andric         // We're only interested in explicit virtual register operands.
7983ca95b02SDimitry Andric         if (!Op.isReg())
7997d523365SDimitry Andric           continue;
8007d523365SDimitry Andric 
8017d523365SDimitry Andric         unsigned Reg = Op.getReg();
8023ca95b02SDimitry Andric         assert(Op.isUse() && "explicit_uses() should only iterate over uses");
8033ca95b02SDimitry Andric         assert(!Op.isImplicit() &&
8043ca95b02SDimitry Andric                "explicit_uses() should only iterate over explicit operands");
8053ca95b02SDimitry Andric         if (TargetRegisterInfo::isPhysicalRegister(Reg))
8067d523365SDimitry Andric           continue;
8077d523365SDimitry Andric 
808d88c1a5aSDimitry Andric         // Identify the definition for this register at this point.
8093ca95b02SDimitry Andric         MachineInstr *Def = GetVRegDef(Reg, Insert, MRI, LIS);
8103ca95b02SDimitry Andric         if (!Def)
8117d523365SDimitry Andric           continue;
8127d523365SDimitry Andric 
8137d523365SDimitry Andric         // Don't nest an INLINE_ASM def into anything, because we don't have
8147d523365SDimitry Andric         // constraints for $pop outputs.
8157d523365SDimitry Andric         if (Def->getOpcode() == TargetOpcode::INLINEASM)
8167d523365SDimitry Andric           continue;
8177d523365SDimitry Andric 
8187d523365SDimitry Andric         // Argument instructions represent live-in registers and not real
8197d523365SDimitry Andric         // instructions.
820d88c1a5aSDimitry Andric         if (WebAssembly::isArgument(*Def))
8217d523365SDimitry Andric           continue;
8227d523365SDimitry Andric 
8233ca95b02SDimitry Andric         // Decide which strategy to take. Prefer to move a single-use value
824d88c1a5aSDimitry Andric         // over cloning it, and prefer cloning over introducing a tee.
8253ca95b02SDimitry Andric         // For moving, we require the def to be in the same block as the use;
8263ca95b02SDimitry Andric         // this makes things simpler (LiveIntervals' handleMove function only
8273ca95b02SDimitry Andric         // supports intra-block moves) and it's MachineSink's job to catch all
8283ca95b02SDimitry Andric         // the sinking opportunities anyway.
8293ca95b02SDimitry Andric         bool SameBlock = Def->getParent() == &MBB;
830d88c1a5aSDimitry Andric         bool CanMove = SameBlock && IsSafeToMove(Def, Insert, AA, MRI) &&
8313ca95b02SDimitry Andric                        !TreeWalker.IsOnStack(Reg);
8323ca95b02SDimitry Andric         if (CanMove && HasOneUse(Reg, Def, MRI, MDT, LIS)) {
8333ca95b02SDimitry Andric           Insert = MoveForSingleUse(Reg, Op, Def, MBB, Insert, LIS, MFI, MRI);
8343ca95b02SDimitry Andric         } else if (ShouldRematerialize(*Def, AA, TII)) {
8353ca95b02SDimitry Andric           Insert =
8363ca95b02SDimitry Andric               RematerializeCheapDef(Reg, Op, *Def, MBB, Insert->getIterator(),
8373ca95b02SDimitry Andric                                     LIS, MFI, MRI, TII, TRI);
8384ba319b5SDimitry Andric         } else if (CanMove &&
8393ca95b02SDimitry Andric                    OneUseDominatesOtherUses(Reg, Op, MBB, MRI, MDT, LIS, MFI)) {
8403ca95b02SDimitry Andric           Insert = MoveAndTeeForMultiUse(Reg, Op, Def, MBB, Insert, LIS, MFI,
8413ca95b02SDimitry Andric                                          MRI, TII);
8423ca95b02SDimitry Andric         } else {
8433ca95b02SDimitry Andric           // We failed to stackify the operand. If the problem was ordering
8443ca95b02SDimitry Andric           // constraints, Commuting may be able to help.
8453ca95b02SDimitry Andric           if (!CanMove && SameBlock)
8463ca95b02SDimitry Andric             Commuting.MaybeCommute(Insert, TreeWalker, TII);
8473ca95b02SDimitry Andric           // Proceed to the next operand.
8487d523365SDimitry Andric           continue;
8497d523365SDimitry Andric         }
8503ca95b02SDimitry Andric 
851d88c1a5aSDimitry Andric         // If the instruction we just stackified is an IMPLICIT_DEF, convert it
852d88c1a5aSDimitry Andric         // to a constant 0 so that the def is explicit, and the push/pop
853d88c1a5aSDimitry Andric         // correspondence is maintained.
854d88c1a5aSDimitry Andric         if (Insert->getOpcode() == TargetOpcode::IMPLICIT_DEF)
855*b5893f02SDimitry Andric           ConvertImplicitDefToConstZero(Insert, MRI, TII, MF, LIS);
856d88c1a5aSDimitry Andric 
8573ca95b02SDimitry Andric         // We stackified an operand. Add the defining instruction's operands to
8583ca95b02SDimitry Andric         // the worklist stack now to continue to build an ever deeper tree.
8593ca95b02SDimitry Andric         Commuting.Reset();
8603ca95b02SDimitry Andric         TreeWalker.PushOperands(Insert);
8613ca95b02SDimitry Andric       }
8623ca95b02SDimitry Andric 
8633ca95b02SDimitry Andric       // If we stackified any operands, skip over the tree to start looking for
8643ca95b02SDimitry Andric       // the next instruction we can build a tree on.
8653ca95b02SDimitry Andric       if (Insert != &*MII) {
866444ed5c5SDimitry Andric         ImposeStackOrdering(&*MII);
867d88c1a5aSDimitry Andric         MII = MachineBasicBlock::iterator(Insert).getReverse();
8683ca95b02SDimitry Andric         Changed = true;
8693ca95b02SDimitry Andric       }
8707d523365SDimitry Andric     }
8717d523365SDimitry Andric   }
8727d523365SDimitry Andric 
873d88c1a5aSDimitry Andric   // If we used VALUE_STACK anywhere, add it to the live-in sets everywhere so
8743ca95b02SDimitry Andric   // that it never looks like a use-before-def.
8757d523365SDimitry Andric   if (Changed) {
876d88c1a5aSDimitry Andric     MF.getRegInfo().addLiveIn(WebAssembly::VALUE_STACK);
8777d523365SDimitry Andric     for (MachineBasicBlock &MBB : MF)
878d88c1a5aSDimitry Andric       MBB.addLiveIn(WebAssembly::VALUE_STACK);
8797d523365SDimitry Andric   }
8807d523365SDimitry Andric 
8817d523365SDimitry Andric #ifndef NDEBUG
8823ca95b02SDimitry Andric   // Verify that pushes and pops are performed in LIFO order.
8837d523365SDimitry Andric   SmallVector<unsigned, 0> Stack;
8847d523365SDimitry Andric   for (MachineBasicBlock &MBB : MF) {
8857d523365SDimitry Andric     for (MachineInstr &MI : MBB) {
8864ba319b5SDimitry Andric       if (MI.isDebugInstr())
8873ca95b02SDimitry Andric         continue;
8887d523365SDimitry Andric       for (MachineOperand &MO : reverse(MI.explicit_operands())) {
8897d523365SDimitry Andric         if (!MO.isReg())
8907d523365SDimitry Andric           continue;
8913ca95b02SDimitry Andric         unsigned Reg = MO.getReg();
8927d523365SDimitry Andric 
8933ca95b02SDimitry Andric         if (MFI.isVRegStackified(Reg)) {
8947d523365SDimitry Andric           if (MO.isDef())
8953ca95b02SDimitry Andric             Stack.push_back(Reg);
8967d523365SDimitry Andric           else
8973ca95b02SDimitry Andric             assert(Stack.pop_back_val() == Reg &&
8983ca95b02SDimitry Andric                    "Register stack pop should be paired with a push");
8997d523365SDimitry Andric         }
9007d523365SDimitry Andric       }
9017d523365SDimitry Andric     }
9027d523365SDimitry Andric     // TODO: Generalize this code to support keeping values on the stack across
9037d523365SDimitry Andric     // basic block boundaries.
9043ca95b02SDimitry Andric     assert(Stack.empty() &&
9053ca95b02SDimitry Andric            "Register stack pushes and pops should be balanced");
9067d523365SDimitry Andric   }
9077d523365SDimitry Andric #endif
9087d523365SDimitry Andric 
9097d523365SDimitry Andric   return Changed;
9107d523365SDimitry Andric }
911