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
117d523365SDimitry Andric /// \brief 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"
257d523365SDimitry Andric #include "WebAssemblyMachineFunctionInfo.h"
263ca95b02SDimitry Andric #include "WebAssemblySubtarget.h"
27d88c1a5aSDimitry Andric #include "WebAssemblyUtilities.h"
287d523365SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
297d523365SDimitry Andric #include "llvm/CodeGen/LiveIntervalAnalysis.h"
307d523365SDimitry Andric #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
313ca95b02SDimitry Andric #include "llvm/CodeGen/MachineDominators.h"
323ca95b02SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
337a7e6055SDimitry Andric #include "llvm/CodeGen/MachineModuleInfoImpls.h"
347d523365SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
357d523365SDimitry Andric #include "llvm/CodeGen/Passes.h"
367d523365SDimitry Andric #include "llvm/Support/Debug.h"
377d523365SDimitry Andric #include "llvm/Support/raw_ostream.h"
387d523365SDimitry Andric using namespace llvm;
397d523365SDimitry Andric 
407d523365SDimitry Andric #define DEBUG_TYPE "wasm-reg-stackify"
417d523365SDimitry Andric 
427d523365SDimitry Andric namespace {
437d523365SDimitry Andric class WebAssemblyRegStackify final : public MachineFunctionPass {
44d88c1a5aSDimitry Andric   StringRef getPassName() const override {
457d523365SDimitry Andric     return "WebAssembly Register Stackify";
467d523365SDimitry Andric   }
477d523365SDimitry Andric 
487d523365SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
497d523365SDimitry Andric     AU.setPreservesCFG();
507d523365SDimitry Andric     AU.addRequired<AAResultsWrapperPass>();
513ca95b02SDimitry Andric     AU.addRequired<MachineDominatorTree>();
527d523365SDimitry Andric     AU.addRequired<LiveIntervals>();
537d523365SDimitry Andric     AU.addPreserved<MachineBlockFrequencyInfo>();
547d523365SDimitry Andric     AU.addPreserved<SlotIndexes>();
557d523365SDimitry Andric     AU.addPreserved<LiveIntervals>();
567d523365SDimitry Andric     AU.addPreservedID(LiveVariablesID);
573ca95b02SDimitry Andric     AU.addPreserved<MachineDominatorTree>();
587d523365SDimitry Andric     MachineFunctionPass::getAnalysisUsage(AU);
597d523365SDimitry Andric   }
607d523365SDimitry Andric 
617d523365SDimitry Andric   bool runOnMachineFunction(MachineFunction &MF) override;
627d523365SDimitry Andric 
637d523365SDimitry Andric public:
647d523365SDimitry Andric   static char ID; // Pass identification, replacement for typeid
657d523365SDimitry Andric   WebAssemblyRegStackify() : MachineFunctionPass(ID) {}
667d523365SDimitry Andric };
677d523365SDimitry Andric } // end anonymous namespace
687d523365SDimitry Andric 
697d523365SDimitry Andric char WebAssemblyRegStackify::ID = 0;
707d523365SDimitry Andric FunctionPass *llvm::createWebAssemblyRegStackify() {
717d523365SDimitry Andric   return new WebAssemblyRegStackify();
727d523365SDimitry Andric }
737d523365SDimitry Andric 
747d523365SDimitry Andric // Decorate the given instruction with implicit operands that enforce the
757d523365SDimitry Andric // expression stack ordering constraints for an instruction which is on
767d523365SDimitry Andric // the expression stack.
777d523365SDimitry Andric static void ImposeStackOrdering(MachineInstr *MI) {
78d88c1a5aSDimitry Andric   // Write the opaque VALUE_STACK register.
79d88c1a5aSDimitry Andric   if (!MI->definesRegister(WebAssembly::VALUE_STACK))
80d88c1a5aSDimitry Andric     MI->addOperand(MachineOperand::CreateReg(WebAssembly::VALUE_STACK,
817d523365SDimitry Andric                                              /*isDef=*/true,
827d523365SDimitry Andric                                              /*isImp=*/true));
837d523365SDimitry Andric 
84d88c1a5aSDimitry Andric   // Also read the opaque VALUE_STACK register.
85d88c1a5aSDimitry Andric   if (!MI->readsRegister(WebAssembly::VALUE_STACK))
86d88c1a5aSDimitry Andric     MI->addOperand(MachineOperand::CreateReg(WebAssembly::VALUE_STACK,
877d523365SDimitry Andric                                              /*isDef=*/false,
887d523365SDimitry Andric                                              /*isImp=*/true));
897d523365SDimitry Andric }
907d523365SDimitry Andric 
91d88c1a5aSDimitry Andric // Convert an IMPLICIT_DEF instruction into an instruction which defines
92d88c1a5aSDimitry Andric // a constant zero value.
93d88c1a5aSDimitry Andric static void ConvertImplicitDefToConstZero(MachineInstr *MI,
94d88c1a5aSDimitry Andric                                           MachineRegisterInfo &MRI,
95d88c1a5aSDimitry Andric                                           const TargetInstrInfo *TII,
96d88c1a5aSDimitry Andric                                           MachineFunction &MF) {
97d88c1a5aSDimitry Andric   assert(MI->getOpcode() == TargetOpcode::IMPLICIT_DEF);
98d88c1a5aSDimitry Andric 
99d88c1a5aSDimitry Andric   const auto *RegClass =
100d88c1a5aSDimitry Andric       MRI.getRegClass(MI->getOperand(0).getReg());
101d88c1a5aSDimitry Andric   if (RegClass == &WebAssembly::I32RegClass) {
102d88c1a5aSDimitry Andric     MI->setDesc(TII->get(WebAssembly::CONST_I32));
103d88c1a5aSDimitry Andric     MI->addOperand(MachineOperand::CreateImm(0));
104d88c1a5aSDimitry Andric   } else if (RegClass == &WebAssembly::I64RegClass) {
105d88c1a5aSDimitry Andric     MI->setDesc(TII->get(WebAssembly::CONST_I64));
106d88c1a5aSDimitry Andric     MI->addOperand(MachineOperand::CreateImm(0));
107d88c1a5aSDimitry Andric   } else if (RegClass == &WebAssembly::F32RegClass) {
108d88c1a5aSDimitry Andric     MI->setDesc(TII->get(WebAssembly::CONST_F32));
109d88c1a5aSDimitry Andric     ConstantFP *Val = cast<ConstantFP>(Constant::getNullValue(
110d88c1a5aSDimitry Andric         Type::getFloatTy(MF.getFunction()->getContext())));
111d88c1a5aSDimitry Andric     MI->addOperand(MachineOperand::CreateFPImm(Val));
112d88c1a5aSDimitry Andric   } else if (RegClass == &WebAssembly::F64RegClass) {
113d88c1a5aSDimitry Andric     MI->setDesc(TII->get(WebAssembly::CONST_F64));
114d88c1a5aSDimitry Andric     ConstantFP *Val = cast<ConstantFP>(Constant::getNullValue(
115d88c1a5aSDimitry Andric         Type::getDoubleTy(MF.getFunction()->getContext())));
116d88c1a5aSDimitry Andric     MI->addOperand(MachineOperand::CreateFPImm(Val));
117d88c1a5aSDimitry Andric   } else {
118d88c1a5aSDimitry Andric     llvm_unreachable("Unexpected reg class");
119d88c1a5aSDimitry Andric   }
120d88c1a5aSDimitry Andric }
121d88c1a5aSDimitry Andric 
1223ca95b02SDimitry Andric // Determine whether a call to the callee referenced by
1233ca95b02SDimitry Andric // MI->getOperand(CalleeOpNo) reads memory, writes memory, and/or has side
1243ca95b02SDimitry Andric // effects.
1253ca95b02SDimitry Andric static void QueryCallee(const MachineInstr &MI, unsigned CalleeOpNo, bool &Read,
1263ca95b02SDimitry Andric                         bool &Write, bool &Effects, bool &StackPointer) {
1273ca95b02SDimitry Andric   // All calls can use the stack pointer.
1283ca95b02SDimitry Andric   StackPointer = true;
1293ca95b02SDimitry Andric 
1303ca95b02SDimitry Andric   const MachineOperand &MO = MI.getOperand(CalleeOpNo);
1313ca95b02SDimitry Andric   if (MO.isGlobal()) {
1323ca95b02SDimitry Andric     const Constant *GV = MO.getGlobal();
1333ca95b02SDimitry Andric     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
1343ca95b02SDimitry Andric       if (!GA->isInterposable())
1353ca95b02SDimitry Andric         GV = GA->getAliasee();
1363ca95b02SDimitry Andric 
1373ca95b02SDimitry Andric     if (const Function *F = dyn_cast<Function>(GV)) {
1383ca95b02SDimitry Andric       if (!F->doesNotThrow())
1393ca95b02SDimitry Andric         Effects = true;
1403ca95b02SDimitry Andric       if (F->doesNotAccessMemory())
1413ca95b02SDimitry Andric         return;
1423ca95b02SDimitry Andric       if (F->onlyReadsMemory()) {
1433ca95b02SDimitry Andric         Read = true;
1443ca95b02SDimitry Andric         return;
1453ca95b02SDimitry Andric       }
1463ca95b02SDimitry Andric     }
1473ca95b02SDimitry Andric   }
1483ca95b02SDimitry Andric 
1493ca95b02SDimitry Andric   // Assume the worst.
1503ca95b02SDimitry Andric   Write = true;
1513ca95b02SDimitry Andric   Read = true;
1523ca95b02SDimitry Andric   Effects = true;
1533ca95b02SDimitry Andric }
1543ca95b02SDimitry Andric 
1553ca95b02SDimitry Andric // Determine whether MI reads memory, writes memory, has side effects,
1567a7e6055SDimitry Andric // and/or uses the stack pointer value.
1573ca95b02SDimitry Andric static void Query(const MachineInstr &MI, AliasAnalysis &AA, bool &Read,
1583ca95b02SDimitry Andric                   bool &Write, bool &Effects, bool &StackPointer) {
1593ca95b02SDimitry Andric   assert(!MI.isPosition());
1603ca95b02SDimitry Andric   assert(!MI.isTerminator());
1613ca95b02SDimitry Andric 
1623ca95b02SDimitry Andric   if (MI.isDebugValue())
1633ca95b02SDimitry Andric     return;
1643ca95b02SDimitry Andric 
1653ca95b02SDimitry Andric   // Check for loads.
166d88c1a5aSDimitry Andric   if (MI.mayLoad() && !MI.isDereferenceableInvariantLoad(&AA))
1673ca95b02SDimitry Andric     Read = true;
1683ca95b02SDimitry Andric 
1693ca95b02SDimitry Andric   // Check for stores.
1703ca95b02SDimitry Andric   if (MI.mayStore()) {
1713ca95b02SDimitry Andric     Write = true;
1723ca95b02SDimitry Andric 
1733ca95b02SDimitry Andric     // Check for stores to __stack_pointer.
1743ca95b02SDimitry Andric     for (auto MMO : MI.memoperands()) {
1753ca95b02SDimitry Andric       const MachinePointerInfo &MPI = MMO->getPointerInfo();
1763ca95b02SDimitry Andric       if (MPI.V.is<const PseudoSourceValue *>()) {
1773ca95b02SDimitry Andric         auto PSV = MPI.V.get<const PseudoSourceValue *>();
1783ca95b02SDimitry Andric         if (const ExternalSymbolPseudoSourceValue *EPSV =
1793ca95b02SDimitry Andric                 dyn_cast<ExternalSymbolPseudoSourceValue>(PSV))
180edd7eaddSDimitry Andric           if (StringRef(EPSV->getSymbol()) == "__stack_pointer") {
1813ca95b02SDimitry Andric             StackPointer = true;
1823ca95b02SDimitry Andric           }
1833ca95b02SDimitry Andric       }
1847a7e6055SDimitry Andric     }
1853ca95b02SDimitry Andric   } else if (MI.hasOrderedMemoryRef()) {
1863ca95b02SDimitry Andric     switch (MI.getOpcode()) {
1873ca95b02SDimitry Andric     case WebAssembly::DIV_S_I32: case WebAssembly::DIV_S_I64:
1883ca95b02SDimitry Andric     case WebAssembly::REM_S_I32: case WebAssembly::REM_S_I64:
1893ca95b02SDimitry Andric     case WebAssembly::DIV_U_I32: case WebAssembly::DIV_U_I64:
1903ca95b02SDimitry Andric     case WebAssembly::REM_U_I32: case WebAssembly::REM_U_I64:
1913ca95b02SDimitry Andric     case WebAssembly::I32_TRUNC_S_F32: case WebAssembly::I64_TRUNC_S_F32:
1923ca95b02SDimitry Andric     case WebAssembly::I32_TRUNC_S_F64: case WebAssembly::I64_TRUNC_S_F64:
1933ca95b02SDimitry Andric     case WebAssembly::I32_TRUNC_U_F32: case WebAssembly::I64_TRUNC_U_F32:
1943ca95b02SDimitry Andric     case WebAssembly::I32_TRUNC_U_F64: case WebAssembly::I64_TRUNC_U_F64:
1953ca95b02SDimitry Andric       // These instruction have hasUnmodeledSideEffects() returning true
1963ca95b02SDimitry Andric       // because they trap on overflow and invalid so they can't be arbitrarily
1973ca95b02SDimitry Andric       // moved, however hasOrderedMemoryRef() interprets this plus their lack
1983ca95b02SDimitry Andric       // of memoperands as having a potential unknown memory reference.
1993ca95b02SDimitry Andric       break;
2003ca95b02SDimitry Andric     default:
2013ca95b02SDimitry Andric       // Record volatile accesses, unless it's a call, as calls are handled
2023ca95b02SDimitry Andric       // specially below.
2033ca95b02SDimitry Andric       if (!MI.isCall()) {
2043ca95b02SDimitry Andric         Write = true;
2053ca95b02SDimitry Andric         Effects = true;
2063ca95b02SDimitry Andric       }
2073ca95b02SDimitry Andric       break;
2083ca95b02SDimitry Andric     }
2093ca95b02SDimitry Andric   }
2103ca95b02SDimitry Andric 
2113ca95b02SDimitry Andric   // Check for side effects.
2123ca95b02SDimitry Andric   if (MI.hasUnmodeledSideEffects()) {
2133ca95b02SDimitry Andric     switch (MI.getOpcode()) {
2143ca95b02SDimitry Andric     case WebAssembly::DIV_S_I32: case WebAssembly::DIV_S_I64:
2153ca95b02SDimitry Andric     case WebAssembly::REM_S_I32: case WebAssembly::REM_S_I64:
2163ca95b02SDimitry Andric     case WebAssembly::DIV_U_I32: case WebAssembly::DIV_U_I64:
2173ca95b02SDimitry Andric     case WebAssembly::REM_U_I32: case WebAssembly::REM_U_I64:
2183ca95b02SDimitry Andric     case WebAssembly::I32_TRUNC_S_F32: case WebAssembly::I64_TRUNC_S_F32:
2193ca95b02SDimitry Andric     case WebAssembly::I32_TRUNC_S_F64: case WebAssembly::I64_TRUNC_S_F64:
2203ca95b02SDimitry Andric     case WebAssembly::I32_TRUNC_U_F32: case WebAssembly::I64_TRUNC_U_F32:
2213ca95b02SDimitry Andric     case WebAssembly::I32_TRUNC_U_F64: case WebAssembly::I64_TRUNC_U_F64:
2223ca95b02SDimitry Andric       // These instructions have hasUnmodeledSideEffects() returning true
2233ca95b02SDimitry Andric       // because they trap on overflow and invalid so they can't be arbitrarily
2243ca95b02SDimitry Andric       // moved, however in the specific case of register stackifying, it is safe
2253ca95b02SDimitry Andric       // to move them because overflow and invalid are Undefined Behavior.
2263ca95b02SDimitry Andric       break;
2273ca95b02SDimitry Andric     default:
2283ca95b02SDimitry Andric       Effects = true;
2293ca95b02SDimitry Andric       break;
2303ca95b02SDimitry Andric     }
2313ca95b02SDimitry Andric   }
2323ca95b02SDimitry Andric 
2333ca95b02SDimitry Andric   // Analyze calls.
2343ca95b02SDimitry Andric   if (MI.isCall()) {
2353ca95b02SDimitry Andric     switch (MI.getOpcode()) {
2363ca95b02SDimitry Andric     case WebAssembly::CALL_VOID:
2373ca95b02SDimitry Andric     case WebAssembly::CALL_INDIRECT_VOID:
2383ca95b02SDimitry Andric       QueryCallee(MI, 0, Read, Write, Effects, StackPointer);
2393ca95b02SDimitry Andric       break;
2403ca95b02SDimitry Andric     case WebAssembly::CALL_I32: case WebAssembly::CALL_I64:
2413ca95b02SDimitry Andric     case WebAssembly::CALL_F32: case WebAssembly::CALL_F64:
2423ca95b02SDimitry Andric     case WebAssembly::CALL_INDIRECT_I32: case WebAssembly::CALL_INDIRECT_I64:
2433ca95b02SDimitry Andric     case WebAssembly::CALL_INDIRECT_F32: case WebAssembly::CALL_INDIRECT_F64:
2443ca95b02SDimitry Andric       QueryCallee(MI, 1, Read, Write, Effects, StackPointer);
2453ca95b02SDimitry Andric       break;
2463ca95b02SDimitry Andric     default:
2473ca95b02SDimitry Andric       llvm_unreachable("unexpected call opcode");
2483ca95b02SDimitry Andric     }
2493ca95b02SDimitry Andric   }
2503ca95b02SDimitry Andric }
2513ca95b02SDimitry Andric 
2523ca95b02SDimitry Andric // Test whether Def is safe and profitable to rematerialize.
2533ca95b02SDimitry Andric static bool ShouldRematerialize(const MachineInstr &Def, AliasAnalysis &AA,
2543ca95b02SDimitry Andric                                 const WebAssemblyInstrInfo *TII) {
2553ca95b02SDimitry Andric   return Def.isAsCheapAsAMove() && TII->isTriviallyReMaterializable(Def, &AA);
2563ca95b02SDimitry Andric }
2573ca95b02SDimitry Andric 
2583ca95b02SDimitry Andric // Identify the definition for this register at this point. This is a
2593ca95b02SDimitry Andric // generalization of MachineRegisterInfo::getUniqueVRegDef that uses
2603ca95b02SDimitry Andric // LiveIntervals to handle complex cases.
2613ca95b02SDimitry Andric static MachineInstr *GetVRegDef(unsigned Reg, const MachineInstr *Insert,
2623ca95b02SDimitry Andric                                 const MachineRegisterInfo &MRI,
2633ca95b02SDimitry Andric                                 const LiveIntervals &LIS)
2643ca95b02SDimitry Andric {
2653ca95b02SDimitry Andric   // Most registers are in SSA form here so we try a quick MRI query first.
2663ca95b02SDimitry Andric   if (MachineInstr *Def = MRI.getUniqueVRegDef(Reg))
2673ca95b02SDimitry Andric     return Def;
2683ca95b02SDimitry Andric 
2693ca95b02SDimitry Andric   // MRI doesn't know what the Def is. Try asking LIS.
2703ca95b02SDimitry Andric   if (const VNInfo *ValNo = LIS.getInterval(Reg).getVNInfoBefore(
2713ca95b02SDimitry Andric           LIS.getInstructionIndex(*Insert)))
2723ca95b02SDimitry Andric     return LIS.getInstructionFromIndex(ValNo->def);
2733ca95b02SDimitry Andric 
2743ca95b02SDimitry Andric   return nullptr;
2753ca95b02SDimitry Andric }
2763ca95b02SDimitry Andric 
2773ca95b02SDimitry Andric // Test whether Reg, as defined at Def, has exactly one use. This is a
2783ca95b02SDimitry Andric // generalization of MachineRegisterInfo::hasOneUse that uses LiveIntervals
2793ca95b02SDimitry Andric // to handle complex cases.
2803ca95b02SDimitry Andric static bool HasOneUse(unsigned Reg, MachineInstr *Def,
2813ca95b02SDimitry Andric                       MachineRegisterInfo &MRI, MachineDominatorTree &MDT,
2823ca95b02SDimitry Andric                       LiveIntervals &LIS) {
2833ca95b02SDimitry Andric   // Most registers are in SSA form here so we try a quick MRI query first.
2843ca95b02SDimitry Andric   if (MRI.hasOneUse(Reg))
2853ca95b02SDimitry Andric     return true;
2863ca95b02SDimitry Andric 
2873ca95b02SDimitry Andric   bool HasOne = false;
2883ca95b02SDimitry Andric   const LiveInterval &LI = LIS.getInterval(Reg);
2893ca95b02SDimitry Andric   const VNInfo *DefVNI = LI.getVNInfoAt(
2903ca95b02SDimitry Andric       LIS.getInstructionIndex(*Def).getRegSlot());
2913ca95b02SDimitry Andric   assert(DefVNI);
292d88c1a5aSDimitry Andric   for (auto &I : MRI.use_nodbg_operands(Reg)) {
2933ca95b02SDimitry Andric     const auto &Result = LI.Query(LIS.getInstructionIndex(*I.getParent()));
2943ca95b02SDimitry Andric     if (Result.valueIn() == DefVNI) {
2953ca95b02SDimitry Andric       if (!Result.isKill())
2963ca95b02SDimitry Andric         return false;
2973ca95b02SDimitry Andric       if (HasOne)
2983ca95b02SDimitry Andric         return false;
2993ca95b02SDimitry Andric       HasOne = true;
3003ca95b02SDimitry Andric     }
3013ca95b02SDimitry Andric   }
3023ca95b02SDimitry Andric   return HasOne;
3033ca95b02SDimitry Andric }
3043ca95b02SDimitry Andric 
3057d523365SDimitry Andric // Test whether it's safe to move Def to just before Insert.
3067d523365SDimitry Andric // TODO: Compute memory dependencies in a way that doesn't require always
3077d523365SDimitry Andric // walking the block.
3087d523365SDimitry Andric // TODO: Compute memory dependencies in a way that uses AliasAnalysis to be
3097d523365SDimitry Andric // more precise.
3107d523365SDimitry Andric static bool IsSafeToMove(const MachineInstr *Def, const MachineInstr *Insert,
311d88c1a5aSDimitry Andric                          AliasAnalysis &AA, const MachineRegisterInfo &MRI) {
3127d523365SDimitry Andric   assert(Def->getParent() == Insert->getParent());
3137d523365SDimitry Andric 
3147d523365SDimitry Andric   // Check for register dependencies.
315d88c1a5aSDimitry Andric   SmallVector<unsigned, 4> MutableRegisters;
3167d523365SDimitry Andric   for (const MachineOperand &MO : Def->operands()) {
3177d523365SDimitry Andric     if (!MO.isReg() || MO.isUndef())
3187d523365SDimitry Andric       continue;
3197d523365SDimitry Andric     unsigned Reg = MO.getReg();
3207d523365SDimitry Andric 
3217d523365SDimitry Andric     // If the register is dead here and at Insert, ignore it.
3227d523365SDimitry Andric     if (MO.isDead() && Insert->definesRegister(Reg) &&
3237d523365SDimitry Andric         !Insert->readsRegister(Reg))
3247d523365SDimitry Andric       continue;
3257d523365SDimitry Andric 
3267d523365SDimitry Andric     if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
3273ca95b02SDimitry Andric       // Ignore ARGUMENTS; it's just used to keep the ARGUMENT_* instructions
3283ca95b02SDimitry Andric       // from moving down, and we've already checked for that.
3293ca95b02SDimitry Andric       if (Reg == WebAssembly::ARGUMENTS)
3303ca95b02SDimitry Andric         continue;
3317d523365SDimitry Andric       // If the physical register is never modified, ignore it.
3327d523365SDimitry Andric       if (!MRI.isPhysRegModified(Reg))
3337d523365SDimitry Andric         continue;
3347d523365SDimitry Andric       // Otherwise, it's a physical register with unknown liveness.
3357d523365SDimitry Andric       return false;
3367d523365SDimitry Andric     }
3377d523365SDimitry Andric 
338d88c1a5aSDimitry Andric     // If one of the operands isn't in SSA form, it has different values at
339d88c1a5aSDimitry Andric     // different times, and we need to make sure we don't move our use across
340d88c1a5aSDimitry Andric     // a different def.
341d88c1a5aSDimitry Andric     if (!MO.isDef() && !MRI.hasOneDef(Reg))
342d88c1a5aSDimitry Andric       MutableRegisters.push_back(Reg);
3437d523365SDimitry Andric   }
3447d523365SDimitry Andric 
3453ca95b02SDimitry Andric   bool Read = false, Write = false, Effects = false, StackPointer = false;
3463ca95b02SDimitry Andric   Query(*Def, AA, Read, Write, Effects, StackPointer);
3473ca95b02SDimitry Andric 
3483ca95b02SDimitry Andric   // If the instruction does not access memory and has no side effects, it has
3493ca95b02SDimitry Andric   // no additional dependencies.
350d88c1a5aSDimitry Andric   bool HasMutableRegisters = !MutableRegisters.empty();
351d88c1a5aSDimitry Andric   if (!Read && !Write && !Effects && !StackPointer && !HasMutableRegisters)
3523ca95b02SDimitry Andric     return true;
3533ca95b02SDimitry Andric 
3543ca95b02SDimitry Andric   // Scan through the intervening instructions between Def and Insert.
3553ca95b02SDimitry Andric   MachineBasicBlock::const_iterator D(Def), I(Insert);
3563ca95b02SDimitry Andric   for (--I; I != D; --I) {
3573ca95b02SDimitry Andric     bool InterveningRead = false;
3583ca95b02SDimitry Andric     bool InterveningWrite = false;
3593ca95b02SDimitry Andric     bool InterveningEffects = false;
3603ca95b02SDimitry Andric     bool InterveningStackPointer = false;
3613ca95b02SDimitry Andric     Query(*I, AA, InterveningRead, InterveningWrite, InterveningEffects,
3623ca95b02SDimitry Andric           InterveningStackPointer);
3633ca95b02SDimitry Andric     if (Effects && InterveningEffects)
3643ca95b02SDimitry Andric       return false;
3653ca95b02SDimitry Andric     if (Read && InterveningWrite)
3663ca95b02SDimitry Andric       return false;
3673ca95b02SDimitry Andric     if (Write && (InterveningRead || InterveningWrite))
3683ca95b02SDimitry Andric       return false;
3693ca95b02SDimitry Andric     if (StackPointer && InterveningStackPointer)
3703ca95b02SDimitry Andric       return false;
371d88c1a5aSDimitry Andric 
372d88c1a5aSDimitry Andric     for (unsigned Reg : MutableRegisters)
373d88c1a5aSDimitry Andric       for (const MachineOperand &MO : I->operands())
374d88c1a5aSDimitry Andric         if (MO.isReg() && MO.isDef() && MO.getReg() == Reg)
375d88c1a5aSDimitry Andric           return false;
3767d523365SDimitry Andric   }
3777d523365SDimitry Andric 
3783ca95b02SDimitry Andric   return true;
3793ca95b02SDimitry Andric }
3803ca95b02SDimitry Andric 
3813ca95b02SDimitry Andric /// Test whether OneUse, a use of Reg, dominates all of Reg's other uses.
3823ca95b02SDimitry Andric static bool OneUseDominatesOtherUses(unsigned Reg, const MachineOperand &OneUse,
3833ca95b02SDimitry Andric                                      const MachineBasicBlock &MBB,
3843ca95b02SDimitry Andric                                      const MachineRegisterInfo &MRI,
3853ca95b02SDimitry Andric                                      const MachineDominatorTree &MDT,
3863ca95b02SDimitry Andric                                      LiveIntervals &LIS,
3873ca95b02SDimitry Andric                                      WebAssemblyFunctionInfo &MFI) {
3883ca95b02SDimitry Andric   const LiveInterval &LI = LIS.getInterval(Reg);
3893ca95b02SDimitry Andric 
3903ca95b02SDimitry Andric   const MachineInstr *OneUseInst = OneUse.getParent();
3913ca95b02SDimitry Andric   VNInfo *OneUseVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*OneUseInst));
3923ca95b02SDimitry Andric 
393d88c1a5aSDimitry Andric   for (const MachineOperand &Use : MRI.use_nodbg_operands(Reg)) {
3943ca95b02SDimitry Andric     if (&Use == &OneUse)
3953ca95b02SDimitry Andric       continue;
3963ca95b02SDimitry Andric 
3973ca95b02SDimitry Andric     const MachineInstr *UseInst = Use.getParent();
3983ca95b02SDimitry Andric     VNInfo *UseVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*UseInst));
3993ca95b02SDimitry Andric 
4003ca95b02SDimitry Andric     if (UseVNI != OneUseVNI)
4013ca95b02SDimitry Andric       continue;
4023ca95b02SDimitry Andric 
4033ca95b02SDimitry Andric     const MachineInstr *OneUseInst = OneUse.getParent();
4043ca95b02SDimitry Andric     if (UseInst == OneUseInst) {
4053ca95b02SDimitry Andric       // Another use in the same instruction. We need to ensure that the one
4063ca95b02SDimitry Andric       // selected use happens "before" it.
4073ca95b02SDimitry Andric       if (&OneUse > &Use)
4083ca95b02SDimitry Andric         return false;
4093ca95b02SDimitry Andric     } else {
4103ca95b02SDimitry Andric       // Test that the use is dominated by the one selected use.
4113ca95b02SDimitry Andric       while (!MDT.dominates(OneUseInst, UseInst)) {
4123ca95b02SDimitry Andric         // Actually, dominating is over-conservative. Test that the use would
4133ca95b02SDimitry Andric         // happen after the one selected use in the stack evaluation order.
4143ca95b02SDimitry Andric         //
4153ca95b02SDimitry Andric         // This is needed as a consequence of using implicit get_locals for
4163ca95b02SDimitry Andric         // uses and implicit set_locals for defs.
4173ca95b02SDimitry Andric         if (UseInst->getDesc().getNumDefs() == 0)
4183ca95b02SDimitry Andric           return false;
4193ca95b02SDimitry Andric         const MachineOperand &MO = UseInst->getOperand(0);
4203ca95b02SDimitry Andric         if (!MO.isReg())
4213ca95b02SDimitry Andric           return false;
4223ca95b02SDimitry Andric         unsigned DefReg = MO.getReg();
4233ca95b02SDimitry Andric         if (!TargetRegisterInfo::isVirtualRegister(DefReg) ||
4243ca95b02SDimitry Andric             !MFI.isVRegStackified(DefReg))
4253ca95b02SDimitry Andric           return false;
4263ca95b02SDimitry Andric         assert(MRI.hasOneUse(DefReg));
4273ca95b02SDimitry Andric         const MachineOperand &NewUse = *MRI.use_begin(DefReg);
4283ca95b02SDimitry Andric         const MachineInstr *NewUseInst = NewUse.getParent();
4293ca95b02SDimitry Andric         if (NewUseInst == OneUseInst) {
4303ca95b02SDimitry Andric           if (&OneUse > &NewUse)
4313ca95b02SDimitry Andric             return false;
4323ca95b02SDimitry Andric           break;
4333ca95b02SDimitry Andric         }
4343ca95b02SDimitry Andric         UseInst = NewUseInst;
4353ca95b02SDimitry Andric       }
4363ca95b02SDimitry Andric     }
4373ca95b02SDimitry Andric   }
4383ca95b02SDimitry Andric   return true;
4393ca95b02SDimitry Andric }
4403ca95b02SDimitry Andric 
441d88c1a5aSDimitry Andric /// Get the appropriate tee opcode for the given register class.
442d88c1a5aSDimitry Andric static unsigned GetTeeOpcode(const TargetRegisterClass *RC) {
4433ca95b02SDimitry Andric   if (RC == &WebAssembly::I32RegClass)
444d88c1a5aSDimitry Andric     return WebAssembly::TEE_I32;
4453ca95b02SDimitry Andric   if (RC == &WebAssembly::I64RegClass)
446d88c1a5aSDimitry Andric     return WebAssembly::TEE_I64;
4473ca95b02SDimitry Andric   if (RC == &WebAssembly::F32RegClass)
448d88c1a5aSDimitry Andric     return WebAssembly::TEE_F32;
4493ca95b02SDimitry Andric   if (RC == &WebAssembly::F64RegClass)
450d88c1a5aSDimitry Andric     return WebAssembly::TEE_F64;
451d88c1a5aSDimitry Andric   if (RC == &WebAssembly::V128RegClass)
452d88c1a5aSDimitry Andric     return WebAssembly::TEE_V128;
4533ca95b02SDimitry Andric   llvm_unreachable("Unexpected register class");
4543ca95b02SDimitry Andric }
4553ca95b02SDimitry Andric 
4563ca95b02SDimitry Andric // Shrink LI to its uses, cleaning up LI.
4573ca95b02SDimitry Andric static void ShrinkToUses(LiveInterval &LI, LiveIntervals &LIS) {
4583ca95b02SDimitry Andric   if (LIS.shrinkToUses(&LI)) {
4593ca95b02SDimitry Andric     SmallVector<LiveInterval*, 4> SplitLIs;
4603ca95b02SDimitry Andric     LIS.splitSeparateComponents(LI, SplitLIs);
4613ca95b02SDimitry Andric   }
4623ca95b02SDimitry Andric }
4633ca95b02SDimitry Andric 
4643ca95b02SDimitry Andric /// A single-use def in the same block with no intervening memory or register
4653ca95b02SDimitry Andric /// dependencies; move the def down and nest it with the current instruction.
4663ca95b02SDimitry Andric static MachineInstr *MoveForSingleUse(unsigned Reg, MachineOperand& Op,
4673ca95b02SDimitry Andric                                       MachineInstr *Def,
4683ca95b02SDimitry Andric                                       MachineBasicBlock &MBB,
4693ca95b02SDimitry Andric                                       MachineInstr *Insert, LiveIntervals &LIS,
4703ca95b02SDimitry Andric                                       WebAssemblyFunctionInfo &MFI,
4713ca95b02SDimitry Andric                                       MachineRegisterInfo &MRI) {
4723ca95b02SDimitry Andric   DEBUG(dbgs() << "Move for single use: "; Def->dump());
4733ca95b02SDimitry Andric 
4743ca95b02SDimitry Andric   MBB.splice(Insert, &MBB, Def);
4753ca95b02SDimitry Andric   LIS.handleMove(*Def);
4763ca95b02SDimitry Andric 
4773ca95b02SDimitry Andric   if (MRI.hasOneDef(Reg) && MRI.hasOneUse(Reg)) {
4783ca95b02SDimitry Andric     // No one else is using this register for anything so we can just stackify
4793ca95b02SDimitry Andric     // it in place.
4803ca95b02SDimitry Andric     MFI.stackifyVReg(Reg);
4813ca95b02SDimitry Andric   } else {
4823ca95b02SDimitry Andric     // The register may have unrelated uses or defs; create a new register for
4833ca95b02SDimitry Andric     // just our one def and use so that we can stackify it.
4843ca95b02SDimitry Andric     unsigned NewReg = MRI.createVirtualRegister(MRI.getRegClass(Reg));
4853ca95b02SDimitry Andric     Def->getOperand(0).setReg(NewReg);
4863ca95b02SDimitry Andric     Op.setReg(NewReg);
4873ca95b02SDimitry Andric 
4883ca95b02SDimitry Andric     // Tell LiveIntervals about the new register.
4893ca95b02SDimitry Andric     LIS.createAndComputeVirtRegInterval(NewReg);
4903ca95b02SDimitry Andric 
4913ca95b02SDimitry Andric     // Tell LiveIntervals about the changes to the old register.
4923ca95b02SDimitry Andric     LiveInterval &LI = LIS.getInterval(Reg);
4933ca95b02SDimitry Andric     LI.removeSegment(LIS.getInstructionIndex(*Def).getRegSlot(),
4943ca95b02SDimitry Andric                      LIS.getInstructionIndex(*Op.getParent()).getRegSlot(),
4953ca95b02SDimitry Andric                      /*RemoveDeadValNo=*/true);
4963ca95b02SDimitry Andric 
4973ca95b02SDimitry Andric     MFI.stackifyVReg(NewReg);
4983ca95b02SDimitry Andric 
4993ca95b02SDimitry Andric     DEBUG(dbgs() << " - Replaced register: "; Def->dump());
5003ca95b02SDimitry Andric   }
5013ca95b02SDimitry Andric 
5023ca95b02SDimitry Andric   ImposeStackOrdering(Def);
5033ca95b02SDimitry Andric   return Def;
5043ca95b02SDimitry Andric }
5053ca95b02SDimitry Andric 
5063ca95b02SDimitry Andric /// A trivially cloneable instruction; clone it and nest the new copy with the
5073ca95b02SDimitry Andric /// current instruction.
5083ca95b02SDimitry Andric static MachineInstr *RematerializeCheapDef(
5093ca95b02SDimitry Andric     unsigned Reg, MachineOperand &Op, MachineInstr &Def, MachineBasicBlock &MBB,
5103ca95b02SDimitry Andric     MachineBasicBlock::instr_iterator Insert, LiveIntervals &LIS,
5113ca95b02SDimitry Andric     WebAssemblyFunctionInfo &MFI, MachineRegisterInfo &MRI,
5123ca95b02SDimitry Andric     const WebAssemblyInstrInfo *TII, const WebAssemblyRegisterInfo *TRI) {
5133ca95b02SDimitry Andric   DEBUG(dbgs() << "Rematerializing cheap def: "; Def.dump());
5143ca95b02SDimitry Andric   DEBUG(dbgs() << " - for use in "; Op.getParent()->dump());
5153ca95b02SDimitry Andric 
5163ca95b02SDimitry Andric   unsigned NewReg = MRI.createVirtualRegister(MRI.getRegClass(Reg));
5173ca95b02SDimitry Andric   TII->reMaterialize(MBB, Insert, NewReg, 0, Def, *TRI);
5183ca95b02SDimitry Andric   Op.setReg(NewReg);
5193ca95b02SDimitry Andric   MachineInstr *Clone = &*std::prev(Insert);
5203ca95b02SDimitry Andric   LIS.InsertMachineInstrInMaps(*Clone);
5213ca95b02SDimitry Andric   LIS.createAndComputeVirtRegInterval(NewReg);
5223ca95b02SDimitry Andric   MFI.stackifyVReg(NewReg);
5233ca95b02SDimitry Andric   ImposeStackOrdering(Clone);
5243ca95b02SDimitry Andric 
5253ca95b02SDimitry Andric   DEBUG(dbgs() << " - Cloned to "; Clone->dump());
5263ca95b02SDimitry Andric 
5273ca95b02SDimitry Andric   // Shrink the interval.
5283ca95b02SDimitry Andric   bool IsDead = MRI.use_empty(Reg);
5293ca95b02SDimitry Andric   if (!IsDead) {
5303ca95b02SDimitry Andric     LiveInterval &LI = LIS.getInterval(Reg);
5313ca95b02SDimitry Andric     ShrinkToUses(LI, LIS);
5323ca95b02SDimitry Andric     IsDead = !LI.liveAt(LIS.getInstructionIndex(Def).getDeadSlot());
5333ca95b02SDimitry Andric   }
5343ca95b02SDimitry Andric 
5353ca95b02SDimitry Andric   // If that was the last use of the original, delete the original.
5363ca95b02SDimitry Andric   if (IsDead) {
5373ca95b02SDimitry Andric     DEBUG(dbgs() << " - Deleting original\n");
5383ca95b02SDimitry Andric     SlotIndex Idx = LIS.getInstructionIndex(Def).getRegSlot();
5393ca95b02SDimitry Andric     LIS.removePhysRegDefAt(WebAssembly::ARGUMENTS, Idx);
5403ca95b02SDimitry Andric     LIS.removeInterval(Reg);
5413ca95b02SDimitry Andric     LIS.RemoveMachineInstrFromMaps(Def);
5423ca95b02SDimitry Andric     Def.eraseFromParent();
5433ca95b02SDimitry Andric   }
5443ca95b02SDimitry Andric 
5453ca95b02SDimitry Andric   return Clone;
5463ca95b02SDimitry Andric }
5473ca95b02SDimitry Andric 
5483ca95b02SDimitry Andric /// A multiple-use def in the same block with no intervening memory or register
5493ca95b02SDimitry Andric /// dependencies; move the def down, nest it with the current instruction, and
550d88c1a5aSDimitry Andric /// insert a tee to satisfy the rest of the uses. As an illustration, rewrite
551d88c1a5aSDimitry Andric /// this:
5523ca95b02SDimitry Andric ///
5533ca95b02SDimitry Andric ///    Reg = INST ...        // Def
5543ca95b02SDimitry Andric ///    INST ..., Reg, ...    // Insert
5553ca95b02SDimitry Andric ///    INST ..., Reg, ...
5563ca95b02SDimitry Andric ///    INST ..., Reg, ...
5573ca95b02SDimitry Andric ///
5583ca95b02SDimitry Andric /// to this:
5593ca95b02SDimitry Andric ///
5603ca95b02SDimitry Andric ///    DefReg = INST ...     // Def (to become the new Insert)
561d88c1a5aSDimitry Andric ///    TeeReg, Reg = TEE_... DefReg
5623ca95b02SDimitry Andric ///    INST ..., TeeReg, ... // Insert
5633ca95b02SDimitry Andric ///    INST ..., Reg, ...
5643ca95b02SDimitry Andric ///    INST ..., Reg, ...
5653ca95b02SDimitry Andric ///
5663ca95b02SDimitry Andric /// with DefReg and TeeReg stackified. This eliminates a get_local from the
5673ca95b02SDimitry Andric /// resulting code.
5683ca95b02SDimitry Andric static MachineInstr *MoveAndTeeForMultiUse(
5693ca95b02SDimitry Andric     unsigned Reg, MachineOperand &Op, MachineInstr *Def, MachineBasicBlock &MBB,
5703ca95b02SDimitry Andric     MachineInstr *Insert, LiveIntervals &LIS, WebAssemblyFunctionInfo &MFI,
5713ca95b02SDimitry Andric     MachineRegisterInfo &MRI, const WebAssemblyInstrInfo *TII) {
5723ca95b02SDimitry Andric   DEBUG(dbgs() << "Move and tee for multi-use:"; Def->dump());
5733ca95b02SDimitry Andric 
5743ca95b02SDimitry Andric   // Move Def into place.
5753ca95b02SDimitry Andric   MBB.splice(Insert, &MBB, Def);
5763ca95b02SDimitry Andric   LIS.handleMove(*Def);
5773ca95b02SDimitry Andric 
5783ca95b02SDimitry Andric   // Create the Tee and attach the registers.
5793ca95b02SDimitry Andric   const auto *RegClass = MRI.getRegClass(Reg);
5803ca95b02SDimitry Andric   unsigned TeeReg = MRI.createVirtualRegister(RegClass);
5813ca95b02SDimitry Andric   unsigned DefReg = MRI.createVirtualRegister(RegClass);
5823ca95b02SDimitry Andric   MachineOperand &DefMO = Def->getOperand(0);
5833ca95b02SDimitry Andric   MachineInstr *Tee = BuildMI(MBB, Insert, Insert->getDebugLoc(),
584d88c1a5aSDimitry Andric                               TII->get(GetTeeOpcode(RegClass)), TeeReg)
5853ca95b02SDimitry Andric                           .addReg(Reg, RegState::Define)
5863ca95b02SDimitry Andric                           .addReg(DefReg, getUndefRegState(DefMO.isDead()));
5873ca95b02SDimitry Andric   Op.setReg(TeeReg);
5883ca95b02SDimitry Andric   DefMO.setReg(DefReg);
5893ca95b02SDimitry Andric   SlotIndex TeeIdx = LIS.InsertMachineInstrInMaps(*Tee).getRegSlot();
5903ca95b02SDimitry Andric   SlotIndex DefIdx = LIS.getInstructionIndex(*Def).getRegSlot();
5913ca95b02SDimitry Andric 
5923ca95b02SDimitry Andric   // Tell LiveIntervals we moved the original vreg def from Def to Tee.
5933ca95b02SDimitry Andric   LiveInterval &LI = LIS.getInterval(Reg);
5943ca95b02SDimitry Andric   LiveInterval::iterator I = LI.FindSegmentContaining(DefIdx);
5953ca95b02SDimitry Andric   VNInfo *ValNo = LI.getVNInfoAt(DefIdx);
5963ca95b02SDimitry Andric   I->start = TeeIdx;
5973ca95b02SDimitry Andric   ValNo->def = TeeIdx;
5983ca95b02SDimitry Andric   ShrinkToUses(LI, LIS);
5993ca95b02SDimitry Andric 
6003ca95b02SDimitry Andric   // Finish stackifying the new regs.
6013ca95b02SDimitry Andric   LIS.createAndComputeVirtRegInterval(TeeReg);
6023ca95b02SDimitry Andric   LIS.createAndComputeVirtRegInterval(DefReg);
6033ca95b02SDimitry Andric   MFI.stackifyVReg(DefReg);
6043ca95b02SDimitry Andric   MFI.stackifyVReg(TeeReg);
6053ca95b02SDimitry Andric   ImposeStackOrdering(Def);
6063ca95b02SDimitry Andric   ImposeStackOrdering(Tee);
6073ca95b02SDimitry Andric 
6083ca95b02SDimitry Andric   DEBUG(dbgs() << " - Replaced register: "; Def->dump());
6093ca95b02SDimitry Andric   DEBUG(dbgs() << " - Tee instruction: "; Tee->dump());
6103ca95b02SDimitry Andric   return Def;
6113ca95b02SDimitry Andric }
6123ca95b02SDimitry Andric 
6133ca95b02SDimitry Andric namespace {
6143ca95b02SDimitry Andric /// A stack for walking the tree of instructions being built, visiting the
6153ca95b02SDimitry Andric /// MachineOperands in DFS order.
6163ca95b02SDimitry Andric class TreeWalkerState {
6173ca95b02SDimitry Andric   typedef MachineInstr::mop_iterator mop_iterator;
6183ca95b02SDimitry Andric   typedef std::reverse_iterator<mop_iterator> mop_reverse_iterator;
6193ca95b02SDimitry Andric   typedef iterator_range<mop_reverse_iterator> RangeTy;
6203ca95b02SDimitry Andric   SmallVector<RangeTy, 4> Worklist;
6213ca95b02SDimitry Andric 
6223ca95b02SDimitry Andric public:
6233ca95b02SDimitry Andric   explicit TreeWalkerState(MachineInstr *Insert) {
6243ca95b02SDimitry Andric     const iterator_range<mop_iterator> &Range = Insert->explicit_uses();
6253ca95b02SDimitry Andric     if (Range.begin() != Range.end())
6263ca95b02SDimitry Andric       Worklist.push_back(reverse(Range));
6273ca95b02SDimitry Andric   }
6283ca95b02SDimitry Andric 
6293ca95b02SDimitry Andric   bool Done() const { return Worklist.empty(); }
6303ca95b02SDimitry Andric 
6313ca95b02SDimitry Andric   MachineOperand &Pop() {
6323ca95b02SDimitry Andric     RangeTy &Range = Worklist.back();
6333ca95b02SDimitry Andric     MachineOperand &Op = *Range.begin();
6343ca95b02SDimitry Andric     Range = drop_begin(Range, 1);
6353ca95b02SDimitry Andric     if (Range.begin() == Range.end())
6363ca95b02SDimitry Andric       Worklist.pop_back();
6373ca95b02SDimitry Andric     assert((Worklist.empty() ||
6383ca95b02SDimitry Andric             Worklist.back().begin() != Worklist.back().end()) &&
6393ca95b02SDimitry Andric            "Empty ranges shouldn't remain in the worklist");
6403ca95b02SDimitry Andric     return Op;
6413ca95b02SDimitry Andric   }
6423ca95b02SDimitry Andric 
6433ca95b02SDimitry Andric   /// Push Instr's operands onto the stack to be visited.
6443ca95b02SDimitry Andric   void PushOperands(MachineInstr *Instr) {
6453ca95b02SDimitry Andric     const iterator_range<mop_iterator> &Range(Instr->explicit_uses());
6463ca95b02SDimitry Andric     if (Range.begin() != Range.end())
6473ca95b02SDimitry Andric       Worklist.push_back(reverse(Range));
6483ca95b02SDimitry Andric   }
6493ca95b02SDimitry Andric 
6503ca95b02SDimitry Andric   /// Some of Instr's operands are on the top of the stack; remove them and
6513ca95b02SDimitry Andric   /// re-insert them starting from the beginning (because we've commuted them).
6523ca95b02SDimitry Andric   void ResetTopOperands(MachineInstr *Instr) {
6533ca95b02SDimitry Andric     assert(HasRemainingOperands(Instr) &&
6543ca95b02SDimitry Andric            "Reseting operands should only be done when the instruction has "
6553ca95b02SDimitry Andric            "an operand still on the stack");
6563ca95b02SDimitry Andric     Worklist.back() = reverse(Instr->explicit_uses());
6573ca95b02SDimitry Andric   }
6583ca95b02SDimitry Andric 
6593ca95b02SDimitry Andric   /// Test whether Instr has operands remaining to be visited at the top of
6603ca95b02SDimitry Andric   /// the stack.
6613ca95b02SDimitry Andric   bool HasRemainingOperands(const MachineInstr *Instr) const {
6623ca95b02SDimitry Andric     if (Worklist.empty())
6633ca95b02SDimitry Andric       return false;
6643ca95b02SDimitry Andric     const RangeTy &Range = Worklist.back();
6653ca95b02SDimitry Andric     return Range.begin() != Range.end() && Range.begin()->getParent() == Instr;
6663ca95b02SDimitry Andric   }
6673ca95b02SDimitry Andric 
6683ca95b02SDimitry Andric   /// Test whether the given register is present on the stack, indicating an
6693ca95b02SDimitry Andric   /// operand in the tree that we haven't visited yet. Moving a definition of
6703ca95b02SDimitry Andric   /// Reg to a point in the tree after that would change its value.
6713ca95b02SDimitry Andric   ///
6723ca95b02SDimitry Andric   /// This is needed as a consequence of using implicit get_locals for
6733ca95b02SDimitry Andric   /// uses and implicit set_locals for defs.
6743ca95b02SDimitry Andric   bool IsOnStack(unsigned Reg) const {
6753ca95b02SDimitry Andric     for (const RangeTy &Range : Worklist)
6763ca95b02SDimitry Andric       for (const MachineOperand &MO : Range)
6773ca95b02SDimitry Andric         if (MO.isReg() && MO.getReg() == Reg)
6783ca95b02SDimitry Andric           return true;
6793ca95b02SDimitry Andric     return false;
6803ca95b02SDimitry Andric   }
6813ca95b02SDimitry Andric };
6823ca95b02SDimitry Andric 
6833ca95b02SDimitry Andric /// State to keep track of whether commuting is in flight or whether it's been
6843ca95b02SDimitry Andric /// tried for the current instruction and didn't work.
6853ca95b02SDimitry Andric class CommutingState {
6863ca95b02SDimitry Andric   /// There are effectively three states: the initial state where we haven't
6873ca95b02SDimitry Andric   /// started commuting anything and we don't know anything yet, the tenative
6883ca95b02SDimitry Andric   /// state where we've commuted the operands of the current instruction and are
6893ca95b02SDimitry Andric   /// revisting it, and the declined state where we've reverted the operands
6903ca95b02SDimitry Andric   /// back to their original order and will no longer commute it further.
6913ca95b02SDimitry Andric   bool TentativelyCommuting;
6923ca95b02SDimitry Andric   bool Declined;
6933ca95b02SDimitry Andric 
6943ca95b02SDimitry Andric   /// During the tentative state, these hold the operand indices of the commuted
6953ca95b02SDimitry Andric   /// operands.
6963ca95b02SDimitry Andric   unsigned Operand0, Operand1;
6973ca95b02SDimitry Andric 
6983ca95b02SDimitry Andric public:
6993ca95b02SDimitry Andric   CommutingState() : TentativelyCommuting(false), Declined(false) {}
7003ca95b02SDimitry Andric 
7013ca95b02SDimitry Andric   /// Stackification for an operand was not successful due to ordering
7023ca95b02SDimitry Andric   /// constraints. If possible, and if we haven't already tried it and declined
7033ca95b02SDimitry Andric   /// it, commute Insert's operands and prepare to revisit it.
7043ca95b02SDimitry Andric   void MaybeCommute(MachineInstr *Insert, TreeWalkerState &TreeWalker,
7053ca95b02SDimitry Andric                     const WebAssemblyInstrInfo *TII) {
7063ca95b02SDimitry Andric     if (TentativelyCommuting) {
7073ca95b02SDimitry Andric       assert(!Declined &&
7083ca95b02SDimitry Andric              "Don't decline commuting until you've finished trying it");
7093ca95b02SDimitry Andric       // Commuting didn't help. Revert it.
7103ca95b02SDimitry Andric       TII->commuteInstruction(*Insert, /*NewMI=*/false, Operand0, Operand1);
7113ca95b02SDimitry Andric       TentativelyCommuting = false;
7123ca95b02SDimitry Andric       Declined = true;
7133ca95b02SDimitry Andric     } else if (!Declined && TreeWalker.HasRemainingOperands(Insert)) {
7143ca95b02SDimitry Andric       Operand0 = TargetInstrInfo::CommuteAnyOperandIndex;
7153ca95b02SDimitry Andric       Operand1 = TargetInstrInfo::CommuteAnyOperandIndex;
7163ca95b02SDimitry Andric       if (TII->findCommutedOpIndices(*Insert, Operand0, Operand1)) {
7173ca95b02SDimitry Andric         // Tentatively commute the operands and try again.
7183ca95b02SDimitry Andric         TII->commuteInstruction(*Insert, /*NewMI=*/false, Operand0, Operand1);
7193ca95b02SDimitry Andric         TreeWalker.ResetTopOperands(Insert);
7203ca95b02SDimitry Andric         TentativelyCommuting = true;
7213ca95b02SDimitry Andric         Declined = false;
7223ca95b02SDimitry Andric       }
7233ca95b02SDimitry Andric     }
7243ca95b02SDimitry Andric   }
7253ca95b02SDimitry Andric 
7263ca95b02SDimitry Andric   /// Stackification for some operand was successful. Reset to the default
7273ca95b02SDimitry Andric   /// state.
7283ca95b02SDimitry Andric   void Reset() {
7293ca95b02SDimitry Andric     TentativelyCommuting = false;
7303ca95b02SDimitry Andric     Declined = false;
7313ca95b02SDimitry Andric   }
7323ca95b02SDimitry Andric };
7333ca95b02SDimitry Andric } // end anonymous namespace
7343ca95b02SDimitry Andric 
7357d523365SDimitry Andric bool WebAssemblyRegStackify::runOnMachineFunction(MachineFunction &MF) {
7367d523365SDimitry Andric   DEBUG(dbgs() << "********** Register Stackifying **********\n"
7377d523365SDimitry Andric                   "********** Function: "
7387d523365SDimitry Andric                << MF.getName() << '\n');
7397d523365SDimitry Andric 
7407d523365SDimitry Andric   bool Changed = false;
7417d523365SDimitry Andric   MachineRegisterInfo &MRI = MF.getRegInfo();
7427d523365SDimitry Andric   WebAssemblyFunctionInfo &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
7433ca95b02SDimitry Andric   const auto *TII = MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
7443ca95b02SDimitry Andric   const auto *TRI = MF.getSubtarget<WebAssemblySubtarget>().getRegisterInfo();
7457d523365SDimitry Andric   AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
7463ca95b02SDimitry Andric   MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
7477d523365SDimitry Andric   LiveIntervals &LIS = getAnalysis<LiveIntervals>();
7487d523365SDimitry Andric 
7497d523365SDimitry Andric   // Walk the instructions from the bottom up. Currently we don't look past
7507d523365SDimitry Andric   // block boundaries, and the blocks aren't ordered so the block visitation
7517d523365SDimitry Andric   // order isn't significant, but we may want to change this in the future.
7527d523365SDimitry Andric   for (MachineBasicBlock &MBB : MF) {
753444ed5c5SDimitry Andric     // Don't use a range-based for loop, because we modify the list as we're
754444ed5c5SDimitry Andric     // iterating over it and the end iterator may change.
755444ed5c5SDimitry Andric     for (auto MII = MBB.rbegin(); MII != MBB.rend(); ++MII) {
756444ed5c5SDimitry Andric       MachineInstr *Insert = &*MII;
7577d523365SDimitry Andric       // Don't nest anything inside an inline asm, because we don't have
7587d523365SDimitry Andric       // constraints for $push inputs.
7597d523365SDimitry Andric       if (Insert->getOpcode() == TargetOpcode::INLINEASM)
7603ca95b02SDimitry Andric         continue;
7613ca95b02SDimitry Andric 
7623ca95b02SDimitry Andric       // Ignore debugging intrinsics.
7633ca95b02SDimitry Andric       if (Insert->getOpcode() == TargetOpcode::DBG_VALUE)
7643ca95b02SDimitry Andric         continue;
7657d523365SDimitry Andric 
7667d523365SDimitry Andric       // Iterate through the inputs in reverse order, since we'll be pulling
7677d523365SDimitry Andric       // operands off the stack in LIFO order.
7683ca95b02SDimitry Andric       CommutingState Commuting;
7693ca95b02SDimitry Andric       TreeWalkerState TreeWalker(Insert);
7703ca95b02SDimitry Andric       while (!TreeWalker.Done()) {
7713ca95b02SDimitry Andric         MachineOperand &Op = TreeWalker.Pop();
7723ca95b02SDimitry Andric 
7737d523365SDimitry Andric         // We're only interested in explicit virtual register operands.
7743ca95b02SDimitry Andric         if (!Op.isReg())
7757d523365SDimitry Andric           continue;
7767d523365SDimitry Andric 
7777d523365SDimitry Andric         unsigned Reg = Op.getReg();
7783ca95b02SDimitry Andric         assert(Op.isUse() && "explicit_uses() should only iterate over uses");
7793ca95b02SDimitry Andric         assert(!Op.isImplicit() &&
7803ca95b02SDimitry Andric                "explicit_uses() should only iterate over explicit operands");
7813ca95b02SDimitry Andric         if (TargetRegisterInfo::isPhysicalRegister(Reg))
7827d523365SDimitry Andric           continue;
7837d523365SDimitry Andric 
784d88c1a5aSDimitry Andric         // Identify the definition for this register at this point.
7853ca95b02SDimitry Andric         MachineInstr *Def = GetVRegDef(Reg, Insert, MRI, LIS);
7863ca95b02SDimitry Andric         if (!Def)
7877d523365SDimitry Andric           continue;
7887d523365SDimitry Andric 
7897d523365SDimitry Andric         // Don't nest an INLINE_ASM def into anything, because we don't have
7907d523365SDimitry Andric         // constraints for $pop outputs.
7917d523365SDimitry Andric         if (Def->getOpcode() == TargetOpcode::INLINEASM)
7927d523365SDimitry Andric           continue;
7937d523365SDimitry Andric 
7947d523365SDimitry Andric         // Argument instructions represent live-in registers and not real
7957d523365SDimitry Andric         // instructions.
796d88c1a5aSDimitry Andric         if (WebAssembly::isArgument(*Def))
7977d523365SDimitry Andric           continue;
7987d523365SDimitry Andric 
7993ca95b02SDimitry Andric         // Decide which strategy to take. Prefer to move a single-use value
800d88c1a5aSDimitry Andric         // over cloning it, and prefer cloning over introducing a tee.
8013ca95b02SDimitry Andric         // For moving, we require the def to be in the same block as the use;
8023ca95b02SDimitry Andric         // this makes things simpler (LiveIntervals' handleMove function only
8033ca95b02SDimitry Andric         // supports intra-block moves) and it's MachineSink's job to catch all
8043ca95b02SDimitry Andric         // the sinking opportunities anyway.
8053ca95b02SDimitry Andric         bool SameBlock = Def->getParent() == &MBB;
806d88c1a5aSDimitry Andric         bool CanMove = SameBlock && IsSafeToMove(Def, Insert, AA, MRI) &&
8073ca95b02SDimitry Andric                        !TreeWalker.IsOnStack(Reg);
8083ca95b02SDimitry Andric         if (CanMove && HasOneUse(Reg, Def, MRI, MDT, LIS)) {
8093ca95b02SDimitry Andric           Insert = MoveForSingleUse(Reg, Op, Def, MBB, Insert, LIS, MFI, MRI);
8103ca95b02SDimitry Andric         } else if (ShouldRematerialize(*Def, AA, TII)) {
8113ca95b02SDimitry Andric           Insert =
8123ca95b02SDimitry Andric               RematerializeCheapDef(Reg, Op, *Def, MBB, Insert->getIterator(),
8133ca95b02SDimitry Andric                                     LIS, MFI, MRI, TII, TRI);
8143ca95b02SDimitry Andric         } else if (CanMove &&
8153ca95b02SDimitry Andric                    OneUseDominatesOtherUses(Reg, Op, MBB, MRI, MDT, LIS, MFI)) {
8163ca95b02SDimitry Andric           Insert = MoveAndTeeForMultiUse(Reg, Op, Def, MBB, Insert, LIS, MFI,
8173ca95b02SDimitry Andric                                          MRI, TII);
8183ca95b02SDimitry Andric         } else {
8193ca95b02SDimitry Andric           // We failed to stackify the operand. If the problem was ordering
8203ca95b02SDimitry Andric           // constraints, Commuting may be able to help.
8213ca95b02SDimitry Andric           if (!CanMove && SameBlock)
8223ca95b02SDimitry Andric             Commuting.MaybeCommute(Insert, TreeWalker, TII);
8233ca95b02SDimitry Andric           // Proceed to the next operand.
8247d523365SDimitry Andric           continue;
8257d523365SDimitry Andric         }
8263ca95b02SDimitry Andric 
827d88c1a5aSDimitry Andric         // If the instruction we just stackified is an IMPLICIT_DEF, convert it
828d88c1a5aSDimitry Andric         // to a constant 0 so that the def is explicit, and the push/pop
829d88c1a5aSDimitry Andric         // correspondence is maintained.
830d88c1a5aSDimitry Andric         if (Insert->getOpcode() == TargetOpcode::IMPLICIT_DEF)
831d88c1a5aSDimitry Andric           ConvertImplicitDefToConstZero(Insert, MRI, TII, MF);
832d88c1a5aSDimitry Andric 
8333ca95b02SDimitry Andric         // We stackified an operand. Add the defining instruction's operands to
8343ca95b02SDimitry Andric         // the worklist stack now to continue to build an ever deeper tree.
8353ca95b02SDimitry Andric         Commuting.Reset();
8363ca95b02SDimitry Andric         TreeWalker.PushOperands(Insert);
8373ca95b02SDimitry Andric       }
8383ca95b02SDimitry Andric 
8393ca95b02SDimitry Andric       // If we stackified any operands, skip over the tree to start looking for
8403ca95b02SDimitry Andric       // the next instruction we can build a tree on.
8413ca95b02SDimitry Andric       if (Insert != &*MII) {
842444ed5c5SDimitry Andric         ImposeStackOrdering(&*MII);
843d88c1a5aSDimitry Andric         MII = MachineBasicBlock::iterator(Insert).getReverse();
8443ca95b02SDimitry Andric         Changed = true;
8453ca95b02SDimitry Andric       }
8467d523365SDimitry Andric     }
8477d523365SDimitry Andric   }
8487d523365SDimitry Andric 
849d88c1a5aSDimitry Andric   // If we used VALUE_STACK anywhere, add it to the live-in sets everywhere so
8503ca95b02SDimitry Andric   // that it never looks like a use-before-def.
8517d523365SDimitry Andric   if (Changed) {
852d88c1a5aSDimitry Andric     MF.getRegInfo().addLiveIn(WebAssembly::VALUE_STACK);
8537d523365SDimitry Andric     for (MachineBasicBlock &MBB : MF)
854d88c1a5aSDimitry Andric       MBB.addLiveIn(WebAssembly::VALUE_STACK);
8557d523365SDimitry Andric   }
8567d523365SDimitry Andric 
8577d523365SDimitry Andric #ifndef NDEBUG
8583ca95b02SDimitry Andric   // Verify that pushes and pops are performed in LIFO order.
8597d523365SDimitry Andric   SmallVector<unsigned, 0> Stack;
8607d523365SDimitry Andric   for (MachineBasicBlock &MBB : MF) {
8617d523365SDimitry Andric     for (MachineInstr &MI : MBB) {
8623ca95b02SDimitry Andric       if (MI.isDebugValue())
8633ca95b02SDimitry Andric         continue;
8647d523365SDimitry Andric       for (MachineOperand &MO : reverse(MI.explicit_operands())) {
8657d523365SDimitry Andric         if (!MO.isReg())
8667d523365SDimitry Andric           continue;
8673ca95b02SDimitry Andric         unsigned Reg = MO.getReg();
8687d523365SDimitry Andric 
8693ca95b02SDimitry Andric         if (MFI.isVRegStackified(Reg)) {
8707d523365SDimitry Andric           if (MO.isDef())
8713ca95b02SDimitry Andric             Stack.push_back(Reg);
8727d523365SDimitry Andric           else
8733ca95b02SDimitry Andric             assert(Stack.pop_back_val() == Reg &&
8743ca95b02SDimitry Andric                    "Register stack pop should be paired with a push");
8757d523365SDimitry Andric         }
8767d523365SDimitry Andric       }
8777d523365SDimitry Andric     }
8787d523365SDimitry Andric     // TODO: Generalize this code to support keeping values on the stack across
8797d523365SDimitry Andric     // basic block boundaries.
8803ca95b02SDimitry Andric     assert(Stack.empty() &&
8813ca95b02SDimitry Andric            "Register stack pushes and pops should be balanced");
8827d523365SDimitry Andric   }
8837d523365SDimitry Andric #endif
8847d523365SDimitry Andric 
8857d523365SDimitry Andric   return Changed;
8867d523365SDimitry Andric }
887