11462faadSDan Gohman //===-- WebAssemblyRegStackify.cpp - Register Stackification --------------===//
21462faadSDan Gohman //
31462faadSDan Gohman //                     The LLVM Compiler Infrastructure
41462faadSDan Gohman //
51462faadSDan Gohman // This file is distributed under the University of Illinois Open Source
61462faadSDan Gohman // License. See LICENSE.TXT for details.
71462faadSDan Gohman //
81462faadSDan Gohman //===----------------------------------------------------------------------===//
91462faadSDan Gohman ///
101462faadSDan Gohman /// \file
115f8f34e4SAdrian Prantl /// This file implements a register stacking pass.
121462faadSDan Gohman ///
131462faadSDan Gohman /// This pass reorders instructions to put register uses and defs in an order
141462faadSDan Gohman /// such that they form single-use expression trees. Registers fitting this form
151462faadSDan Gohman /// are then marked as "stackified", meaning references to them are replaced by
16e040533eSDan Gohman /// "push" and "pop" from the value stack.
171462faadSDan Gohman ///
1831448f16SDan Gohman /// This is primarily a code size optimization, since temporary values on the
19e040533eSDan Gohman /// value stack don't need to be named.
201462faadSDan Gohman ///
211462faadSDan Gohman //===----------------------------------------------------------------------===//
221462faadSDan Gohman 
234ba4816bSDan Gohman #include "MCTargetDesc/WebAssemblyMCTargetDesc.h" // for WebAssembly::ARGUMENT_*
246bda14b3SChandler Carruth #include "WebAssembly.h"
257a6b9825SDan Gohman #include "WebAssemblyMachineFunctionInfo.h"
26b6fd39a3SDan Gohman #include "WebAssemblySubtarget.h"
274fc4e42dSDan Gohman #include "WebAssemblyUtilities.h"
287c18d608SYury Delendik #include "llvm/ADT/SmallPtrSet.h"
2981719f85SDan Gohman #include "llvm/Analysis/AliasAnalysis.h"
30f842297dSMatthias Braun #include "llvm/CodeGen/LiveIntervals.h"
311462faadSDan Gohman #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
32adf28177SDan Gohman #include "llvm/CodeGen/MachineDominators.h"
33adf28177SDan Gohman #include "llvm/CodeGen/MachineInstrBuilder.h"
3482607f56SDan Gohman #include "llvm/CodeGen/MachineModuleInfoImpls.h"
351462faadSDan Gohman #include "llvm/CodeGen/MachineRegisterInfo.h"
361462faadSDan Gohman #include "llvm/CodeGen/Passes.h"
371462faadSDan Gohman #include "llvm/Support/Debug.h"
381462faadSDan Gohman #include "llvm/Support/raw_ostream.h"
391462faadSDan Gohman using namespace llvm;
401462faadSDan Gohman 
411462faadSDan Gohman #define DEBUG_TYPE "wasm-reg-stackify"
421462faadSDan Gohman 
431462faadSDan Gohman namespace {
441462faadSDan Gohman class WebAssemblyRegStackify final : public MachineFunctionPass {
45117296c0SMehdi Amini   StringRef getPassName() const override {
461462faadSDan Gohman     return "WebAssembly Register Stackify";
471462faadSDan Gohman   }
481462faadSDan Gohman 
491462faadSDan Gohman   void getAnalysisUsage(AnalysisUsage &AU) const override {
501462faadSDan Gohman     AU.setPreservesCFG();
5181719f85SDan Gohman     AU.addRequired<AAResultsWrapperPass>();
52adf28177SDan Gohman     AU.addRequired<MachineDominatorTree>();
538887d1faSDan Gohman     AU.addRequired<LiveIntervals>();
541462faadSDan Gohman     AU.addPreserved<MachineBlockFrequencyInfo>();
558887d1faSDan Gohman     AU.addPreserved<SlotIndexes>();
568887d1faSDan Gohman     AU.addPreserved<LiveIntervals>();
578887d1faSDan Gohman     AU.addPreservedID(LiveVariablesID);
58adf28177SDan Gohman     AU.addPreserved<MachineDominatorTree>();
591462faadSDan Gohman     MachineFunctionPass::getAnalysisUsage(AU);
601462faadSDan Gohman   }
611462faadSDan Gohman 
621462faadSDan Gohman   bool runOnMachineFunction(MachineFunction &MF) override;
631462faadSDan Gohman 
641462faadSDan Gohman public:
651462faadSDan Gohman   static char ID; // Pass identification, replacement for typeid
661462faadSDan Gohman   WebAssemblyRegStackify() : MachineFunctionPass(ID) {}
671462faadSDan Gohman };
681462faadSDan Gohman } // end anonymous namespace
691462faadSDan Gohman 
701462faadSDan Gohman char WebAssemblyRegStackify::ID = 0;
7140926451SJacob Gravelle INITIALIZE_PASS(WebAssemblyRegStackify, DEBUG_TYPE,
7240926451SJacob Gravelle                 "Reorder instructions to use the WebAssembly value stack",
7340926451SJacob Gravelle                 false, false)
7440926451SJacob Gravelle 
751462faadSDan Gohman FunctionPass *llvm::createWebAssemblyRegStackify() {
761462faadSDan Gohman   return new WebAssemblyRegStackify();
771462faadSDan Gohman }
781462faadSDan Gohman 
79b0992dafSDan Gohman // Decorate the given instruction with implicit operands that enforce the
808887d1faSDan Gohman // expression stack ordering constraints for an instruction which is on
818887d1faSDan Gohman // the expression stack.
828887d1faSDan Gohman static void ImposeStackOrdering(MachineInstr *MI) {
83e040533eSDan Gohman   // Write the opaque VALUE_STACK register.
84e040533eSDan Gohman   if (!MI->definesRegister(WebAssembly::VALUE_STACK))
85e040533eSDan Gohman     MI->addOperand(MachineOperand::CreateReg(WebAssembly::VALUE_STACK,
86b0992dafSDan Gohman                                              /*isDef=*/true,
87b0992dafSDan Gohman                                              /*isImp=*/true));
884da4abd8SDan Gohman 
89e040533eSDan Gohman   // Also read the opaque VALUE_STACK register.
90e040533eSDan Gohman   if (!MI->readsRegister(WebAssembly::VALUE_STACK))
91e040533eSDan Gohman     MI->addOperand(MachineOperand::CreateReg(WebAssembly::VALUE_STACK,
92b0992dafSDan Gohman                                              /*isDef=*/false,
93b0992dafSDan Gohman                                              /*isImp=*/true));
94b0992dafSDan Gohman }
95b0992dafSDan Gohman 
96e81021a5SDan Gohman // Convert an IMPLICIT_DEF instruction into an instruction which defines
97e81021a5SDan Gohman // a constant zero value.
98e81021a5SDan Gohman static void ConvertImplicitDefToConstZero(MachineInstr *MI,
99e81021a5SDan Gohman                                           MachineRegisterInfo &MRI,
100e81021a5SDan Gohman                                           const TargetInstrInfo *TII,
101*feb18fe9SThomas Lively                                           MachineFunction &MF,
102*feb18fe9SThomas Lively                                           LiveIntervals &LIS) {
103e81021a5SDan Gohman   assert(MI->getOpcode() == TargetOpcode::IMPLICIT_DEF);
104e81021a5SDan Gohman 
105f208f631SHeejin Ahn   const auto *RegClass = MRI.getRegClass(MI->getOperand(0).getReg());
106e81021a5SDan Gohman   if (RegClass == &WebAssembly::I32RegClass) {
107e81021a5SDan Gohman     MI->setDesc(TII->get(WebAssembly::CONST_I32));
108e81021a5SDan Gohman     MI->addOperand(MachineOperand::CreateImm(0));
109e81021a5SDan Gohman   } else if (RegClass == &WebAssembly::I64RegClass) {
110e81021a5SDan Gohman     MI->setDesc(TII->get(WebAssembly::CONST_I64));
111e81021a5SDan Gohman     MI->addOperand(MachineOperand::CreateImm(0));
112e81021a5SDan Gohman   } else if (RegClass == &WebAssembly::F32RegClass) {
113e81021a5SDan Gohman     MI->setDesc(TII->get(WebAssembly::CONST_F32));
114e81021a5SDan Gohman     ConstantFP *Val = cast<ConstantFP>(Constant::getNullValue(
11521109249SDavid Blaikie         Type::getFloatTy(MF.getFunction().getContext())));
116e81021a5SDan Gohman     MI->addOperand(MachineOperand::CreateFPImm(Val));
117e81021a5SDan Gohman   } else if (RegClass == &WebAssembly::F64RegClass) {
118e81021a5SDan Gohman     MI->setDesc(TII->get(WebAssembly::CONST_F64));
119e81021a5SDan Gohman     ConstantFP *Val = cast<ConstantFP>(Constant::getNullValue(
12021109249SDavid Blaikie         Type::getDoubleTy(MF.getFunction().getContext())));
121e81021a5SDan Gohman     MI->addOperand(MachineOperand::CreateFPImm(Val));
1226ff31fe3SThomas Lively   } else if (RegClass == &WebAssembly::V128RegClass) {
123*feb18fe9SThomas Lively     unsigned TempReg = MRI.createVirtualRegister(&WebAssembly::I32RegClass);
124*feb18fe9SThomas Lively     MI->setDesc(TII->get(WebAssembly::SPLAT_v4i32));
125*feb18fe9SThomas Lively     MI->addOperand(MachineOperand::CreateReg(TempReg, false));
126*feb18fe9SThomas Lively     MachineInstr *Const = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
127*feb18fe9SThomas Lively                                   TII->get(WebAssembly::CONST_I32), TempReg)
128*feb18fe9SThomas Lively                               .addImm(0);
129*feb18fe9SThomas Lively     LIS.InsertMachineInstrInMaps(*Const);
130e81021a5SDan Gohman   } else {
131e81021a5SDan Gohman     llvm_unreachable("Unexpected reg class");
132e81021a5SDan Gohman   }
133e81021a5SDan Gohman }
134e81021a5SDan Gohman 
1352644d74bSDan Gohman // Determine whether a call to the callee referenced by
1362644d74bSDan Gohman // MI->getOperand(CalleeOpNo) reads memory, writes memory, and/or has side
1372644d74bSDan Gohman // effects.
138500d0469SDuncan P. N. Exon Smith static void QueryCallee(const MachineInstr &MI, unsigned CalleeOpNo, bool &Read,
139500d0469SDuncan P. N. Exon Smith                         bool &Write, bool &Effects, bool &StackPointer) {
140d08cd15fSDan Gohman   // All calls can use the stack pointer.
141d08cd15fSDan Gohman   StackPointer = true;
142d08cd15fSDan Gohman 
143500d0469SDuncan P. N. Exon Smith   const MachineOperand &MO = MI.getOperand(CalleeOpNo);
1442644d74bSDan Gohman   if (MO.isGlobal()) {
1452644d74bSDan Gohman     const Constant *GV = MO.getGlobal();
1462644d74bSDan Gohman     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
1472644d74bSDan Gohman       if (!GA->isInterposable())
1482644d74bSDan Gohman         GV = GA->getAliasee();
1492644d74bSDan Gohman 
1502644d74bSDan Gohman     if (const Function *F = dyn_cast<Function>(GV)) {
1512644d74bSDan Gohman       if (!F->doesNotThrow())
1522644d74bSDan Gohman         Effects = true;
1532644d74bSDan Gohman       if (F->doesNotAccessMemory())
1542644d74bSDan Gohman         return;
1552644d74bSDan Gohman       if (F->onlyReadsMemory()) {
1562644d74bSDan Gohman         Read = true;
1572644d74bSDan Gohman         return;
1582644d74bSDan Gohman       }
1592644d74bSDan Gohman     }
1602644d74bSDan Gohman   }
1612644d74bSDan Gohman 
1622644d74bSDan Gohman   // Assume the worst.
1632644d74bSDan Gohman   Write = true;
1642644d74bSDan Gohman   Read = true;
1652644d74bSDan Gohman   Effects = true;
1662644d74bSDan Gohman }
1672644d74bSDan Gohman 
168d08cd15fSDan Gohman // Determine whether MI reads memory, writes memory, has side effects,
16982607f56SDan Gohman // and/or uses the stack pointer value.
170500d0469SDuncan P. N. Exon Smith static void Query(const MachineInstr &MI, AliasAnalysis &AA, bool &Read,
171500d0469SDuncan P. N. Exon Smith                   bool &Write, bool &Effects, bool &StackPointer) {
172500d0469SDuncan P. N. Exon Smith   assert(!MI.isTerminator());
1736c8f20d7SDan Gohman 
1745ef4d5f9SHeejin Ahn   if (MI.isDebugInstr() || MI.isPosition())
1756c8f20d7SDan Gohman     return;
1762644d74bSDan Gohman 
1772644d74bSDan Gohman   // Check for loads.
178d98cf00cSJustin Lebar   if (MI.mayLoad() && !MI.isDereferenceableInvariantLoad(&AA))
1792644d74bSDan Gohman     Read = true;
1802644d74bSDan Gohman 
1812644d74bSDan Gohman   // Check for stores.
182500d0469SDuncan P. N. Exon Smith   if (MI.mayStore()) {
1832644d74bSDan Gohman     Write = true;
184d08cd15fSDan Gohman 
185d08cd15fSDan Gohman     // Check for stores to __stack_pointer.
186500d0469SDuncan P. N. Exon Smith     for (auto MMO : MI.memoperands()) {
187d08cd15fSDan Gohman       const MachinePointerInfo &MPI = MMO->getPointerInfo();
188d08cd15fSDan Gohman       if (MPI.V.is<const PseudoSourceValue *>()) {
189d08cd15fSDan Gohman         auto PSV = MPI.V.get<const PseudoSourceValue *>();
190d08cd15fSDan Gohman         if (const ExternalSymbolPseudoSourceValue *EPSV =
191d08cd15fSDan Gohman                 dyn_cast<ExternalSymbolPseudoSourceValue>(PSV))
1929d24fb7fSSam Clegg           if (StringRef(EPSV->getSymbol()) == "__stack_pointer") {
193d08cd15fSDan Gohman             StackPointer = true;
194d08cd15fSDan Gohman           }
195d08cd15fSDan Gohman       }
19682607f56SDan Gohman     }
197500d0469SDuncan P. N. Exon Smith   } else if (MI.hasOrderedMemoryRef()) {
198500d0469SDuncan P. N. Exon Smith     switch (MI.getOpcode()) {
199f208f631SHeejin Ahn     case WebAssembly::DIV_S_I32:
200f208f631SHeejin Ahn     case WebAssembly::DIV_S_I64:
201f208f631SHeejin Ahn     case WebAssembly::REM_S_I32:
202f208f631SHeejin Ahn     case WebAssembly::REM_S_I64:
203f208f631SHeejin Ahn     case WebAssembly::DIV_U_I32:
204f208f631SHeejin Ahn     case WebAssembly::DIV_U_I64:
205f208f631SHeejin Ahn     case WebAssembly::REM_U_I32:
206f208f631SHeejin Ahn     case WebAssembly::REM_U_I64:
207f208f631SHeejin Ahn     case WebAssembly::I32_TRUNC_S_F32:
208f208f631SHeejin Ahn     case WebAssembly::I64_TRUNC_S_F32:
209f208f631SHeejin Ahn     case WebAssembly::I32_TRUNC_S_F64:
210f208f631SHeejin Ahn     case WebAssembly::I64_TRUNC_S_F64:
211f208f631SHeejin Ahn     case WebAssembly::I32_TRUNC_U_F32:
212f208f631SHeejin Ahn     case WebAssembly::I64_TRUNC_U_F32:
213f208f631SHeejin Ahn     case WebAssembly::I32_TRUNC_U_F64:
214f208f631SHeejin Ahn     case WebAssembly::I64_TRUNC_U_F64:
2152644d74bSDan Gohman       // These instruction have hasUnmodeledSideEffects() returning true
2162644d74bSDan Gohman       // because they trap on overflow and invalid so they can't be arbitrarily
2172644d74bSDan Gohman       // moved, however hasOrderedMemoryRef() interprets this plus their lack
2182644d74bSDan Gohman       // of memoperands as having a potential unknown memory reference.
2192644d74bSDan Gohman       break;
2202644d74bSDan Gohman     default:
2211054570aSDan Gohman       // Record volatile accesses, unless it's a call, as calls are handled
2222644d74bSDan Gohman       // specially below.
223500d0469SDuncan P. N. Exon Smith       if (!MI.isCall()) {
2242644d74bSDan Gohman         Write = true;
2251054570aSDan Gohman         Effects = true;
2261054570aSDan Gohman       }
2272644d74bSDan Gohman       break;
2282644d74bSDan Gohman     }
2292644d74bSDan Gohman   }
2302644d74bSDan Gohman 
2312644d74bSDan Gohman   // Check for side effects.
232500d0469SDuncan P. N. Exon Smith   if (MI.hasUnmodeledSideEffects()) {
233500d0469SDuncan P. N. Exon Smith     switch (MI.getOpcode()) {
234f208f631SHeejin Ahn     case WebAssembly::DIV_S_I32:
235f208f631SHeejin Ahn     case WebAssembly::DIV_S_I64:
236f208f631SHeejin Ahn     case WebAssembly::REM_S_I32:
237f208f631SHeejin Ahn     case WebAssembly::REM_S_I64:
238f208f631SHeejin Ahn     case WebAssembly::DIV_U_I32:
239f208f631SHeejin Ahn     case WebAssembly::DIV_U_I64:
240f208f631SHeejin Ahn     case WebAssembly::REM_U_I32:
241f208f631SHeejin Ahn     case WebAssembly::REM_U_I64:
242f208f631SHeejin Ahn     case WebAssembly::I32_TRUNC_S_F32:
243f208f631SHeejin Ahn     case WebAssembly::I64_TRUNC_S_F32:
244f208f631SHeejin Ahn     case WebAssembly::I32_TRUNC_S_F64:
245f208f631SHeejin Ahn     case WebAssembly::I64_TRUNC_S_F64:
246f208f631SHeejin Ahn     case WebAssembly::I32_TRUNC_U_F32:
247f208f631SHeejin Ahn     case WebAssembly::I64_TRUNC_U_F32:
248f208f631SHeejin Ahn     case WebAssembly::I32_TRUNC_U_F64:
249f208f631SHeejin Ahn     case WebAssembly::I64_TRUNC_U_F64:
2502644d74bSDan Gohman       // These instructions have hasUnmodeledSideEffects() returning true
2512644d74bSDan Gohman       // because they trap on overflow and invalid so they can't be arbitrarily
2522644d74bSDan Gohman       // moved, however in the specific case of register stackifying, it is safe
2532644d74bSDan Gohman       // to move them because overflow and invalid are Undefined Behavior.
2542644d74bSDan Gohman       break;
2552644d74bSDan Gohman     default:
2562644d74bSDan Gohman       Effects = true;
2572644d74bSDan Gohman       break;
2582644d74bSDan Gohman     }
2592644d74bSDan Gohman   }
2602644d74bSDan Gohman 
2612644d74bSDan Gohman   // Analyze calls.
262500d0469SDuncan P. N. Exon Smith   if (MI.isCall()) {
26356e79dd0SHeejin Ahn     unsigned CalleeOpNo = WebAssembly::getCalleeOpNo(MI);
26456e79dd0SHeejin Ahn     QueryCallee(MI, CalleeOpNo, Read, Write, Effects, StackPointer);
2652644d74bSDan Gohman   }
2662644d74bSDan Gohman }
2672644d74bSDan Gohman 
2682644d74bSDan Gohman // Test whether Def is safe and profitable to rematerialize.
2699cfc75c2SDuncan P. N. Exon Smith static bool ShouldRematerialize(const MachineInstr &Def, AliasAnalysis &AA,
2702644d74bSDan Gohman                                 const WebAssemblyInstrInfo *TII) {
2719cfc75c2SDuncan P. N. Exon Smith   return Def.isAsCheapAsAMove() && TII->isTriviallyReMaterializable(Def, &AA);
2722644d74bSDan Gohman }
2732644d74bSDan Gohman 
27412de0b91SDan Gohman // Identify the definition for this register at this point. This is a
27512de0b91SDan Gohman // generalization of MachineRegisterInfo::getUniqueVRegDef that uses
27612de0b91SDan Gohman // LiveIntervals to handle complex cases.
2772644d74bSDan Gohman static MachineInstr *GetVRegDef(unsigned Reg, const MachineInstr *Insert,
2782644d74bSDan Gohman                                 const MachineRegisterInfo &MRI,
279f208f631SHeejin Ahn                                 const LiveIntervals &LIS) {
2802644d74bSDan Gohman   // Most registers are in SSA form here so we try a quick MRI query first.
2812644d74bSDan Gohman   if (MachineInstr *Def = MRI.getUniqueVRegDef(Reg))
2822644d74bSDan Gohman     return Def;
2832644d74bSDan Gohman 
2842644d74bSDan Gohman   // MRI doesn't know what the Def is. Try asking LIS.
2852644d74bSDan Gohman   if (const VNInfo *ValNo = LIS.getInterval(Reg).getVNInfoBefore(
2862644d74bSDan Gohman           LIS.getInstructionIndex(*Insert)))
2872644d74bSDan Gohman     return LIS.getInstructionFromIndex(ValNo->def);
2882644d74bSDan Gohman 
2892644d74bSDan Gohman   return nullptr;
2902644d74bSDan Gohman }
2912644d74bSDan Gohman 
29212de0b91SDan Gohman // Test whether Reg, as defined at Def, has exactly one use. This is a
29312de0b91SDan Gohman // generalization of MachineRegisterInfo::hasOneUse that uses LiveIntervals
29412de0b91SDan Gohman // to handle complex cases.
295f208f631SHeejin Ahn static bool HasOneUse(unsigned Reg, MachineInstr *Def, MachineRegisterInfo &MRI,
296f208f631SHeejin Ahn                       MachineDominatorTree &MDT, LiveIntervals &LIS) {
29712de0b91SDan Gohman   // Most registers are in SSA form here so we try a quick MRI query first.
29812de0b91SDan Gohman   if (MRI.hasOneUse(Reg))
29912de0b91SDan Gohman     return true;
30012de0b91SDan Gohman 
30112de0b91SDan Gohman   bool HasOne = false;
30212de0b91SDan Gohman   const LiveInterval &LI = LIS.getInterval(Reg);
303f208f631SHeejin Ahn   const VNInfo *DefVNI =
304f208f631SHeejin Ahn       LI.getVNInfoAt(LIS.getInstructionIndex(*Def).getRegSlot());
30512de0b91SDan Gohman   assert(DefVNI);
306a8a63829SDominic Chen   for (auto &I : MRI.use_nodbg_operands(Reg)) {
30712de0b91SDan Gohman     const auto &Result = LI.Query(LIS.getInstructionIndex(*I.getParent()));
30812de0b91SDan Gohman     if (Result.valueIn() == DefVNI) {
30912de0b91SDan Gohman       if (!Result.isKill())
31012de0b91SDan Gohman         return false;
31112de0b91SDan Gohman       if (HasOne)
31212de0b91SDan Gohman         return false;
31312de0b91SDan Gohman       HasOne = true;
31412de0b91SDan Gohman     }
31512de0b91SDan Gohman   }
31612de0b91SDan Gohman   return HasOne;
31712de0b91SDan Gohman }
31812de0b91SDan Gohman 
3198887d1faSDan Gohman // Test whether it's safe to move Def to just before Insert.
32081719f85SDan Gohman // TODO: Compute memory dependencies in a way that doesn't require always
32181719f85SDan Gohman // walking the block.
32281719f85SDan Gohman // TODO: Compute memory dependencies in a way that uses AliasAnalysis to be
32381719f85SDan Gohman // more precise.
32481719f85SDan Gohman static bool IsSafeToMove(const MachineInstr *Def, const MachineInstr *Insert,
325e9e6891bSDerek Schuff                          AliasAnalysis &AA, const MachineRegisterInfo &MRI) {
326391a98afSDan Gohman   assert(Def->getParent() == Insert->getParent());
3278887d1faSDan Gohman 
3288887d1faSDan Gohman   // Check for register dependencies.
329e9e6891bSDerek Schuff   SmallVector<unsigned, 4> MutableRegisters;
3308887d1faSDan Gohman   for (const MachineOperand &MO : Def->operands()) {
3318887d1faSDan Gohman     if (!MO.isReg() || MO.isUndef())
3328887d1faSDan Gohman       continue;
3338887d1faSDan Gohman     unsigned Reg = MO.getReg();
3348887d1faSDan Gohman 
3358887d1faSDan Gohman     // If the register is dead here and at Insert, ignore it.
3368887d1faSDan Gohman     if (MO.isDead() && Insert->definesRegister(Reg) &&
3378887d1faSDan Gohman         !Insert->readsRegister(Reg))
3388887d1faSDan Gohman       continue;
3398887d1faSDan Gohman 
3408887d1faSDan Gohman     if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
3410cfb5f85SDan Gohman       // Ignore ARGUMENTS; it's just used to keep the ARGUMENT_* instructions
3420cfb5f85SDan Gohman       // from moving down, and we've already checked for that.
3430cfb5f85SDan Gohman       if (Reg == WebAssembly::ARGUMENTS)
3440cfb5f85SDan Gohman         continue;
3458887d1faSDan Gohman       // If the physical register is never modified, ignore it.
3468887d1faSDan Gohman       if (!MRI.isPhysRegModified(Reg))
3478887d1faSDan Gohman         continue;
3488887d1faSDan Gohman       // Otherwise, it's a physical register with unknown liveness.
3498887d1faSDan Gohman       return false;
3508887d1faSDan Gohman     }
3518887d1faSDan Gohman 
352e9e6891bSDerek Schuff     // If one of the operands isn't in SSA form, it has different values at
353e9e6891bSDerek Schuff     // different times, and we need to make sure we don't move our use across
354e9e6891bSDerek Schuff     // a different def.
355e9e6891bSDerek Schuff     if (!MO.isDef() && !MRI.hasOneDef(Reg))
356e9e6891bSDerek Schuff       MutableRegisters.push_back(Reg);
3578887d1faSDan Gohman   }
3588887d1faSDan Gohman 
359d08cd15fSDan Gohman   bool Read = false, Write = false, Effects = false, StackPointer = false;
360500d0469SDuncan P. N. Exon Smith   Query(*Def, AA, Read, Write, Effects, StackPointer);
3612644d74bSDan Gohman 
3622644d74bSDan Gohman   // If the instruction does not access memory and has no side effects, it has
3632644d74bSDan Gohman   // no additional dependencies.
364e9e6891bSDerek Schuff   bool HasMutableRegisters = !MutableRegisters.empty();
365e9e6891bSDerek Schuff   if (!Read && !Write && !Effects && !StackPointer && !HasMutableRegisters)
3662644d74bSDan Gohman     return true;
3672644d74bSDan Gohman 
3682644d74bSDan Gohman   // Scan through the intervening instructions between Def and Insert.
3692644d74bSDan Gohman   MachineBasicBlock::const_iterator D(Def), I(Insert);
3702644d74bSDan Gohman   for (--I; I != D; --I) {
3712644d74bSDan Gohman     bool InterveningRead = false;
3722644d74bSDan Gohman     bool InterveningWrite = false;
3732644d74bSDan Gohman     bool InterveningEffects = false;
374d08cd15fSDan Gohman     bool InterveningStackPointer = false;
375500d0469SDuncan P. N. Exon Smith     Query(*I, AA, InterveningRead, InterveningWrite, InterveningEffects,
376d08cd15fSDan Gohman           InterveningStackPointer);
3772644d74bSDan Gohman     if (Effects && InterveningEffects)
3782644d74bSDan Gohman       return false;
3792644d74bSDan Gohman     if (Read && InterveningWrite)
3802644d74bSDan Gohman       return false;
3812644d74bSDan Gohman     if (Write && (InterveningRead || InterveningWrite))
3822644d74bSDan Gohman       return false;
383d08cd15fSDan Gohman     if (StackPointer && InterveningStackPointer)
384d08cd15fSDan Gohman       return false;
385e9e6891bSDerek Schuff 
386e9e6891bSDerek Schuff     for (unsigned Reg : MutableRegisters)
387e9e6891bSDerek Schuff       for (const MachineOperand &MO : I->operands())
388e9e6891bSDerek Schuff         if (MO.isReg() && MO.isDef() && MO.getReg() == Reg)
389e9e6891bSDerek Schuff           return false;
3902644d74bSDan Gohman   }
3912644d74bSDan Gohman 
3922644d74bSDan Gohman   return true;
39381719f85SDan Gohman }
39481719f85SDan Gohman 
395adf28177SDan Gohman /// Test whether OneUse, a use of Reg, dominates all of Reg's other uses.
396adf28177SDan Gohman static bool OneUseDominatesOtherUses(unsigned Reg, const MachineOperand &OneUse,
397adf28177SDan Gohman                                      const MachineBasicBlock &MBB,
398adf28177SDan Gohman                                      const MachineRegisterInfo &MRI,
3990cfb5f85SDan Gohman                                      const MachineDominatorTree &MDT,
4001054570aSDan Gohman                                      LiveIntervals &LIS,
4011054570aSDan Gohman                                      WebAssemblyFunctionInfo &MFI) {
4020cfb5f85SDan Gohman   const LiveInterval &LI = LIS.getInterval(Reg);
4030cfb5f85SDan Gohman 
4040cfb5f85SDan Gohman   const MachineInstr *OneUseInst = OneUse.getParent();
4050cfb5f85SDan Gohman   VNInfo *OneUseVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*OneUseInst));
4060cfb5f85SDan Gohman 
407a8a63829SDominic Chen   for (const MachineOperand &Use : MRI.use_nodbg_operands(Reg)) {
408adf28177SDan Gohman     if (&Use == &OneUse)
409adf28177SDan Gohman       continue;
4100cfb5f85SDan Gohman 
411adf28177SDan Gohman     const MachineInstr *UseInst = Use.getParent();
4120cfb5f85SDan Gohman     VNInfo *UseVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*UseInst));
4130cfb5f85SDan Gohman 
4140cfb5f85SDan Gohman     if (UseVNI != OneUseVNI)
4150cfb5f85SDan Gohman       continue;
4160cfb5f85SDan Gohman 
417adf28177SDan Gohman     const MachineInstr *OneUseInst = OneUse.getParent();
41812de0b91SDan Gohman     if (UseInst == OneUseInst) {
419adf28177SDan Gohman       // Another use in the same instruction. We need to ensure that the one
420adf28177SDan Gohman       // selected use happens "before" it.
421adf28177SDan Gohman       if (&OneUse > &Use)
422adf28177SDan Gohman         return false;
423adf28177SDan Gohman     } else {
424adf28177SDan Gohman       // Test that the use is dominated by the one selected use.
4251054570aSDan Gohman       while (!MDT.dominates(OneUseInst, UseInst)) {
4261054570aSDan Gohman         // Actually, dominating is over-conservative. Test that the use would
4271054570aSDan Gohman         // happen after the one selected use in the stack evaluation order.
4281054570aSDan Gohman         //
4291054570aSDan Gohman         // This is needed as a consequence of using implicit get_locals for
4301054570aSDan Gohman         // uses and implicit set_locals for defs.
4311054570aSDan Gohman         if (UseInst->getDesc().getNumDefs() == 0)
432adf28177SDan Gohman           return false;
4331054570aSDan Gohman         const MachineOperand &MO = UseInst->getOperand(0);
4341054570aSDan Gohman         if (!MO.isReg())
4351054570aSDan Gohman           return false;
4361054570aSDan Gohman         unsigned DefReg = MO.getReg();
4371054570aSDan Gohman         if (!TargetRegisterInfo::isVirtualRegister(DefReg) ||
4381054570aSDan Gohman             !MFI.isVRegStackified(DefReg))
4391054570aSDan Gohman           return false;
440b3857e4dSYury Delendik         assert(MRI.hasOneNonDBGUse(DefReg));
441b3857e4dSYury Delendik         const MachineOperand &NewUse = *MRI.use_nodbg_begin(DefReg);
4421054570aSDan Gohman         const MachineInstr *NewUseInst = NewUse.getParent();
4431054570aSDan Gohman         if (NewUseInst == OneUseInst) {
4441054570aSDan Gohman           if (&OneUse > &NewUse)
4451054570aSDan Gohman             return false;
4461054570aSDan Gohman           break;
4471054570aSDan Gohman         }
4481054570aSDan Gohman         UseInst = NewUseInst;
4491054570aSDan Gohman       }
450adf28177SDan Gohman     }
451adf28177SDan Gohman   }
452adf28177SDan Gohman   return true;
453adf28177SDan Gohman }
454adf28177SDan Gohman 
4554fc4e42dSDan Gohman /// Get the appropriate tee opcode for the given register class.
4564fc4e42dSDan Gohman static unsigned GetTeeOpcode(const TargetRegisterClass *RC) {
457adf28177SDan Gohman   if (RC == &WebAssembly::I32RegClass)
4584fc4e42dSDan Gohman     return WebAssembly::TEE_I32;
459adf28177SDan Gohman   if (RC == &WebAssembly::I64RegClass)
4604fc4e42dSDan Gohman     return WebAssembly::TEE_I64;
461adf28177SDan Gohman   if (RC == &WebAssembly::F32RegClass)
4624fc4e42dSDan Gohman     return WebAssembly::TEE_F32;
463adf28177SDan Gohman   if (RC == &WebAssembly::F64RegClass)
4644fc4e42dSDan Gohman     return WebAssembly::TEE_F64;
46539bf39f3SDerek Schuff   if (RC == &WebAssembly::V128RegClass)
4664fc4e42dSDan Gohman     return WebAssembly::TEE_V128;
467adf28177SDan Gohman   llvm_unreachable("Unexpected register class");
468adf28177SDan Gohman }
469adf28177SDan Gohman 
4702644d74bSDan Gohman // Shrink LI to its uses, cleaning up LI.
4712644d74bSDan Gohman static void ShrinkToUses(LiveInterval &LI, LiveIntervals &LIS) {
4722644d74bSDan Gohman   if (LIS.shrinkToUses(&LI)) {
4732644d74bSDan Gohman     SmallVector<LiveInterval *, 4> SplitLIs;
4742644d74bSDan Gohman     LIS.splitSeparateComponents(LI, SplitLIs);
4752644d74bSDan Gohman   }
4762644d74bSDan Gohman }
4772644d74bSDan Gohman 
4787c18d608SYury Delendik static void MoveDebugValues(unsigned Reg, MachineInstr *Insert,
4797c18d608SYury Delendik                             MachineBasicBlock &MBB, MachineRegisterInfo &MRI) {
4807c18d608SYury Delendik   for (auto &Op : MRI.reg_operands(Reg)) {
4817c18d608SYury Delendik     MachineInstr *MI = Op.getParent();
4827c18d608SYury Delendik     assert(MI != nullptr);
4837c18d608SYury Delendik     if (MI->isDebugValue() && MI->getParent() == &MBB)
4847c18d608SYury Delendik       MBB.splice(Insert, &MBB, MI);
4857c18d608SYury Delendik   }
4867c18d608SYury Delendik }
4877c18d608SYury Delendik 
4887c18d608SYury Delendik static void UpdateDebugValuesReg(unsigned Reg, unsigned NewReg,
4897c18d608SYury Delendik                                  MachineBasicBlock &MBB,
4907c18d608SYury Delendik                                  MachineRegisterInfo &MRI) {
4917c18d608SYury Delendik   for (auto &Op : MRI.reg_operands(Reg)) {
4927c18d608SYury Delendik     MachineInstr *MI = Op.getParent();
4937c18d608SYury Delendik     assert(MI != nullptr);
4947c18d608SYury Delendik     if (MI->isDebugValue() && MI->getParent() == &MBB)
4957c18d608SYury Delendik       Op.setReg(NewReg);
4967c18d608SYury Delendik   }
4977c18d608SYury Delendik }
4987c18d608SYury Delendik 
499adf28177SDan Gohman /// A single-use def in the same block with no intervening memory or register
500adf28177SDan Gohman /// dependencies; move the def down and nest it with the current instruction.
5010cfb5f85SDan Gohman static MachineInstr *MoveForSingleUse(unsigned Reg, MachineOperand &Op,
502f208f631SHeejin Ahn                                       MachineInstr *Def, MachineBasicBlock &MBB,
503adf28177SDan Gohman                                       MachineInstr *Insert, LiveIntervals &LIS,
5040cfb5f85SDan Gohman                                       WebAssemblyFunctionInfo &MFI,
5050cfb5f85SDan Gohman                                       MachineRegisterInfo &MRI) {
506d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Move for single use: "; Def->dump());
5072644d74bSDan Gohman 
508adf28177SDan Gohman   MBB.splice(Insert, &MBB, Def);
5097c18d608SYury Delendik   MoveDebugValues(Reg, Insert, MBB, MRI);
5101afd1e2bSJF Bastien   LIS.handleMove(*Def);
5110cfb5f85SDan Gohman 
51212de0b91SDan Gohman   if (MRI.hasOneDef(Reg) && MRI.hasOneUse(Reg)) {
51312de0b91SDan Gohman     // No one else is using this register for anything so we can just stackify
51412de0b91SDan Gohman     // it in place.
515adf28177SDan Gohman     MFI.stackifyVReg(Reg);
5160cfb5f85SDan Gohman   } else {
51712de0b91SDan Gohman     // The register may have unrelated uses or defs; create a new register for
51812de0b91SDan Gohman     // just our one def and use so that we can stackify it.
5190cfb5f85SDan Gohman     unsigned NewReg = MRI.createVirtualRegister(MRI.getRegClass(Reg));
5200cfb5f85SDan Gohman     Def->getOperand(0).setReg(NewReg);
5210cfb5f85SDan Gohman     Op.setReg(NewReg);
5220cfb5f85SDan Gohman 
5230cfb5f85SDan Gohman     // Tell LiveIntervals about the new register.
5240cfb5f85SDan Gohman     LIS.createAndComputeVirtRegInterval(NewReg);
5250cfb5f85SDan Gohman 
5260cfb5f85SDan Gohman     // Tell LiveIntervals about the changes to the old register.
5270cfb5f85SDan Gohman     LiveInterval &LI = LIS.getInterval(Reg);
5286c8f20d7SDan Gohman     LI.removeSegment(LIS.getInstructionIndex(*Def).getRegSlot(),
5296c8f20d7SDan Gohman                      LIS.getInstructionIndex(*Op.getParent()).getRegSlot(),
5306c8f20d7SDan Gohman                      /*RemoveDeadValNo=*/true);
5310cfb5f85SDan Gohman 
5320cfb5f85SDan Gohman     MFI.stackifyVReg(NewReg);
5332644d74bSDan Gohman 
5347c18d608SYury Delendik     UpdateDebugValuesReg(Reg, NewReg, MBB, MRI);
5357c18d608SYury Delendik 
536d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << " - Replaced register: "; Def->dump());
5370cfb5f85SDan Gohman   }
5380cfb5f85SDan Gohman 
539adf28177SDan Gohman   ImposeStackOrdering(Def);
540adf28177SDan Gohman   return Def;
541adf28177SDan Gohman }
542adf28177SDan Gohman 
5437c18d608SYury Delendik static void CloneDebugValues(unsigned Reg, MachineInstr *Insert,
5447c18d608SYury Delendik                              unsigned TargetReg, MachineBasicBlock &MBB,
5457c18d608SYury Delendik                              MachineRegisterInfo &MRI,
5467c18d608SYury Delendik                              const WebAssemblyInstrInfo *TII) {
5477c18d608SYury Delendik   SmallPtrSet<MachineInstr *, 4> Instrs;
5487c18d608SYury Delendik   for (auto &Op : MRI.reg_operands(Reg)) {
5497c18d608SYury Delendik     MachineInstr *MI = Op.getParent();
5507c18d608SYury Delendik     assert(MI != nullptr);
5517c18d608SYury Delendik     if (MI->isDebugValue() && MI->getParent() == &MBB &&
5527c18d608SYury Delendik         Instrs.find(MI) == Instrs.end())
5537c18d608SYury Delendik       Instrs.insert(MI);
5547c18d608SYury Delendik   }
5557c18d608SYury Delendik   for (const auto &MI : Instrs) {
5567c18d608SYury Delendik     MachineInstr &Clone = TII->duplicate(MBB, Insert, *MI);
5577c18d608SYury Delendik     for (unsigned i = 0, e = Clone.getNumOperands(); i != e; ++i) {
5587c18d608SYury Delendik       MachineOperand &MO = Clone.getOperand(i);
5597c18d608SYury Delendik       if (MO.isReg() && MO.getReg() == Reg)
5607c18d608SYury Delendik         MO.setReg(TargetReg);
5617c18d608SYury Delendik     }
5627c18d608SYury Delendik     LLVM_DEBUG(dbgs() << " - - Cloned DBG_VALUE: "; Clone.dump());
5637c18d608SYury Delendik   }
5647c18d608SYury Delendik }
5657c18d608SYury Delendik 
566adf28177SDan Gohman /// A trivially cloneable instruction; clone it and nest the new copy with the
567adf28177SDan Gohman /// current instruction.
5689cfc75c2SDuncan P. N. Exon Smith static MachineInstr *RematerializeCheapDef(
5699cfc75c2SDuncan P. N. Exon Smith     unsigned Reg, MachineOperand &Op, MachineInstr &Def, MachineBasicBlock &MBB,
5709cfc75c2SDuncan P. N. Exon Smith     MachineBasicBlock::instr_iterator Insert, LiveIntervals &LIS,
5719cfc75c2SDuncan P. N. Exon Smith     WebAssemblyFunctionInfo &MFI, MachineRegisterInfo &MRI,
5729cfc75c2SDuncan P. N. Exon Smith     const WebAssemblyInstrInfo *TII, const WebAssemblyRegisterInfo *TRI) {
573d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Rematerializing cheap def: "; Def.dump());
574d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << " - for use in "; Op.getParent()->dump());
5752644d74bSDan Gohman 
576adf28177SDan Gohman   unsigned NewReg = MRI.createVirtualRegister(MRI.getRegClass(Reg));
577adf28177SDan Gohman   TII->reMaterialize(MBB, Insert, NewReg, 0, Def, *TRI);
578adf28177SDan Gohman   Op.setReg(NewReg);
5799cfc75c2SDuncan P. N. Exon Smith   MachineInstr *Clone = &*std::prev(Insert);
58013d3b9b7SJF Bastien   LIS.InsertMachineInstrInMaps(*Clone);
581adf28177SDan Gohman   LIS.createAndComputeVirtRegInterval(NewReg);
582adf28177SDan Gohman   MFI.stackifyVReg(NewReg);
583adf28177SDan Gohman   ImposeStackOrdering(Clone);
584adf28177SDan Gohman 
585d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << " - Cloned to "; Clone->dump());
5862644d74bSDan Gohman 
5870cfb5f85SDan Gohman   // Shrink the interval.
5880cfb5f85SDan Gohman   bool IsDead = MRI.use_empty(Reg);
5890cfb5f85SDan Gohman   if (!IsDead) {
5900cfb5f85SDan Gohman     LiveInterval &LI = LIS.getInterval(Reg);
5912644d74bSDan Gohman     ShrinkToUses(LI, LIS);
5929cfc75c2SDuncan P. N. Exon Smith     IsDead = !LI.liveAt(LIS.getInstructionIndex(Def).getDeadSlot());
5930cfb5f85SDan Gohman   }
5940cfb5f85SDan Gohman 
595adf28177SDan Gohman   // If that was the last use of the original, delete the original.
5967c18d608SYury Delendik   // Move or clone corresponding DBG_VALUEs to the 'Insert' location.
5970cfb5f85SDan Gohman   if (IsDead) {
598d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << " - Deleting original\n");
5999cfc75c2SDuncan P. N. Exon Smith     SlotIndex Idx = LIS.getInstructionIndex(Def).getRegSlot();
600adf28177SDan Gohman     LIS.removePhysRegDefAt(WebAssembly::ARGUMENTS, Idx);
601adf28177SDan Gohman     LIS.removeInterval(Reg);
6029cfc75c2SDuncan P. N. Exon Smith     LIS.RemoveMachineInstrFromMaps(Def);
6039cfc75c2SDuncan P. N. Exon Smith     Def.eraseFromParent();
6047c18d608SYury Delendik 
6057c18d608SYury Delendik     MoveDebugValues(Reg, &*Insert, MBB, MRI);
6067c18d608SYury Delendik     UpdateDebugValuesReg(Reg, NewReg, MBB, MRI);
6077c18d608SYury Delendik   } else {
6087c18d608SYury Delendik     CloneDebugValues(Reg, &*Insert, NewReg, MBB, MRI, TII);
609adf28177SDan Gohman   }
6100cfb5f85SDan Gohman 
611adf28177SDan Gohman   return Clone;
612adf28177SDan Gohman }
613adf28177SDan Gohman 
614adf28177SDan Gohman /// A multiple-use def in the same block with no intervening memory or register
615adf28177SDan Gohman /// dependencies; move the def down, nest it with the current instruction, and
6164fc4e42dSDan Gohman /// insert a tee to satisfy the rest of the uses. As an illustration, rewrite
6174fc4e42dSDan Gohman /// this:
618adf28177SDan Gohman ///
619adf28177SDan Gohman ///    Reg = INST ...        // Def
620adf28177SDan Gohman ///    INST ..., Reg, ...    // Insert
621adf28177SDan Gohman ///    INST ..., Reg, ...
622adf28177SDan Gohman ///    INST ..., Reg, ...
623adf28177SDan Gohman ///
624adf28177SDan Gohman /// to this:
625adf28177SDan Gohman ///
6268aa237c3SDan Gohman ///    DefReg = INST ...     // Def (to become the new Insert)
6274fc4e42dSDan Gohman ///    TeeReg, Reg = TEE_... DefReg
628adf28177SDan Gohman ///    INST ..., TeeReg, ... // Insert
6296c8f20d7SDan Gohman ///    INST ..., Reg, ...
6306c8f20d7SDan Gohman ///    INST ..., Reg, ...
631adf28177SDan Gohman ///
6328aa237c3SDan Gohman /// with DefReg and TeeReg stackified. This eliminates a get_local from the
633adf28177SDan Gohman /// resulting code.
634adf28177SDan Gohman static MachineInstr *MoveAndTeeForMultiUse(
635adf28177SDan Gohman     unsigned Reg, MachineOperand &Op, MachineInstr *Def, MachineBasicBlock &MBB,
636adf28177SDan Gohman     MachineInstr *Insert, LiveIntervals &LIS, WebAssemblyFunctionInfo &MFI,
637adf28177SDan Gohman     MachineRegisterInfo &MRI, const WebAssemblyInstrInfo *TII) {
638d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Move and tee for multi-use:"; Def->dump());
6392644d74bSDan Gohman 
64012de0b91SDan Gohman   // Move Def into place.
641adf28177SDan Gohman   MBB.splice(Insert, &MBB, Def);
6421afd1e2bSJF Bastien   LIS.handleMove(*Def);
64312de0b91SDan Gohman 
64412de0b91SDan Gohman   // Create the Tee and attach the registers.
645adf28177SDan Gohman   const auto *RegClass = MRI.getRegClass(Reg);
646adf28177SDan Gohman   unsigned TeeReg = MRI.createVirtualRegister(RegClass);
6478aa237c3SDan Gohman   unsigned DefReg = MRI.createVirtualRegister(RegClass);
64833e694a8SDan Gohman   MachineOperand &DefMO = Def->getOperand(0);
649adf28177SDan Gohman   MachineInstr *Tee = BuildMI(MBB, Insert, Insert->getDebugLoc(),
6504fc4e42dSDan Gohman                               TII->get(GetTeeOpcode(RegClass)), TeeReg)
65112de0b91SDan Gohman                           .addReg(Reg, RegState::Define)
65233e694a8SDan Gohman                           .addReg(DefReg, getUndefRegState(DefMO.isDead()));
653adf28177SDan Gohman   Op.setReg(TeeReg);
65433e694a8SDan Gohman   DefMO.setReg(DefReg);
65512de0b91SDan Gohman   SlotIndex TeeIdx = LIS.InsertMachineInstrInMaps(*Tee).getRegSlot();
65612de0b91SDan Gohman   SlotIndex DefIdx = LIS.getInstructionIndex(*Def).getRegSlot();
65712de0b91SDan Gohman 
6587c18d608SYury Delendik   MoveDebugValues(Reg, Insert, MBB, MRI);
6597c18d608SYury Delendik 
66012de0b91SDan Gohman   // Tell LiveIntervals we moved the original vreg def from Def to Tee.
66112de0b91SDan Gohman   LiveInterval &LI = LIS.getInterval(Reg);
66212de0b91SDan Gohman   LiveInterval::iterator I = LI.FindSegmentContaining(DefIdx);
66312de0b91SDan Gohman   VNInfo *ValNo = LI.getVNInfoAt(DefIdx);
66412de0b91SDan Gohman   I->start = TeeIdx;
66512de0b91SDan Gohman   ValNo->def = TeeIdx;
66612de0b91SDan Gohman   ShrinkToUses(LI, LIS);
66712de0b91SDan Gohman 
66812de0b91SDan Gohman   // Finish stackifying the new regs.
669adf28177SDan Gohman   LIS.createAndComputeVirtRegInterval(TeeReg);
6708aa237c3SDan Gohman   LIS.createAndComputeVirtRegInterval(DefReg);
6718aa237c3SDan Gohman   MFI.stackifyVReg(DefReg);
672adf28177SDan Gohman   MFI.stackifyVReg(TeeReg);
673adf28177SDan Gohman   ImposeStackOrdering(Def);
674adf28177SDan Gohman   ImposeStackOrdering(Tee);
67512de0b91SDan Gohman 
6767c18d608SYury Delendik   CloneDebugValues(Reg, Tee, DefReg, MBB, MRI, TII);
6777c18d608SYury Delendik   CloneDebugValues(Reg, Insert, TeeReg, MBB, MRI, TII);
6787c18d608SYury Delendik 
679d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << " - Replaced register: "; Def->dump());
680d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << " - Tee instruction: "; Tee->dump());
681adf28177SDan Gohman   return Def;
682adf28177SDan Gohman }
683adf28177SDan Gohman 
684adf28177SDan Gohman namespace {
685adf28177SDan Gohman /// A stack for walking the tree of instructions being built, visiting the
686adf28177SDan Gohman /// MachineOperands in DFS order.
687adf28177SDan Gohman class TreeWalkerState {
688adf28177SDan Gohman   typedef MachineInstr::mop_iterator mop_iterator;
689adf28177SDan Gohman   typedef std::reverse_iterator<mop_iterator> mop_reverse_iterator;
690adf28177SDan Gohman   typedef iterator_range<mop_reverse_iterator> RangeTy;
691adf28177SDan Gohman   SmallVector<RangeTy, 4> Worklist;
692adf28177SDan Gohman 
693adf28177SDan Gohman public:
694adf28177SDan Gohman   explicit TreeWalkerState(MachineInstr *Insert) {
695adf28177SDan Gohman     const iterator_range<mop_iterator> &Range = Insert->explicit_uses();
696adf28177SDan Gohman     if (Range.begin() != Range.end())
697adf28177SDan Gohman       Worklist.push_back(reverse(Range));
698adf28177SDan Gohman   }
699adf28177SDan Gohman 
700adf28177SDan Gohman   bool Done() const { return Worklist.empty(); }
701adf28177SDan Gohman 
702adf28177SDan Gohman   MachineOperand &Pop() {
703adf28177SDan Gohman     RangeTy &Range = Worklist.back();
704adf28177SDan Gohman     MachineOperand &Op = *Range.begin();
705adf28177SDan Gohman     Range = drop_begin(Range, 1);
706adf28177SDan Gohman     if (Range.begin() == Range.end())
707adf28177SDan Gohman       Worklist.pop_back();
708adf28177SDan Gohman     assert((Worklist.empty() ||
709adf28177SDan Gohman             Worklist.back().begin() != Worklist.back().end()) &&
710adf28177SDan Gohman            "Empty ranges shouldn't remain in the worklist");
711adf28177SDan Gohman     return Op;
712adf28177SDan Gohman   }
713adf28177SDan Gohman 
714adf28177SDan Gohman   /// Push Instr's operands onto the stack to be visited.
715adf28177SDan Gohman   void PushOperands(MachineInstr *Instr) {
716adf28177SDan Gohman     const iterator_range<mop_iterator> &Range(Instr->explicit_uses());
717adf28177SDan Gohman     if (Range.begin() != Range.end())
718adf28177SDan Gohman       Worklist.push_back(reverse(Range));
719adf28177SDan Gohman   }
720adf28177SDan Gohman 
721adf28177SDan Gohman   /// Some of Instr's operands are on the top of the stack; remove them and
722adf28177SDan Gohman   /// re-insert them starting from the beginning (because we've commuted them).
723adf28177SDan Gohman   void ResetTopOperands(MachineInstr *Instr) {
724adf28177SDan Gohman     assert(HasRemainingOperands(Instr) &&
725adf28177SDan Gohman            "Reseting operands should only be done when the instruction has "
726adf28177SDan Gohman            "an operand still on the stack");
727adf28177SDan Gohman     Worklist.back() = reverse(Instr->explicit_uses());
728adf28177SDan Gohman   }
729adf28177SDan Gohman 
730adf28177SDan Gohman   /// Test whether Instr has operands remaining to be visited at the top of
731adf28177SDan Gohman   /// the stack.
732adf28177SDan Gohman   bool HasRemainingOperands(const MachineInstr *Instr) const {
733adf28177SDan Gohman     if (Worklist.empty())
734adf28177SDan Gohman       return false;
735adf28177SDan Gohman     const RangeTy &Range = Worklist.back();
736adf28177SDan Gohman     return Range.begin() != Range.end() && Range.begin()->getParent() == Instr;
737adf28177SDan Gohman   }
738fbfe5ec4SDan Gohman 
739fbfe5ec4SDan Gohman   /// Test whether the given register is present on the stack, indicating an
740fbfe5ec4SDan Gohman   /// operand in the tree that we haven't visited yet. Moving a definition of
741fbfe5ec4SDan Gohman   /// Reg to a point in the tree after that would change its value.
7421054570aSDan Gohman   ///
7431054570aSDan Gohman   /// This is needed as a consequence of using implicit get_locals for
7441054570aSDan Gohman   /// uses and implicit set_locals for defs.
745fbfe5ec4SDan Gohman   bool IsOnStack(unsigned Reg) const {
746fbfe5ec4SDan Gohman     for (const RangeTy &Range : Worklist)
747fbfe5ec4SDan Gohman       for (const MachineOperand &MO : Range)
748fbfe5ec4SDan Gohman         if (MO.isReg() && MO.getReg() == Reg)
749fbfe5ec4SDan Gohman           return true;
750fbfe5ec4SDan Gohman     return false;
751fbfe5ec4SDan Gohman   }
752adf28177SDan Gohman };
753adf28177SDan Gohman 
754adf28177SDan Gohman /// State to keep track of whether commuting is in flight or whether it's been
755adf28177SDan Gohman /// tried for the current instruction and didn't work.
756adf28177SDan Gohman class CommutingState {
757adf28177SDan Gohman   /// There are effectively three states: the initial state where we haven't
758adf28177SDan Gohman   /// started commuting anything and we don't know anything yet, the tenative
759adf28177SDan Gohman   /// state where we've commuted the operands of the current instruction and are
760adf28177SDan Gohman   /// revisting it, and the declined state where we've reverted the operands
761adf28177SDan Gohman   /// back to their original order and will no longer commute it further.
762adf28177SDan Gohman   bool TentativelyCommuting;
763adf28177SDan Gohman   bool Declined;
764adf28177SDan Gohman 
765adf28177SDan Gohman   /// During the tentative state, these hold the operand indices of the commuted
766adf28177SDan Gohman   /// operands.
767adf28177SDan Gohman   unsigned Operand0, Operand1;
768adf28177SDan Gohman 
769adf28177SDan Gohman public:
770adf28177SDan Gohman   CommutingState() : TentativelyCommuting(false), Declined(false) {}
771adf28177SDan Gohman 
772adf28177SDan Gohman   /// Stackification for an operand was not successful due to ordering
773adf28177SDan Gohman   /// constraints. If possible, and if we haven't already tried it and declined
774adf28177SDan Gohman   /// it, commute Insert's operands and prepare to revisit it.
775adf28177SDan Gohman   void MaybeCommute(MachineInstr *Insert, TreeWalkerState &TreeWalker,
776adf28177SDan Gohman                     const WebAssemblyInstrInfo *TII) {
777adf28177SDan Gohman     if (TentativelyCommuting) {
778adf28177SDan Gohman       assert(!Declined &&
779adf28177SDan Gohman              "Don't decline commuting until you've finished trying it");
780adf28177SDan Gohman       // Commuting didn't help. Revert it.
7819cfc75c2SDuncan P. N. Exon Smith       TII->commuteInstruction(*Insert, /*NewMI=*/false, Operand0, Operand1);
782adf28177SDan Gohman       TentativelyCommuting = false;
783adf28177SDan Gohman       Declined = true;
784adf28177SDan Gohman     } else if (!Declined && TreeWalker.HasRemainingOperands(Insert)) {
785adf28177SDan Gohman       Operand0 = TargetInstrInfo::CommuteAnyOperandIndex;
786adf28177SDan Gohman       Operand1 = TargetInstrInfo::CommuteAnyOperandIndex;
7879cfc75c2SDuncan P. N. Exon Smith       if (TII->findCommutedOpIndices(*Insert, Operand0, Operand1)) {
788adf28177SDan Gohman         // Tentatively commute the operands and try again.
7899cfc75c2SDuncan P. N. Exon Smith         TII->commuteInstruction(*Insert, /*NewMI=*/false, Operand0, Operand1);
790adf28177SDan Gohman         TreeWalker.ResetTopOperands(Insert);
791adf28177SDan Gohman         TentativelyCommuting = true;
792adf28177SDan Gohman         Declined = false;
793adf28177SDan Gohman       }
794adf28177SDan Gohman     }
795adf28177SDan Gohman   }
796adf28177SDan Gohman 
797adf28177SDan Gohman   /// Stackification for some operand was successful. Reset to the default
798adf28177SDan Gohman   /// state.
799adf28177SDan Gohman   void Reset() {
800adf28177SDan Gohman     TentativelyCommuting = false;
801adf28177SDan Gohman     Declined = false;
802adf28177SDan Gohman   }
803adf28177SDan Gohman };
804adf28177SDan Gohman } // end anonymous namespace
805adf28177SDan Gohman 
8061462faadSDan Gohman bool WebAssemblyRegStackify::runOnMachineFunction(MachineFunction &MF) {
807d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "********** Register Stackifying **********\n"
8081462faadSDan Gohman                        "********** Function: "
8091462faadSDan Gohman                     << MF.getName() << '\n');
8101462faadSDan Gohman 
8111462faadSDan Gohman   bool Changed = false;
8121462faadSDan Gohman   MachineRegisterInfo &MRI = MF.getRegInfo();
8131462faadSDan Gohman   WebAssemblyFunctionInfo &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
814b6fd39a3SDan Gohman   const auto *TII = MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
815b6fd39a3SDan Gohman   const auto *TRI = MF.getSubtarget<WebAssemblySubtarget>().getRegisterInfo();
81681719f85SDan Gohman   AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
817adf28177SDan Gohman   MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
8188887d1faSDan Gohman   LiveIntervals &LIS = getAnalysis<LiveIntervals>();
819d70e5907SDan Gohman 
8201462faadSDan Gohman   // Walk the instructions from the bottom up. Currently we don't look past
8211462faadSDan Gohman   // block boundaries, and the blocks aren't ordered so the block visitation
8221462faadSDan Gohman   // order isn't significant, but we may want to change this in the future.
8231462faadSDan Gohman   for (MachineBasicBlock &MBB : MF) {
8248f59cf75SDan Gohman     // Don't use a range-based for loop, because we modify the list as we're
8258f59cf75SDan Gohman     // iterating over it and the end iterator may change.
8268f59cf75SDan Gohman     for (auto MII = MBB.rbegin(); MII != MBB.rend(); ++MII) {
8278f59cf75SDan Gohman       MachineInstr *Insert = &*MII;
82881719f85SDan Gohman       // Don't nest anything inside an inline asm, because we don't have
82981719f85SDan Gohman       // constraints for $push inputs.
83081719f85SDan Gohman       if (Insert->getOpcode() == TargetOpcode::INLINEASM)
831595e8ab2SDan Gohman         continue;
832595e8ab2SDan Gohman 
833595e8ab2SDan Gohman       // Ignore debugging intrinsics.
834595e8ab2SDan Gohman       if (Insert->getOpcode() == TargetOpcode::DBG_VALUE)
835595e8ab2SDan Gohman         continue;
83681719f85SDan Gohman 
8371462faadSDan Gohman       // Iterate through the inputs in reverse order, since we'll be pulling
83853d13997SDan Gohman       // operands off the stack in LIFO order.
839adf28177SDan Gohman       CommutingState Commuting;
840adf28177SDan Gohman       TreeWalkerState TreeWalker(Insert);
841adf28177SDan Gohman       while (!TreeWalker.Done()) {
842adf28177SDan Gohman         MachineOperand &Op = TreeWalker.Pop();
843adf28177SDan Gohman 
8441462faadSDan Gohman         // We're only interested in explicit virtual register operands.
845adf28177SDan Gohman         if (!Op.isReg())
8461462faadSDan Gohman           continue;
8471462faadSDan Gohman 
8481462faadSDan Gohman         unsigned Reg = Op.getReg();
849adf28177SDan Gohman         assert(Op.isUse() && "explicit_uses() should only iterate over uses");
850adf28177SDan Gohman         assert(!Op.isImplicit() &&
851adf28177SDan Gohman                "explicit_uses() should only iterate over explicit operands");
852adf28177SDan Gohman         if (TargetRegisterInfo::isPhysicalRegister(Reg))
853adf28177SDan Gohman           continue;
8541462faadSDan Gohman 
855ffc184bbSDan Gohman         // Identify the definition for this register at this point.
8562644d74bSDan Gohman         MachineInstr *Def = GetVRegDef(Reg, Insert, MRI, LIS);
8571462faadSDan Gohman         if (!Def)
8581462faadSDan Gohman           continue;
8591462faadSDan Gohman 
86081719f85SDan Gohman         // Don't nest an INLINE_ASM def into anything, because we don't have
86181719f85SDan Gohman         // constraints for $pop outputs.
86281719f85SDan Gohman         if (Def->getOpcode() == TargetOpcode::INLINEASM)
86381719f85SDan Gohman           continue;
86481719f85SDan Gohman 
8654ba4816bSDan Gohman         // Argument instructions represent live-in registers and not real
8664ba4816bSDan Gohman         // instructions.
8674fc4e42dSDan Gohman         if (WebAssembly::isArgument(*Def))
8684ba4816bSDan Gohman           continue;
8694ba4816bSDan Gohman 
870adf28177SDan Gohman         // Decide which strategy to take. Prefer to move a single-use value
8714fc4e42dSDan Gohman         // over cloning it, and prefer cloning over introducing a tee.
872adf28177SDan Gohman         // For moving, we require the def to be in the same block as the use;
873adf28177SDan Gohman         // this makes things simpler (LiveIntervals' handleMove function only
874adf28177SDan Gohman         // supports intra-block moves) and it's MachineSink's job to catch all
875adf28177SDan Gohman         // the sinking opportunities anyway.
876adf28177SDan Gohman         bool SameBlock = Def->getParent() == &MBB;
877e9e6891bSDerek Schuff         bool CanMove = SameBlock && IsSafeToMove(Def, Insert, AA, MRI) &&
878fbfe5ec4SDan Gohman                        !TreeWalker.IsOnStack(Reg);
87912de0b91SDan Gohman         if (CanMove && HasOneUse(Reg, Def, MRI, MDT, LIS)) {
8800cfb5f85SDan Gohman           Insert = MoveForSingleUse(Reg, Op, Def, MBB, Insert, LIS, MFI, MRI);
8819cfc75c2SDuncan P. N. Exon Smith         } else if (ShouldRematerialize(*Def, AA, TII)) {
8829cfc75c2SDuncan P. N. Exon Smith           Insert =
8839cfc75c2SDuncan P. N. Exon Smith               RematerializeCheapDef(Reg, Op, *Def, MBB, Insert->getIterator(),
8849cfc75c2SDuncan P. N. Exon Smith                                     LIS, MFI, MRI, TII, TRI);
885cf2a9e28SSam Clegg         } else if (CanMove &&
8861054570aSDan Gohman                    OneUseDominatesOtherUses(Reg, Op, MBB, MRI, MDT, LIS, MFI)) {
887adf28177SDan Gohman           Insert = MoveAndTeeForMultiUse(Reg, Op, Def, MBB, Insert, LIS, MFI,
888adf28177SDan Gohman                                          MRI, TII);
889b6fd39a3SDan Gohman         } else {
890adf28177SDan Gohman           // We failed to stackify the operand. If the problem was ordering
891adf28177SDan Gohman           // constraints, Commuting may be able to help.
892adf28177SDan Gohman           if (!CanMove && SameBlock)
893adf28177SDan Gohman             Commuting.MaybeCommute(Insert, TreeWalker, TII);
894adf28177SDan Gohman           // Proceed to the next operand.
895adf28177SDan Gohman           continue;
896b6fd39a3SDan Gohman         }
897adf28177SDan Gohman 
898e81021a5SDan Gohman         // If the instruction we just stackified is an IMPLICIT_DEF, convert it
899e81021a5SDan Gohman         // to a constant 0 so that the def is explicit, and the push/pop
900e81021a5SDan Gohman         // correspondence is maintained.
901e81021a5SDan Gohman         if (Insert->getOpcode() == TargetOpcode::IMPLICIT_DEF)
902*feb18fe9SThomas Lively           ConvertImplicitDefToConstZero(Insert, MRI, TII, MF, LIS);
903e81021a5SDan Gohman 
904adf28177SDan Gohman         // We stackified an operand. Add the defining instruction's operands to
905adf28177SDan Gohman         // the worklist stack now to continue to build an ever deeper tree.
906adf28177SDan Gohman         Commuting.Reset();
907adf28177SDan Gohman         TreeWalker.PushOperands(Insert);
908b6fd39a3SDan Gohman       }
909adf28177SDan Gohman 
910adf28177SDan Gohman       // If we stackified any operands, skip over the tree to start looking for
911adf28177SDan Gohman       // the next instruction we can build a tree on.
912adf28177SDan Gohman       if (Insert != &*MII) {
9138f59cf75SDan Gohman         ImposeStackOrdering(&*MII);
914c7e5a9ceSEric Liu         MII = MachineBasicBlock::iterator(Insert).getReverse();
915adf28177SDan Gohman         Changed = true;
916adf28177SDan Gohman       }
9171462faadSDan Gohman     }
9181462faadSDan Gohman   }
9191462faadSDan Gohman 
920e040533eSDan Gohman   // If we used VALUE_STACK anywhere, add it to the live-in sets everywhere so
921adf28177SDan Gohman   // that it never looks like a use-before-def.
922b0992dafSDan Gohman   if (Changed) {
923e040533eSDan Gohman     MF.getRegInfo().addLiveIn(WebAssembly::VALUE_STACK);
924b0992dafSDan Gohman     for (MachineBasicBlock &MBB : MF)
925e040533eSDan Gohman       MBB.addLiveIn(WebAssembly::VALUE_STACK);
926b0992dafSDan Gohman   }
927b0992dafSDan Gohman 
9287bafa0eaSDan Gohman #ifndef NDEBUG
929b6fd39a3SDan Gohman   // Verify that pushes and pops are performed in LIFO order.
9307bafa0eaSDan Gohman   SmallVector<unsigned, 0> Stack;
9317bafa0eaSDan Gohman   for (MachineBasicBlock &MBB : MF) {
9327bafa0eaSDan Gohman     for (MachineInstr &MI : MBB) {
933801bf7ebSShiva Chen       if (MI.isDebugInstr())
9340cfb5f85SDan Gohman         continue;
9357bafa0eaSDan Gohman       for (MachineOperand &MO : reverse(MI.explicit_operands())) {
9367a6b9825SDan Gohman         if (!MO.isReg())
9377a6b9825SDan Gohman           continue;
938adf28177SDan Gohman         unsigned Reg = MO.getReg();
9397bafa0eaSDan Gohman 
940adf28177SDan Gohman         if (MFI.isVRegStackified(Reg)) {
9417bafa0eaSDan Gohman           if (MO.isDef())
942adf28177SDan Gohman             Stack.push_back(Reg);
9437bafa0eaSDan Gohman           else
944adf28177SDan Gohman             assert(Stack.pop_back_val() == Reg &&
945adf28177SDan Gohman                    "Register stack pop should be paired with a push");
9467bafa0eaSDan Gohman         }
9477bafa0eaSDan Gohman       }
9487bafa0eaSDan Gohman     }
9497bafa0eaSDan Gohman     // TODO: Generalize this code to support keeping values on the stack across
9507bafa0eaSDan Gohman     // basic block boundaries.
951adf28177SDan Gohman     assert(Stack.empty() &&
952adf28177SDan Gohman            "Register stack pushes and pops should be balanced");
9537bafa0eaSDan Gohman   }
9547bafa0eaSDan Gohman #endif
9557bafa0eaSDan Gohman 
9561462faadSDan Gohman   return Changed;
9571462faadSDan Gohman }
958