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
111462faadSDan Gohman /// \brief 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 
231462faadSDan Gohman #include "WebAssembly.h"
244ba4816bSDan Gohman #include "MCTargetDesc/WebAssemblyMCTargetDesc.h" // for WebAssembly::ARGUMENT_*
257a6b9825SDan Gohman #include "WebAssemblyMachineFunctionInfo.h"
26b6fd39a3SDan Gohman #include "WebAssemblySubtarget.h"
27*4fc4e42dSDan Gohman #include "WebAssemblyUtilities.h"
2881719f85SDan Gohman #include "llvm/Analysis/AliasAnalysis.h"
298887d1faSDan Gohman #include "llvm/CodeGen/LiveIntervalAnalysis.h"
301462faadSDan Gohman #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
31adf28177SDan Gohman #include "llvm/CodeGen/MachineDominators.h"
32adf28177SDan Gohman #include "llvm/CodeGen/MachineInstrBuilder.h"
331462faadSDan Gohman #include "llvm/CodeGen/MachineRegisterInfo.h"
341462faadSDan Gohman #include "llvm/CodeGen/Passes.h"
351462faadSDan Gohman #include "llvm/Support/Debug.h"
361462faadSDan Gohman #include "llvm/Support/raw_ostream.h"
371462faadSDan Gohman using namespace llvm;
381462faadSDan Gohman 
391462faadSDan Gohman #define DEBUG_TYPE "wasm-reg-stackify"
401462faadSDan Gohman 
411462faadSDan Gohman namespace {
421462faadSDan Gohman class WebAssemblyRegStackify final : public MachineFunctionPass {
43117296c0SMehdi Amini   StringRef getPassName() const override {
441462faadSDan Gohman     return "WebAssembly Register Stackify";
451462faadSDan Gohman   }
461462faadSDan Gohman 
471462faadSDan Gohman   void getAnalysisUsage(AnalysisUsage &AU) const override {
481462faadSDan Gohman     AU.setPreservesCFG();
4981719f85SDan Gohman     AU.addRequired<AAResultsWrapperPass>();
50adf28177SDan Gohman     AU.addRequired<MachineDominatorTree>();
518887d1faSDan Gohman     AU.addRequired<LiveIntervals>();
521462faadSDan Gohman     AU.addPreserved<MachineBlockFrequencyInfo>();
538887d1faSDan Gohman     AU.addPreserved<SlotIndexes>();
548887d1faSDan Gohman     AU.addPreserved<LiveIntervals>();
558887d1faSDan Gohman     AU.addPreservedID(LiveVariablesID);
56adf28177SDan Gohman     AU.addPreserved<MachineDominatorTree>();
571462faadSDan Gohman     MachineFunctionPass::getAnalysisUsage(AU);
581462faadSDan Gohman   }
591462faadSDan Gohman 
601462faadSDan Gohman   bool runOnMachineFunction(MachineFunction &MF) override;
611462faadSDan Gohman 
621462faadSDan Gohman public:
631462faadSDan Gohman   static char ID; // Pass identification, replacement for typeid
641462faadSDan Gohman   WebAssemblyRegStackify() : MachineFunctionPass(ID) {}
651462faadSDan Gohman };
661462faadSDan Gohman } // end anonymous namespace
671462faadSDan Gohman 
681462faadSDan Gohman char WebAssemblyRegStackify::ID = 0;
691462faadSDan Gohman FunctionPass *llvm::createWebAssemblyRegStackify() {
701462faadSDan Gohman   return new WebAssemblyRegStackify();
711462faadSDan Gohman }
721462faadSDan Gohman 
73b0992dafSDan Gohman // Decorate the given instruction with implicit operands that enforce the
748887d1faSDan Gohman // expression stack ordering constraints for an instruction which is on
758887d1faSDan Gohman // the expression stack.
768887d1faSDan Gohman static void ImposeStackOrdering(MachineInstr *MI) {
77e040533eSDan Gohman   // Write the opaque VALUE_STACK register.
78e040533eSDan Gohman   if (!MI->definesRegister(WebAssembly::VALUE_STACK))
79e040533eSDan Gohman     MI->addOperand(MachineOperand::CreateReg(WebAssembly::VALUE_STACK,
80b0992dafSDan Gohman                                              /*isDef=*/true,
81b0992dafSDan Gohman                                              /*isImp=*/true));
824da4abd8SDan Gohman 
83e040533eSDan Gohman   // Also read the opaque VALUE_STACK register.
84e040533eSDan Gohman   if (!MI->readsRegister(WebAssembly::VALUE_STACK))
85e040533eSDan Gohman     MI->addOperand(MachineOperand::CreateReg(WebAssembly::VALUE_STACK,
86b0992dafSDan Gohman                                              /*isDef=*/false,
87b0992dafSDan Gohman                                              /*isImp=*/true));
88b0992dafSDan Gohman }
89b0992dafSDan Gohman 
902644d74bSDan Gohman // Determine whether a call to the callee referenced by
912644d74bSDan Gohman // MI->getOperand(CalleeOpNo) reads memory, writes memory, and/or has side
922644d74bSDan Gohman // effects.
93500d0469SDuncan P. N. Exon Smith static void QueryCallee(const MachineInstr &MI, unsigned CalleeOpNo, bool &Read,
94500d0469SDuncan P. N. Exon Smith                         bool &Write, bool &Effects, bool &StackPointer) {
95d08cd15fSDan Gohman   // All calls can use the stack pointer.
96d08cd15fSDan Gohman   StackPointer = true;
97d08cd15fSDan Gohman 
98500d0469SDuncan P. N. Exon Smith   const MachineOperand &MO = MI.getOperand(CalleeOpNo);
992644d74bSDan Gohman   if (MO.isGlobal()) {
1002644d74bSDan Gohman     const Constant *GV = MO.getGlobal();
1012644d74bSDan Gohman     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
1022644d74bSDan Gohman       if (!GA->isInterposable())
1032644d74bSDan Gohman         GV = GA->getAliasee();
1042644d74bSDan Gohman 
1052644d74bSDan Gohman     if (const Function *F = dyn_cast<Function>(GV)) {
1062644d74bSDan Gohman       if (!F->doesNotThrow())
1072644d74bSDan Gohman         Effects = true;
1082644d74bSDan Gohman       if (F->doesNotAccessMemory())
1092644d74bSDan Gohman         return;
1102644d74bSDan Gohman       if (F->onlyReadsMemory()) {
1112644d74bSDan Gohman         Read = true;
1122644d74bSDan Gohman         return;
1132644d74bSDan Gohman       }
1142644d74bSDan Gohman     }
1152644d74bSDan Gohman   }
1162644d74bSDan Gohman 
1172644d74bSDan Gohman   // Assume the worst.
1182644d74bSDan Gohman   Write = true;
1192644d74bSDan Gohman   Read = true;
1202644d74bSDan Gohman   Effects = true;
1212644d74bSDan Gohman }
1222644d74bSDan Gohman 
123d08cd15fSDan Gohman // Determine whether MI reads memory, writes memory, has side effects,
124d08cd15fSDan Gohman // and/or uses the __stack_pointer value.
125500d0469SDuncan P. N. Exon Smith static void Query(const MachineInstr &MI, AliasAnalysis &AA, bool &Read,
126500d0469SDuncan P. N. Exon Smith                   bool &Write, bool &Effects, bool &StackPointer) {
127500d0469SDuncan P. N. Exon Smith   assert(!MI.isPosition());
128500d0469SDuncan P. N. Exon Smith   assert(!MI.isTerminator());
1296c8f20d7SDan Gohman 
130500d0469SDuncan P. N. Exon Smith   if (MI.isDebugValue())
1316c8f20d7SDan Gohman     return;
1322644d74bSDan Gohman 
1332644d74bSDan Gohman   // Check for loads.
134d98cf00cSJustin Lebar   if (MI.mayLoad() && !MI.isDereferenceableInvariantLoad(&AA))
1352644d74bSDan Gohman     Read = true;
1362644d74bSDan Gohman 
1372644d74bSDan Gohman   // Check for stores.
138500d0469SDuncan P. N. Exon Smith   if (MI.mayStore()) {
1392644d74bSDan Gohman     Write = true;
140d08cd15fSDan Gohman 
141d08cd15fSDan Gohman     // Check for stores to __stack_pointer.
142500d0469SDuncan P. N. Exon Smith     for (auto MMO : MI.memoperands()) {
143d08cd15fSDan Gohman       const MachinePointerInfo &MPI = MMO->getPointerInfo();
144d08cd15fSDan Gohman       if (MPI.V.is<const PseudoSourceValue *>()) {
145d08cd15fSDan Gohman         auto PSV = MPI.V.get<const PseudoSourceValue *>();
146d08cd15fSDan Gohman         if (const ExternalSymbolPseudoSourceValue *EPSV =
147d08cd15fSDan Gohman                 dyn_cast<ExternalSymbolPseudoSourceValue>(PSV))
148d08cd15fSDan Gohman           if (StringRef(EPSV->getSymbol()) == "__stack_pointer")
149d08cd15fSDan Gohman             StackPointer = true;
150d08cd15fSDan Gohman       }
151d08cd15fSDan Gohman     }
152500d0469SDuncan P. N. Exon Smith   } else if (MI.hasOrderedMemoryRef()) {
153500d0469SDuncan P. N. Exon Smith     switch (MI.getOpcode()) {
1542644d74bSDan Gohman     case WebAssembly::DIV_S_I32: case WebAssembly::DIV_S_I64:
1552644d74bSDan Gohman     case WebAssembly::REM_S_I32: case WebAssembly::REM_S_I64:
1562644d74bSDan Gohman     case WebAssembly::DIV_U_I32: case WebAssembly::DIV_U_I64:
1572644d74bSDan Gohman     case WebAssembly::REM_U_I32: case WebAssembly::REM_U_I64:
1582644d74bSDan Gohman     case WebAssembly::I32_TRUNC_S_F32: case WebAssembly::I64_TRUNC_S_F32:
1592644d74bSDan Gohman     case WebAssembly::I32_TRUNC_S_F64: case WebAssembly::I64_TRUNC_S_F64:
1602644d74bSDan Gohman     case WebAssembly::I32_TRUNC_U_F32: case WebAssembly::I64_TRUNC_U_F32:
1612644d74bSDan Gohman     case WebAssembly::I32_TRUNC_U_F64: case WebAssembly::I64_TRUNC_U_F64:
1622644d74bSDan Gohman       // These instruction have hasUnmodeledSideEffects() returning true
1632644d74bSDan Gohman       // because they trap on overflow and invalid so they can't be arbitrarily
1642644d74bSDan Gohman       // moved, however hasOrderedMemoryRef() interprets this plus their lack
1652644d74bSDan Gohman       // of memoperands as having a potential unknown memory reference.
1662644d74bSDan Gohman       break;
1672644d74bSDan Gohman     default:
1681054570aSDan Gohman       // Record volatile accesses, unless it's a call, as calls are handled
1692644d74bSDan Gohman       // specially below.
170500d0469SDuncan P. N. Exon Smith       if (!MI.isCall()) {
1712644d74bSDan Gohman         Write = true;
1721054570aSDan Gohman         Effects = true;
1731054570aSDan Gohman       }
1742644d74bSDan Gohman       break;
1752644d74bSDan Gohman     }
1762644d74bSDan Gohman   }
1772644d74bSDan Gohman 
1782644d74bSDan Gohman   // Check for side effects.
179500d0469SDuncan P. N. Exon Smith   if (MI.hasUnmodeledSideEffects()) {
180500d0469SDuncan P. N. Exon Smith     switch (MI.getOpcode()) {
1812644d74bSDan Gohman     case WebAssembly::DIV_S_I32: case WebAssembly::DIV_S_I64:
1822644d74bSDan Gohman     case WebAssembly::REM_S_I32: case WebAssembly::REM_S_I64:
1832644d74bSDan Gohman     case WebAssembly::DIV_U_I32: case WebAssembly::DIV_U_I64:
1842644d74bSDan Gohman     case WebAssembly::REM_U_I32: case WebAssembly::REM_U_I64:
1852644d74bSDan Gohman     case WebAssembly::I32_TRUNC_S_F32: case WebAssembly::I64_TRUNC_S_F32:
1862644d74bSDan Gohman     case WebAssembly::I32_TRUNC_S_F64: case WebAssembly::I64_TRUNC_S_F64:
1872644d74bSDan Gohman     case WebAssembly::I32_TRUNC_U_F32: case WebAssembly::I64_TRUNC_U_F32:
1882644d74bSDan Gohman     case WebAssembly::I32_TRUNC_U_F64: case WebAssembly::I64_TRUNC_U_F64:
1892644d74bSDan Gohman       // These instructions have hasUnmodeledSideEffects() returning true
1902644d74bSDan Gohman       // because they trap on overflow and invalid so they can't be arbitrarily
1912644d74bSDan Gohman       // moved, however in the specific case of register stackifying, it is safe
1922644d74bSDan Gohman       // to move them because overflow and invalid are Undefined Behavior.
1932644d74bSDan Gohman       break;
1942644d74bSDan Gohman     default:
1952644d74bSDan Gohman       Effects = true;
1962644d74bSDan Gohman       break;
1972644d74bSDan Gohman     }
1982644d74bSDan Gohman   }
1992644d74bSDan Gohman 
2002644d74bSDan Gohman   // Analyze calls.
201500d0469SDuncan P. N. Exon Smith   if (MI.isCall()) {
202500d0469SDuncan P. N. Exon Smith     switch (MI.getOpcode()) {
2032644d74bSDan Gohman     case WebAssembly::CALL_VOID:
2041054570aSDan Gohman     case WebAssembly::CALL_INDIRECT_VOID:
205d08cd15fSDan Gohman       QueryCallee(MI, 0, Read, Write, Effects, StackPointer);
2062644d74bSDan Gohman       break;
2071054570aSDan Gohman     case WebAssembly::CALL_I32: case WebAssembly::CALL_I64:
2081054570aSDan Gohman     case WebAssembly::CALL_F32: case WebAssembly::CALL_F64:
2091054570aSDan Gohman     case WebAssembly::CALL_INDIRECT_I32: case WebAssembly::CALL_INDIRECT_I64:
2101054570aSDan Gohman     case WebAssembly::CALL_INDIRECT_F32: case WebAssembly::CALL_INDIRECT_F64:
211d08cd15fSDan Gohman       QueryCallee(MI, 1, Read, Write, Effects, StackPointer);
2122644d74bSDan Gohman       break;
2132644d74bSDan Gohman     default:
2142644d74bSDan Gohman       llvm_unreachable("unexpected call opcode");
2152644d74bSDan Gohman     }
2162644d74bSDan Gohman   }
2172644d74bSDan Gohman }
2182644d74bSDan Gohman 
2192644d74bSDan Gohman // Test whether Def is safe and profitable to rematerialize.
2209cfc75c2SDuncan P. N. Exon Smith static bool ShouldRematerialize(const MachineInstr &Def, AliasAnalysis &AA,
2212644d74bSDan Gohman                                 const WebAssemblyInstrInfo *TII) {
2229cfc75c2SDuncan P. N. Exon Smith   return Def.isAsCheapAsAMove() && TII->isTriviallyReMaterializable(Def, &AA);
2232644d74bSDan Gohman }
2242644d74bSDan Gohman 
22512de0b91SDan Gohman // Identify the definition for this register at this point. This is a
22612de0b91SDan Gohman // generalization of MachineRegisterInfo::getUniqueVRegDef that uses
22712de0b91SDan Gohman // LiveIntervals to handle complex cases.
2282644d74bSDan Gohman static MachineInstr *GetVRegDef(unsigned Reg, const MachineInstr *Insert,
2292644d74bSDan Gohman                                 const MachineRegisterInfo &MRI,
2302644d74bSDan Gohman                                 const LiveIntervals &LIS)
2312644d74bSDan Gohman {
2322644d74bSDan Gohman   // Most registers are in SSA form here so we try a quick MRI query first.
2332644d74bSDan Gohman   if (MachineInstr *Def = MRI.getUniqueVRegDef(Reg))
2342644d74bSDan Gohman     return Def;
2352644d74bSDan Gohman 
2362644d74bSDan Gohman   // MRI doesn't know what the Def is. Try asking LIS.
2372644d74bSDan Gohman   if (const VNInfo *ValNo = LIS.getInterval(Reg).getVNInfoBefore(
2382644d74bSDan Gohman           LIS.getInstructionIndex(*Insert)))
2392644d74bSDan Gohman     return LIS.getInstructionFromIndex(ValNo->def);
2402644d74bSDan Gohman 
2412644d74bSDan Gohman   return nullptr;
2422644d74bSDan Gohman }
2432644d74bSDan Gohman 
24412de0b91SDan Gohman // Test whether Reg, as defined at Def, has exactly one use. This is a
24512de0b91SDan Gohman // generalization of MachineRegisterInfo::hasOneUse that uses LiveIntervals
24612de0b91SDan Gohman // to handle complex cases.
24712de0b91SDan Gohman static bool HasOneUse(unsigned Reg, MachineInstr *Def,
24812de0b91SDan Gohman                       MachineRegisterInfo &MRI, MachineDominatorTree &MDT,
24912de0b91SDan Gohman                       LiveIntervals &LIS) {
25012de0b91SDan Gohman   // Most registers are in SSA form here so we try a quick MRI query first.
25112de0b91SDan Gohman   if (MRI.hasOneUse(Reg))
25212de0b91SDan Gohman     return true;
25312de0b91SDan Gohman 
25412de0b91SDan Gohman   bool HasOne = false;
25512de0b91SDan Gohman   const LiveInterval &LI = LIS.getInterval(Reg);
25612de0b91SDan Gohman   const VNInfo *DefVNI = LI.getVNInfoAt(
25712de0b91SDan Gohman       LIS.getInstructionIndex(*Def).getRegSlot());
25812de0b91SDan Gohman   assert(DefVNI);
259a8a63829SDominic Chen   for (auto &I : MRI.use_nodbg_operands(Reg)) {
26012de0b91SDan Gohman     const auto &Result = LI.Query(LIS.getInstructionIndex(*I.getParent()));
26112de0b91SDan Gohman     if (Result.valueIn() == DefVNI) {
26212de0b91SDan Gohman       if (!Result.isKill())
26312de0b91SDan Gohman         return false;
26412de0b91SDan Gohman       if (HasOne)
26512de0b91SDan Gohman         return false;
26612de0b91SDan Gohman       HasOne = true;
26712de0b91SDan Gohman     }
26812de0b91SDan Gohman   }
26912de0b91SDan Gohman   return HasOne;
27012de0b91SDan Gohman }
27112de0b91SDan Gohman 
2728887d1faSDan Gohman // Test whether it's safe to move Def to just before Insert.
27381719f85SDan Gohman // TODO: Compute memory dependencies in a way that doesn't require always
27481719f85SDan Gohman // walking the block.
27581719f85SDan Gohman // TODO: Compute memory dependencies in a way that uses AliasAnalysis to be
27681719f85SDan Gohman // more precise.
27781719f85SDan Gohman static bool IsSafeToMove(const MachineInstr *Def, const MachineInstr *Insert,
278e9e6891bSDerek Schuff                          AliasAnalysis &AA, const MachineRegisterInfo &MRI) {
279391a98afSDan Gohman   assert(Def->getParent() == Insert->getParent());
2808887d1faSDan Gohman 
2818887d1faSDan Gohman   // Check for register dependencies.
282e9e6891bSDerek Schuff   SmallVector<unsigned, 4> MutableRegisters;
2838887d1faSDan Gohman   for (const MachineOperand &MO : Def->operands()) {
2848887d1faSDan Gohman     if (!MO.isReg() || MO.isUndef())
2858887d1faSDan Gohman       continue;
2868887d1faSDan Gohman     unsigned Reg = MO.getReg();
2878887d1faSDan Gohman 
2888887d1faSDan Gohman     // If the register is dead here and at Insert, ignore it.
2898887d1faSDan Gohman     if (MO.isDead() && Insert->definesRegister(Reg) &&
2908887d1faSDan Gohman         !Insert->readsRegister(Reg))
2918887d1faSDan Gohman       continue;
2928887d1faSDan Gohman 
2938887d1faSDan Gohman     if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
2940cfb5f85SDan Gohman       // Ignore ARGUMENTS; it's just used to keep the ARGUMENT_* instructions
2950cfb5f85SDan Gohman       // from moving down, and we've already checked for that.
2960cfb5f85SDan Gohman       if (Reg == WebAssembly::ARGUMENTS)
2970cfb5f85SDan Gohman         continue;
2988887d1faSDan Gohman       // If the physical register is never modified, ignore it.
2998887d1faSDan Gohman       if (!MRI.isPhysRegModified(Reg))
3008887d1faSDan Gohman         continue;
3018887d1faSDan Gohman       // Otherwise, it's a physical register with unknown liveness.
3028887d1faSDan Gohman       return false;
3038887d1faSDan Gohman     }
3048887d1faSDan Gohman 
305e9e6891bSDerek Schuff     // If one of the operands isn't in SSA form, it has different values at
306e9e6891bSDerek Schuff     // different times, and we need to make sure we don't move our use across
307e9e6891bSDerek Schuff     // a different def.
308e9e6891bSDerek Schuff     if (!MO.isDef() && !MRI.hasOneDef(Reg))
309e9e6891bSDerek Schuff       MutableRegisters.push_back(Reg);
3108887d1faSDan Gohman   }
3118887d1faSDan Gohman 
312d08cd15fSDan Gohman   bool Read = false, Write = false, Effects = false, StackPointer = false;
313500d0469SDuncan P. N. Exon Smith   Query(*Def, AA, Read, Write, Effects, StackPointer);
3142644d74bSDan Gohman 
3152644d74bSDan Gohman   // If the instruction does not access memory and has no side effects, it has
3162644d74bSDan Gohman   // no additional dependencies.
317e9e6891bSDerek Schuff   bool HasMutableRegisters = !MutableRegisters.empty();
318e9e6891bSDerek Schuff   if (!Read && !Write && !Effects && !StackPointer && !HasMutableRegisters)
3192644d74bSDan Gohman     return true;
3202644d74bSDan Gohman 
3212644d74bSDan Gohman   // Scan through the intervening instructions between Def and Insert.
3222644d74bSDan Gohman   MachineBasicBlock::const_iterator D(Def), I(Insert);
3232644d74bSDan Gohman   for (--I; I != D; --I) {
3242644d74bSDan Gohman     bool InterveningRead = false;
3252644d74bSDan Gohman     bool InterveningWrite = false;
3262644d74bSDan Gohman     bool InterveningEffects = false;
327d08cd15fSDan Gohman     bool InterveningStackPointer = false;
328500d0469SDuncan P. N. Exon Smith     Query(*I, AA, InterveningRead, InterveningWrite, InterveningEffects,
329d08cd15fSDan Gohman           InterveningStackPointer);
3302644d74bSDan Gohman     if (Effects && InterveningEffects)
3312644d74bSDan Gohman       return false;
3322644d74bSDan Gohman     if (Read && InterveningWrite)
3332644d74bSDan Gohman       return false;
3342644d74bSDan Gohman     if (Write && (InterveningRead || InterveningWrite))
3352644d74bSDan Gohman       return false;
336d08cd15fSDan Gohman     if (StackPointer && InterveningStackPointer)
337d08cd15fSDan Gohman       return false;
338e9e6891bSDerek Schuff 
339e9e6891bSDerek Schuff     for (unsigned Reg : MutableRegisters)
340e9e6891bSDerek Schuff       for (const MachineOperand &MO : I->operands())
341e9e6891bSDerek Schuff         if (MO.isReg() && MO.isDef() && MO.getReg() == Reg)
342e9e6891bSDerek Schuff           return false;
3432644d74bSDan Gohman   }
3442644d74bSDan Gohman 
3452644d74bSDan Gohman   return true;
34681719f85SDan Gohman }
34781719f85SDan Gohman 
348adf28177SDan Gohman /// Test whether OneUse, a use of Reg, dominates all of Reg's other uses.
349adf28177SDan Gohman static bool OneUseDominatesOtherUses(unsigned Reg, const MachineOperand &OneUse,
350adf28177SDan Gohman                                      const MachineBasicBlock &MBB,
351adf28177SDan Gohman                                      const MachineRegisterInfo &MRI,
3520cfb5f85SDan Gohman                                      const MachineDominatorTree &MDT,
3531054570aSDan Gohman                                      LiveIntervals &LIS,
3541054570aSDan Gohman                                      WebAssemblyFunctionInfo &MFI) {
3550cfb5f85SDan Gohman   const LiveInterval &LI = LIS.getInterval(Reg);
3560cfb5f85SDan Gohman 
3570cfb5f85SDan Gohman   const MachineInstr *OneUseInst = OneUse.getParent();
3580cfb5f85SDan Gohman   VNInfo *OneUseVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*OneUseInst));
3590cfb5f85SDan Gohman 
360a8a63829SDominic Chen   for (const MachineOperand &Use : MRI.use_nodbg_operands(Reg)) {
361adf28177SDan Gohman     if (&Use == &OneUse)
362adf28177SDan Gohman       continue;
3630cfb5f85SDan Gohman 
364adf28177SDan Gohman     const MachineInstr *UseInst = Use.getParent();
3650cfb5f85SDan Gohman     VNInfo *UseVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*UseInst));
3660cfb5f85SDan Gohman 
3670cfb5f85SDan Gohman     if (UseVNI != OneUseVNI)
3680cfb5f85SDan Gohman       continue;
3690cfb5f85SDan Gohman 
370adf28177SDan Gohman     const MachineInstr *OneUseInst = OneUse.getParent();
37112de0b91SDan Gohman     if (UseInst == OneUseInst) {
372adf28177SDan Gohman       // Another use in the same instruction. We need to ensure that the one
373adf28177SDan Gohman       // selected use happens "before" it.
374adf28177SDan Gohman       if (&OneUse > &Use)
375adf28177SDan Gohman         return false;
376adf28177SDan Gohman     } else {
377adf28177SDan Gohman       // Test that the use is dominated by the one selected use.
3781054570aSDan Gohman       while (!MDT.dominates(OneUseInst, UseInst)) {
3791054570aSDan Gohman         // Actually, dominating is over-conservative. Test that the use would
3801054570aSDan Gohman         // happen after the one selected use in the stack evaluation order.
3811054570aSDan Gohman         //
3821054570aSDan Gohman         // This is needed as a consequence of using implicit get_locals for
3831054570aSDan Gohman         // uses and implicit set_locals for defs.
3841054570aSDan Gohman         if (UseInst->getDesc().getNumDefs() == 0)
385adf28177SDan Gohman           return false;
3861054570aSDan Gohman         const MachineOperand &MO = UseInst->getOperand(0);
3871054570aSDan Gohman         if (!MO.isReg())
3881054570aSDan Gohman           return false;
3891054570aSDan Gohman         unsigned DefReg = MO.getReg();
3901054570aSDan Gohman         if (!TargetRegisterInfo::isVirtualRegister(DefReg) ||
3911054570aSDan Gohman             !MFI.isVRegStackified(DefReg))
3921054570aSDan Gohman           return false;
3931054570aSDan Gohman         assert(MRI.hasOneUse(DefReg));
3941054570aSDan Gohman         const MachineOperand &NewUse = *MRI.use_begin(DefReg);
3951054570aSDan Gohman         const MachineInstr *NewUseInst = NewUse.getParent();
3961054570aSDan Gohman         if (NewUseInst == OneUseInst) {
3971054570aSDan Gohman           if (&OneUse > &NewUse)
3981054570aSDan Gohman             return false;
3991054570aSDan Gohman           break;
4001054570aSDan Gohman         }
4011054570aSDan Gohman         UseInst = NewUseInst;
4021054570aSDan Gohman       }
403adf28177SDan Gohman     }
404adf28177SDan Gohman   }
405adf28177SDan Gohman   return true;
406adf28177SDan Gohman }
407adf28177SDan Gohman 
408*4fc4e42dSDan Gohman /// Get the appropriate tee opcode for the given register class.
409*4fc4e42dSDan Gohman static unsigned GetTeeOpcode(const TargetRegisterClass *RC) {
410adf28177SDan Gohman   if (RC == &WebAssembly::I32RegClass)
411*4fc4e42dSDan Gohman     return WebAssembly::TEE_I32;
412adf28177SDan Gohman   if (RC == &WebAssembly::I64RegClass)
413*4fc4e42dSDan Gohman     return WebAssembly::TEE_I64;
414adf28177SDan Gohman   if (RC == &WebAssembly::F32RegClass)
415*4fc4e42dSDan Gohman     return WebAssembly::TEE_F32;
416adf28177SDan Gohman   if (RC == &WebAssembly::F64RegClass)
417*4fc4e42dSDan Gohman     return WebAssembly::TEE_F64;
41839bf39f3SDerek Schuff   if (RC == &WebAssembly::V128RegClass)
419*4fc4e42dSDan Gohman     return WebAssembly::TEE_V128;
420adf28177SDan Gohman   llvm_unreachable("Unexpected register class");
421adf28177SDan Gohman }
422adf28177SDan Gohman 
4232644d74bSDan Gohman // Shrink LI to its uses, cleaning up LI.
4242644d74bSDan Gohman static void ShrinkToUses(LiveInterval &LI, LiveIntervals &LIS) {
4252644d74bSDan Gohman   if (LIS.shrinkToUses(&LI)) {
4262644d74bSDan Gohman     SmallVector<LiveInterval*, 4> SplitLIs;
4272644d74bSDan Gohman     LIS.splitSeparateComponents(LI, SplitLIs);
4282644d74bSDan Gohman   }
4292644d74bSDan Gohman }
4302644d74bSDan Gohman 
431adf28177SDan Gohman /// A single-use def in the same block with no intervening memory or register
432adf28177SDan Gohman /// dependencies; move the def down and nest it with the current instruction.
4330cfb5f85SDan Gohman static MachineInstr *MoveForSingleUse(unsigned Reg, MachineOperand& Op,
4340cfb5f85SDan Gohman                                       MachineInstr *Def,
435adf28177SDan Gohman                                       MachineBasicBlock &MBB,
436adf28177SDan Gohman                                       MachineInstr *Insert, LiveIntervals &LIS,
4370cfb5f85SDan Gohman                                       WebAssemblyFunctionInfo &MFI,
4380cfb5f85SDan Gohman                                       MachineRegisterInfo &MRI) {
4392644d74bSDan Gohman   DEBUG(dbgs() << "Move for single use: "; Def->dump());
4402644d74bSDan Gohman 
441adf28177SDan Gohman   MBB.splice(Insert, &MBB, Def);
4421afd1e2bSJF Bastien   LIS.handleMove(*Def);
4430cfb5f85SDan Gohman 
44412de0b91SDan Gohman   if (MRI.hasOneDef(Reg) && MRI.hasOneUse(Reg)) {
44512de0b91SDan Gohman     // No one else is using this register for anything so we can just stackify
44612de0b91SDan Gohman     // it in place.
447adf28177SDan Gohman     MFI.stackifyVReg(Reg);
4480cfb5f85SDan Gohman   } else {
44912de0b91SDan Gohman     // The register may have unrelated uses or defs; create a new register for
45012de0b91SDan Gohman     // just our one def and use so that we can stackify it.
4510cfb5f85SDan Gohman     unsigned NewReg = MRI.createVirtualRegister(MRI.getRegClass(Reg));
4520cfb5f85SDan Gohman     Def->getOperand(0).setReg(NewReg);
4530cfb5f85SDan Gohman     Op.setReg(NewReg);
4540cfb5f85SDan Gohman 
4550cfb5f85SDan Gohman     // Tell LiveIntervals about the new register.
4560cfb5f85SDan Gohman     LIS.createAndComputeVirtRegInterval(NewReg);
4570cfb5f85SDan Gohman 
4580cfb5f85SDan Gohman     // Tell LiveIntervals about the changes to the old register.
4590cfb5f85SDan Gohman     LiveInterval &LI = LIS.getInterval(Reg);
4606c8f20d7SDan Gohman     LI.removeSegment(LIS.getInstructionIndex(*Def).getRegSlot(),
4616c8f20d7SDan Gohman                      LIS.getInstructionIndex(*Op.getParent()).getRegSlot(),
4626c8f20d7SDan Gohman                      /*RemoveDeadValNo=*/true);
4630cfb5f85SDan Gohman 
4640cfb5f85SDan Gohman     MFI.stackifyVReg(NewReg);
4652644d74bSDan Gohman 
4662644d74bSDan Gohman     DEBUG(dbgs() << " - Replaced register: "; Def->dump());
4670cfb5f85SDan Gohman   }
4680cfb5f85SDan Gohman 
469adf28177SDan Gohman   ImposeStackOrdering(Def);
470adf28177SDan Gohman   return Def;
471adf28177SDan Gohman }
472adf28177SDan Gohman 
473adf28177SDan Gohman /// A trivially cloneable instruction; clone it and nest the new copy with the
474adf28177SDan Gohman /// current instruction.
4759cfc75c2SDuncan P. N. Exon Smith static MachineInstr *RematerializeCheapDef(
4769cfc75c2SDuncan P. N. Exon Smith     unsigned Reg, MachineOperand &Op, MachineInstr &Def, MachineBasicBlock &MBB,
4779cfc75c2SDuncan P. N. Exon Smith     MachineBasicBlock::instr_iterator Insert, LiveIntervals &LIS,
4789cfc75c2SDuncan P. N. Exon Smith     WebAssemblyFunctionInfo &MFI, MachineRegisterInfo &MRI,
4799cfc75c2SDuncan P. N. Exon Smith     const WebAssemblyInstrInfo *TII, const WebAssemblyRegisterInfo *TRI) {
4809cfc75c2SDuncan P. N. Exon Smith   DEBUG(dbgs() << "Rematerializing cheap def: "; Def.dump());
4812644d74bSDan Gohman   DEBUG(dbgs() << " - for use in "; Op.getParent()->dump());
4822644d74bSDan Gohman 
483adf28177SDan Gohman   unsigned NewReg = MRI.createVirtualRegister(MRI.getRegClass(Reg));
484adf28177SDan Gohman   TII->reMaterialize(MBB, Insert, NewReg, 0, Def, *TRI);
485adf28177SDan Gohman   Op.setReg(NewReg);
4869cfc75c2SDuncan P. N. Exon Smith   MachineInstr *Clone = &*std::prev(Insert);
48713d3b9b7SJF Bastien   LIS.InsertMachineInstrInMaps(*Clone);
488adf28177SDan Gohman   LIS.createAndComputeVirtRegInterval(NewReg);
489adf28177SDan Gohman   MFI.stackifyVReg(NewReg);
490adf28177SDan Gohman   ImposeStackOrdering(Clone);
491adf28177SDan Gohman 
4922644d74bSDan Gohman   DEBUG(dbgs() << " - Cloned to "; Clone->dump());
4932644d74bSDan Gohman 
4940cfb5f85SDan Gohman   // Shrink the interval.
4950cfb5f85SDan Gohman   bool IsDead = MRI.use_empty(Reg);
4960cfb5f85SDan Gohman   if (!IsDead) {
4970cfb5f85SDan Gohman     LiveInterval &LI = LIS.getInterval(Reg);
4982644d74bSDan Gohman     ShrinkToUses(LI, LIS);
4999cfc75c2SDuncan P. N. Exon Smith     IsDead = !LI.liveAt(LIS.getInstructionIndex(Def).getDeadSlot());
5000cfb5f85SDan Gohman   }
5010cfb5f85SDan Gohman 
502adf28177SDan Gohman   // If that was the last use of the original, delete the original.
5030cfb5f85SDan Gohman   if (IsDead) {
5042644d74bSDan Gohman     DEBUG(dbgs() << " - Deleting original\n");
5059cfc75c2SDuncan P. N. Exon Smith     SlotIndex Idx = LIS.getInstructionIndex(Def).getRegSlot();
506adf28177SDan Gohman     LIS.removePhysRegDefAt(WebAssembly::ARGUMENTS, Idx);
507adf28177SDan Gohman     LIS.removeInterval(Reg);
5089cfc75c2SDuncan P. N. Exon Smith     LIS.RemoveMachineInstrFromMaps(Def);
5099cfc75c2SDuncan P. N. Exon Smith     Def.eraseFromParent();
510adf28177SDan Gohman   }
5110cfb5f85SDan Gohman 
512adf28177SDan Gohman   return Clone;
513adf28177SDan Gohman }
514adf28177SDan Gohman 
515adf28177SDan Gohman /// A multiple-use def in the same block with no intervening memory or register
516adf28177SDan Gohman /// dependencies; move the def down, nest it with the current instruction, and
517*4fc4e42dSDan Gohman /// insert a tee to satisfy the rest of the uses. As an illustration, rewrite
518*4fc4e42dSDan Gohman /// this:
519adf28177SDan Gohman ///
520adf28177SDan Gohman ///    Reg = INST ...        // Def
521adf28177SDan Gohman ///    INST ..., Reg, ...    // Insert
522adf28177SDan Gohman ///    INST ..., Reg, ...
523adf28177SDan Gohman ///    INST ..., Reg, ...
524adf28177SDan Gohman ///
525adf28177SDan Gohman /// to this:
526adf28177SDan Gohman ///
5278aa237c3SDan Gohman ///    DefReg = INST ...     // Def (to become the new Insert)
528*4fc4e42dSDan Gohman ///    TeeReg, Reg = TEE_... DefReg
529adf28177SDan Gohman ///    INST ..., TeeReg, ... // Insert
5306c8f20d7SDan Gohman ///    INST ..., Reg, ...
5316c8f20d7SDan Gohman ///    INST ..., Reg, ...
532adf28177SDan Gohman ///
5338aa237c3SDan Gohman /// with DefReg and TeeReg stackified. This eliminates a get_local from the
534adf28177SDan Gohman /// resulting code.
535adf28177SDan Gohman static MachineInstr *MoveAndTeeForMultiUse(
536adf28177SDan Gohman     unsigned Reg, MachineOperand &Op, MachineInstr *Def, MachineBasicBlock &MBB,
537adf28177SDan Gohman     MachineInstr *Insert, LiveIntervals &LIS, WebAssemblyFunctionInfo &MFI,
538adf28177SDan Gohman     MachineRegisterInfo &MRI, const WebAssemblyInstrInfo *TII) {
5392644d74bSDan Gohman   DEBUG(dbgs() << "Move and tee for multi-use:"; Def->dump());
5402644d74bSDan Gohman 
54112de0b91SDan Gohman   // Move Def into place.
542adf28177SDan Gohman   MBB.splice(Insert, &MBB, Def);
5431afd1e2bSJF Bastien   LIS.handleMove(*Def);
54412de0b91SDan Gohman 
54512de0b91SDan Gohman   // Create the Tee and attach the registers.
546adf28177SDan Gohman   const auto *RegClass = MRI.getRegClass(Reg);
547adf28177SDan Gohman   unsigned TeeReg = MRI.createVirtualRegister(RegClass);
5488aa237c3SDan Gohman   unsigned DefReg = MRI.createVirtualRegister(RegClass);
54933e694a8SDan Gohman   MachineOperand &DefMO = Def->getOperand(0);
550adf28177SDan Gohman   MachineInstr *Tee = BuildMI(MBB, Insert, Insert->getDebugLoc(),
551*4fc4e42dSDan Gohman                               TII->get(GetTeeOpcode(RegClass)), TeeReg)
55212de0b91SDan Gohman                           .addReg(Reg, RegState::Define)
55333e694a8SDan Gohman                           .addReg(DefReg, getUndefRegState(DefMO.isDead()));
554adf28177SDan Gohman   Op.setReg(TeeReg);
55533e694a8SDan Gohman   DefMO.setReg(DefReg);
55612de0b91SDan Gohman   SlotIndex TeeIdx = LIS.InsertMachineInstrInMaps(*Tee).getRegSlot();
55712de0b91SDan Gohman   SlotIndex DefIdx = LIS.getInstructionIndex(*Def).getRegSlot();
55812de0b91SDan Gohman 
55912de0b91SDan Gohman   // Tell LiveIntervals we moved the original vreg def from Def to Tee.
56012de0b91SDan Gohman   LiveInterval &LI = LIS.getInterval(Reg);
56112de0b91SDan Gohman   LiveInterval::iterator I = LI.FindSegmentContaining(DefIdx);
56212de0b91SDan Gohman   VNInfo *ValNo = LI.getVNInfoAt(DefIdx);
56312de0b91SDan Gohman   I->start = TeeIdx;
56412de0b91SDan Gohman   ValNo->def = TeeIdx;
56512de0b91SDan Gohman   ShrinkToUses(LI, LIS);
56612de0b91SDan Gohman 
56712de0b91SDan Gohman   // Finish stackifying the new regs.
568adf28177SDan Gohman   LIS.createAndComputeVirtRegInterval(TeeReg);
5698aa237c3SDan Gohman   LIS.createAndComputeVirtRegInterval(DefReg);
5708aa237c3SDan Gohman   MFI.stackifyVReg(DefReg);
571adf28177SDan Gohman   MFI.stackifyVReg(TeeReg);
572adf28177SDan Gohman   ImposeStackOrdering(Def);
573adf28177SDan Gohman   ImposeStackOrdering(Tee);
57412de0b91SDan Gohman 
57512de0b91SDan Gohman   DEBUG(dbgs() << " - Replaced register: "; Def->dump());
57612de0b91SDan Gohman   DEBUG(dbgs() << " - Tee instruction: "; Tee->dump());
577adf28177SDan Gohman   return Def;
578adf28177SDan Gohman }
579adf28177SDan Gohman 
580adf28177SDan Gohman namespace {
581adf28177SDan Gohman /// A stack for walking the tree of instructions being built, visiting the
582adf28177SDan Gohman /// MachineOperands in DFS order.
583adf28177SDan Gohman class TreeWalkerState {
584adf28177SDan Gohman   typedef MachineInstr::mop_iterator mop_iterator;
585adf28177SDan Gohman   typedef std::reverse_iterator<mop_iterator> mop_reverse_iterator;
586adf28177SDan Gohman   typedef iterator_range<mop_reverse_iterator> RangeTy;
587adf28177SDan Gohman   SmallVector<RangeTy, 4> Worklist;
588adf28177SDan Gohman 
589adf28177SDan Gohman public:
590adf28177SDan Gohman   explicit TreeWalkerState(MachineInstr *Insert) {
591adf28177SDan Gohman     const iterator_range<mop_iterator> &Range = Insert->explicit_uses();
592adf28177SDan Gohman     if (Range.begin() != Range.end())
593adf28177SDan Gohman       Worklist.push_back(reverse(Range));
594adf28177SDan Gohman   }
595adf28177SDan Gohman 
596adf28177SDan Gohman   bool Done() const { return Worklist.empty(); }
597adf28177SDan Gohman 
598adf28177SDan Gohman   MachineOperand &Pop() {
599adf28177SDan Gohman     RangeTy &Range = Worklist.back();
600adf28177SDan Gohman     MachineOperand &Op = *Range.begin();
601adf28177SDan Gohman     Range = drop_begin(Range, 1);
602adf28177SDan Gohman     if (Range.begin() == Range.end())
603adf28177SDan Gohman       Worklist.pop_back();
604adf28177SDan Gohman     assert((Worklist.empty() ||
605adf28177SDan Gohman             Worklist.back().begin() != Worklist.back().end()) &&
606adf28177SDan Gohman            "Empty ranges shouldn't remain in the worklist");
607adf28177SDan Gohman     return Op;
608adf28177SDan Gohman   }
609adf28177SDan Gohman 
610adf28177SDan Gohman   /// Push Instr's operands onto the stack to be visited.
611adf28177SDan Gohman   void PushOperands(MachineInstr *Instr) {
612adf28177SDan Gohman     const iterator_range<mop_iterator> &Range(Instr->explicit_uses());
613adf28177SDan Gohman     if (Range.begin() != Range.end())
614adf28177SDan Gohman       Worklist.push_back(reverse(Range));
615adf28177SDan Gohman   }
616adf28177SDan Gohman 
617adf28177SDan Gohman   /// Some of Instr's operands are on the top of the stack; remove them and
618adf28177SDan Gohman   /// re-insert them starting from the beginning (because we've commuted them).
619adf28177SDan Gohman   void ResetTopOperands(MachineInstr *Instr) {
620adf28177SDan Gohman     assert(HasRemainingOperands(Instr) &&
621adf28177SDan Gohman            "Reseting operands should only be done when the instruction has "
622adf28177SDan Gohman            "an operand still on the stack");
623adf28177SDan Gohman     Worklist.back() = reverse(Instr->explicit_uses());
624adf28177SDan Gohman   }
625adf28177SDan Gohman 
626adf28177SDan Gohman   /// Test whether Instr has operands remaining to be visited at the top of
627adf28177SDan Gohman   /// the stack.
628adf28177SDan Gohman   bool HasRemainingOperands(const MachineInstr *Instr) const {
629adf28177SDan Gohman     if (Worklist.empty())
630adf28177SDan Gohman       return false;
631adf28177SDan Gohman     const RangeTy &Range = Worklist.back();
632adf28177SDan Gohman     return Range.begin() != Range.end() && Range.begin()->getParent() == Instr;
633adf28177SDan Gohman   }
634fbfe5ec4SDan Gohman 
635fbfe5ec4SDan Gohman   /// Test whether the given register is present on the stack, indicating an
636fbfe5ec4SDan Gohman   /// operand in the tree that we haven't visited yet. Moving a definition of
637fbfe5ec4SDan Gohman   /// Reg to a point in the tree after that would change its value.
6381054570aSDan Gohman   ///
6391054570aSDan Gohman   /// This is needed as a consequence of using implicit get_locals for
6401054570aSDan Gohman   /// uses and implicit set_locals for defs.
641fbfe5ec4SDan Gohman   bool IsOnStack(unsigned Reg) const {
642fbfe5ec4SDan Gohman     for (const RangeTy &Range : Worklist)
643fbfe5ec4SDan Gohman       for (const MachineOperand &MO : Range)
644fbfe5ec4SDan Gohman         if (MO.isReg() && MO.getReg() == Reg)
645fbfe5ec4SDan Gohman           return true;
646fbfe5ec4SDan Gohman     return false;
647fbfe5ec4SDan Gohman   }
648adf28177SDan Gohman };
649adf28177SDan Gohman 
650adf28177SDan Gohman /// State to keep track of whether commuting is in flight or whether it's been
651adf28177SDan Gohman /// tried for the current instruction and didn't work.
652adf28177SDan Gohman class CommutingState {
653adf28177SDan Gohman   /// There are effectively three states: the initial state where we haven't
654adf28177SDan Gohman   /// started commuting anything and we don't know anything yet, the tenative
655adf28177SDan Gohman   /// state where we've commuted the operands of the current instruction and are
656adf28177SDan Gohman   /// revisting it, and the declined state where we've reverted the operands
657adf28177SDan Gohman   /// back to their original order and will no longer commute it further.
658adf28177SDan Gohman   bool TentativelyCommuting;
659adf28177SDan Gohman   bool Declined;
660adf28177SDan Gohman 
661adf28177SDan Gohman   /// During the tentative state, these hold the operand indices of the commuted
662adf28177SDan Gohman   /// operands.
663adf28177SDan Gohman   unsigned Operand0, Operand1;
664adf28177SDan Gohman 
665adf28177SDan Gohman public:
666adf28177SDan Gohman   CommutingState() : TentativelyCommuting(false), Declined(false) {}
667adf28177SDan Gohman 
668adf28177SDan Gohman   /// Stackification for an operand was not successful due to ordering
669adf28177SDan Gohman   /// constraints. If possible, and if we haven't already tried it and declined
670adf28177SDan Gohman   /// it, commute Insert's operands and prepare to revisit it.
671adf28177SDan Gohman   void MaybeCommute(MachineInstr *Insert, TreeWalkerState &TreeWalker,
672adf28177SDan Gohman                     const WebAssemblyInstrInfo *TII) {
673adf28177SDan Gohman     if (TentativelyCommuting) {
674adf28177SDan Gohman       assert(!Declined &&
675adf28177SDan Gohman              "Don't decline commuting until you've finished trying it");
676adf28177SDan Gohman       // Commuting didn't help. Revert it.
6779cfc75c2SDuncan P. N. Exon Smith       TII->commuteInstruction(*Insert, /*NewMI=*/false, Operand0, Operand1);
678adf28177SDan Gohman       TentativelyCommuting = false;
679adf28177SDan Gohman       Declined = true;
680adf28177SDan Gohman     } else if (!Declined && TreeWalker.HasRemainingOperands(Insert)) {
681adf28177SDan Gohman       Operand0 = TargetInstrInfo::CommuteAnyOperandIndex;
682adf28177SDan Gohman       Operand1 = TargetInstrInfo::CommuteAnyOperandIndex;
6839cfc75c2SDuncan P. N. Exon Smith       if (TII->findCommutedOpIndices(*Insert, Operand0, Operand1)) {
684adf28177SDan Gohman         // Tentatively commute the operands and try again.
6859cfc75c2SDuncan P. N. Exon Smith         TII->commuteInstruction(*Insert, /*NewMI=*/false, Operand0, Operand1);
686adf28177SDan Gohman         TreeWalker.ResetTopOperands(Insert);
687adf28177SDan Gohman         TentativelyCommuting = true;
688adf28177SDan Gohman         Declined = false;
689adf28177SDan Gohman       }
690adf28177SDan Gohman     }
691adf28177SDan Gohman   }
692adf28177SDan Gohman 
693adf28177SDan Gohman   /// Stackification for some operand was successful. Reset to the default
694adf28177SDan Gohman   /// state.
695adf28177SDan Gohman   void Reset() {
696adf28177SDan Gohman     TentativelyCommuting = false;
697adf28177SDan Gohman     Declined = false;
698adf28177SDan Gohman   }
699adf28177SDan Gohman };
700adf28177SDan Gohman } // end anonymous namespace
701adf28177SDan Gohman 
7021462faadSDan Gohman bool WebAssemblyRegStackify::runOnMachineFunction(MachineFunction &MF) {
7031462faadSDan Gohman   DEBUG(dbgs() << "********** Register Stackifying **********\n"
7041462faadSDan Gohman                   "********** Function: "
7051462faadSDan Gohman                << MF.getName() << '\n');
7061462faadSDan Gohman 
7071462faadSDan Gohman   bool Changed = false;
7081462faadSDan Gohman   MachineRegisterInfo &MRI = MF.getRegInfo();
7091462faadSDan Gohman   WebAssemblyFunctionInfo &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
710b6fd39a3SDan Gohman   const auto *TII = MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
711b6fd39a3SDan Gohman   const auto *TRI = MF.getSubtarget<WebAssemblySubtarget>().getRegisterInfo();
71281719f85SDan Gohman   AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
713adf28177SDan Gohman   MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
7148887d1faSDan Gohman   LiveIntervals &LIS = getAnalysis<LiveIntervals>();
715d70e5907SDan Gohman 
7161462faadSDan Gohman   // Walk the instructions from the bottom up. Currently we don't look past
7171462faadSDan Gohman   // block boundaries, and the blocks aren't ordered so the block visitation
7181462faadSDan Gohman   // order isn't significant, but we may want to change this in the future.
7191462faadSDan Gohman   for (MachineBasicBlock &MBB : MF) {
7208f59cf75SDan Gohman     // Don't use a range-based for loop, because we modify the list as we're
7218f59cf75SDan Gohman     // iterating over it and the end iterator may change.
7228f59cf75SDan Gohman     for (auto MII = MBB.rbegin(); MII != MBB.rend(); ++MII) {
7238f59cf75SDan Gohman       MachineInstr *Insert = &*MII;
72481719f85SDan Gohman       // Don't nest anything inside an inline asm, because we don't have
72581719f85SDan Gohman       // constraints for $push inputs.
72681719f85SDan Gohman       if (Insert->getOpcode() == TargetOpcode::INLINEASM)
727595e8ab2SDan Gohman         continue;
728595e8ab2SDan Gohman 
729595e8ab2SDan Gohman       // Ignore debugging intrinsics.
730595e8ab2SDan Gohman       if (Insert->getOpcode() == TargetOpcode::DBG_VALUE)
731595e8ab2SDan Gohman         continue;
73281719f85SDan Gohman 
7331462faadSDan Gohman       // Iterate through the inputs in reverse order, since we'll be pulling
73453d13997SDan Gohman       // operands off the stack in LIFO order.
735adf28177SDan Gohman       CommutingState Commuting;
736adf28177SDan Gohman       TreeWalkerState TreeWalker(Insert);
737adf28177SDan Gohman       while (!TreeWalker.Done()) {
738adf28177SDan Gohman         MachineOperand &Op = TreeWalker.Pop();
739adf28177SDan Gohman 
7401462faadSDan Gohman         // We're only interested in explicit virtual register operands.
741adf28177SDan Gohman         if (!Op.isReg())
7421462faadSDan Gohman           continue;
7431462faadSDan Gohman 
7441462faadSDan Gohman         unsigned Reg = Op.getReg();
745adf28177SDan Gohman         assert(Op.isUse() && "explicit_uses() should only iterate over uses");
746adf28177SDan Gohman         assert(!Op.isImplicit() &&
747adf28177SDan Gohman                "explicit_uses() should only iterate over explicit operands");
748adf28177SDan Gohman         if (TargetRegisterInfo::isPhysicalRegister(Reg))
749adf28177SDan Gohman           continue;
7501462faadSDan Gohman 
751ffc184bbSDan Gohman         // Identify the definition for this register at this point.
7522644d74bSDan Gohman         MachineInstr *Def = GetVRegDef(Reg, Insert, MRI, LIS);
7531462faadSDan Gohman         if (!Def)
7541462faadSDan Gohman           continue;
7551462faadSDan Gohman 
75681719f85SDan Gohman         // Don't nest an INLINE_ASM def into anything, because we don't have
75781719f85SDan Gohman         // constraints for $pop outputs.
75881719f85SDan Gohman         if (Def->getOpcode() == TargetOpcode::INLINEASM)
75981719f85SDan Gohman           continue;
76081719f85SDan Gohman 
7614ba4816bSDan Gohman         // Argument instructions represent live-in registers and not real
7624ba4816bSDan Gohman         // instructions.
763*4fc4e42dSDan Gohman         if (WebAssembly::isArgument(*Def))
7644ba4816bSDan Gohman           continue;
7654ba4816bSDan Gohman 
766adf28177SDan Gohman         // Decide which strategy to take. Prefer to move a single-use value
767*4fc4e42dSDan Gohman         // over cloning it, and prefer cloning over introducing a tee.
768adf28177SDan Gohman         // For moving, we require the def to be in the same block as the use;
769adf28177SDan Gohman         // this makes things simpler (LiveIntervals' handleMove function only
770adf28177SDan Gohman         // supports intra-block moves) and it's MachineSink's job to catch all
771adf28177SDan Gohman         // the sinking opportunities anyway.
772adf28177SDan Gohman         bool SameBlock = Def->getParent() == &MBB;
773e9e6891bSDerek Schuff         bool CanMove = SameBlock && IsSafeToMove(Def, Insert, AA, MRI) &&
774fbfe5ec4SDan Gohman                        !TreeWalker.IsOnStack(Reg);
77512de0b91SDan Gohman         if (CanMove && HasOneUse(Reg, Def, MRI, MDT, LIS)) {
7760cfb5f85SDan Gohman           Insert = MoveForSingleUse(Reg, Op, Def, MBB, Insert, LIS, MFI, MRI);
7779cfc75c2SDuncan P. N. Exon Smith         } else if (ShouldRematerialize(*Def, AA, TII)) {
7789cfc75c2SDuncan P. N. Exon Smith           Insert =
7799cfc75c2SDuncan P. N. Exon Smith               RematerializeCheapDef(Reg, Op, *Def, MBB, Insert->getIterator(),
7809cfc75c2SDuncan P. N. Exon Smith                                     LIS, MFI, MRI, TII, TRI);
781adf28177SDan Gohman         } else if (CanMove &&
7821054570aSDan Gohman                    OneUseDominatesOtherUses(Reg, Op, MBB, MRI, MDT, LIS, MFI)) {
783adf28177SDan Gohman           Insert = MoveAndTeeForMultiUse(Reg, Op, Def, MBB, Insert, LIS, MFI,
784adf28177SDan Gohman                                          MRI, TII);
785b6fd39a3SDan Gohman         } else {
786adf28177SDan Gohman           // We failed to stackify the operand. If the problem was ordering
787adf28177SDan Gohman           // constraints, Commuting may be able to help.
788adf28177SDan Gohman           if (!CanMove && SameBlock)
789adf28177SDan Gohman             Commuting.MaybeCommute(Insert, TreeWalker, TII);
790adf28177SDan Gohman           // Proceed to the next operand.
791adf28177SDan Gohman           continue;
792b6fd39a3SDan Gohman         }
793adf28177SDan Gohman 
794adf28177SDan Gohman         // We stackified an operand. Add the defining instruction's operands to
795adf28177SDan Gohman         // the worklist stack now to continue to build an ever deeper tree.
796adf28177SDan Gohman         Commuting.Reset();
797adf28177SDan Gohman         TreeWalker.PushOperands(Insert);
798b6fd39a3SDan Gohman       }
799adf28177SDan Gohman 
800adf28177SDan Gohman       // If we stackified any operands, skip over the tree to start looking for
801adf28177SDan Gohman       // the next instruction we can build a tree on.
802adf28177SDan Gohman       if (Insert != &*MII) {
8038f59cf75SDan Gohman         ImposeStackOrdering(&*MII);
804c7e5a9ceSEric Liu         MII = MachineBasicBlock::iterator(Insert).getReverse();
805adf28177SDan Gohman         Changed = true;
806adf28177SDan Gohman       }
8071462faadSDan Gohman     }
8081462faadSDan Gohman   }
8091462faadSDan Gohman 
810e040533eSDan Gohman   // If we used VALUE_STACK anywhere, add it to the live-in sets everywhere so
811adf28177SDan Gohman   // that it never looks like a use-before-def.
812b0992dafSDan Gohman   if (Changed) {
813e040533eSDan Gohman     MF.getRegInfo().addLiveIn(WebAssembly::VALUE_STACK);
814b0992dafSDan Gohman     for (MachineBasicBlock &MBB : MF)
815e040533eSDan Gohman       MBB.addLiveIn(WebAssembly::VALUE_STACK);
816b0992dafSDan Gohman   }
817b0992dafSDan Gohman 
8187bafa0eaSDan Gohman #ifndef NDEBUG
819b6fd39a3SDan Gohman   // Verify that pushes and pops are performed in LIFO order.
8207bafa0eaSDan Gohman   SmallVector<unsigned, 0> Stack;
8217bafa0eaSDan Gohman   for (MachineBasicBlock &MBB : MF) {
8227bafa0eaSDan Gohman     for (MachineInstr &MI : MBB) {
8230cfb5f85SDan Gohman       if (MI.isDebugValue())
8240cfb5f85SDan Gohman         continue;
8257bafa0eaSDan Gohman       for (MachineOperand &MO : reverse(MI.explicit_operands())) {
8267a6b9825SDan Gohman         if (!MO.isReg())
8277a6b9825SDan Gohman           continue;
828adf28177SDan Gohman         unsigned Reg = MO.getReg();
8297bafa0eaSDan Gohman 
830adf28177SDan Gohman         if (MFI.isVRegStackified(Reg)) {
8317bafa0eaSDan Gohman           if (MO.isDef())
832adf28177SDan Gohman             Stack.push_back(Reg);
8337bafa0eaSDan Gohman           else
834adf28177SDan Gohman             assert(Stack.pop_back_val() == Reg &&
835adf28177SDan Gohman                    "Register stack pop should be paired with a push");
8367bafa0eaSDan Gohman         }
8377bafa0eaSDan Gohman       }
8387bafa0eaSDan Gohman     }
8397bafa0eaSDan Gohman     // TODO: Generalize this code to support keeping values on the stack across
8407bafa0eaSDan Gohman     // basic block boundaries.
841adf28177SDan Gohman     assert(Stack.empty() &&
842adf28177SDan Gohman            "Register stack pushes and pops should be balanced");
8437bafa0eaSDan Gohman   }
8447bafa0eaSDan Gohman #endif
8457bafa0eaSDan Gohman 
8461462faadSDan Gohman   return Changed;
8471462faadSDan Gohman }
848