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
161462faadSDan Gohman /// "push" and "pop" from the stack.
171462faadSDan Gohman ///
1831448f16SDan Gohman /// This is primarily a code size optimization, since temporary values on the
191462faadSDan Gohman /// expression 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"
2781719f85SDan Gohman #include "llvm/Analysis/AliasAnalysis.h"
288887d1faSDan Gohman #include "llvm/CodeGen/LiveIntervalAnalysis.h"
291462faadSDan Gohman #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
30adf28177SDan Gohman #include "llvm/CodeGen/MachineDominators.h"
31adf28177SDan Gohman #include "llvm/CodeGen/MachineInstrBuilder.h"
321462faadSDan Gohman #include "llvm/CodeGen/MachineRegisterInfo.h"
331462faadSDan Gohman #include "llvm/CodeGen/Passes.h"
341462faadSDan Gohman #include "llvm/Support/Debug.h"
351462faadSDan Gohman #include "llvm/Support/raw_ostream.h"
361462faadSDan Gohman using namespace llvm;
371462faadSDan Gohman 
381462faadSDan Gohman #define DEBUG_TYPE "wasm-reg-stackify"
391462faadSDan Gohman 
401462faadSDan Gohman namespace {
411462faadSDan Gohman class WebAssemblyRegStackify final : public MachineFunctionPass {
421462faadSDan Gohman   const char *getPassName() const override {
431462faadSDan Gohman     return "WebAssembly Register Stackify";
441462faadSDan Gohman   }
451462faadSDan Gohman 
461462faadSDan Gohman   void getAnalysisUsage(AnalysisUsage &AU) const override {
471462faadSDan Gohman     AU.setPreservesCFG();
4881719f85SDan Gohman     AU.addRequired<AAResultsWrapperPass>();
49adf28177SDan Gohman     AU.addRequired<MachineDominatorTree>();
508887d1faSDan Gohman     AU.addRequired<LiveIntervals>();
511462faadSDan Gohman     AU.addPreserved<MachineBlockFrequencyInfo>();
528887d1faSDan Gohman     AU.addPreserved<SlotIndexes>();
538887d1faSDan Gohman     AU.addPreserved<LiveIntervals>();
548887d1faSDan Gohman     AU.addPreservedID(LiveVariablesID);
55adf28177SDan Gohman     AU.addPreserved<MachineDominatorTree>();
561462faadSDan Gohman     MachineFunctionPass::getAnalysisUsage(AU);
571462faadSDan Gohman   }
581462faadSDan Gohman 
591462faadSDan Gohman   bool runOnMachineFunction(MachineFunction &MF) override;
601462faadSDan Gohman 
611462faadSDan Gohman public:
621462faadSDan Gohman   static char ID; // Pass identification, replacement for typeid
631462faadSDan Gohman   WebAssemblyRegStackify() : MachineFunctionPass(ID) {}
641462faadSDan Gohman };
651462faadSDan Gohman } // end anonymous namespace
661462faadSDan Gohman 
671462faadSDan Gohman char WebAssemblyRegStackify::ID = 0;
681462faadSDan Gohman FunctionPass *llvm::createWebAssemblyRegStackify() {
691462faadSDan Gohman   return new WebAssemblyRegStackify();
701462faadSDan Gohman }
711462faadSDan Gohman 
72b0992dafSDan Gohman // Decorate the given instruction with implicit operands that enforce the
738887d1faSDan Gohman // expression stack ordering constraints for an instruction which is on
748887d1faSDan Gohman // the expression stack.
758887d1faSDan Gohman static void ImposeStackOrdering(MachineInstr *MI) {
764da4abd8SDan Gohman   // Write the opaque EXPR_STACK register.
774da4abd8SDan Gohman   if (!MI->definesRegister(WebAssembly::EXPR_STACK))
78b0992dafSDan Gohman     MI->addOperand(MachineOperand::CreateReg(WebAssembly::EXPR_STACK,
79b0992dafSDan Gohman                                              /*isDef=*/true,
80b0992dafSDan Gohman                                              /*isImp=*/true));
814da4abd8SDan Gohman 
824da4abd8SDan Gohman   // Also read the opaque EXPR_STACK register.
83a712a6c4SDan Gohman   if (!MI->readsRegister(WebAssembly::EXPR_STACK))
84b0992dafSDan Gohman     MI->addOperand(MachineOperand::CreateReg(WebAssembly::EXPR_STACK,
85b0992dafSDan Gohman                                              /*isDef=*/false,
86b0992dafSDan Gohman                                              /*isImp=*/true));
87b0992dafSDan Gohman }
88b0992dafSDan Gohman 
89*2644d74bSDan Gohman // Determine whether a call to the callee referenced by
90*2644d74bSDan Gohman // MI->getOperand(CalleeOpNo) reads memory, writes memory, and/or has side
91*2644d74bSDan Gohman // effects.
92*2644d74bSDan Gohman static void QueryCallee(const MachineInstr *MI, unsigned CalleeOpNo,
93*2644d74bSDan Gohman                         bool &Read, bool &Write, bool &Effects) {
94*2644d74bSDan Gohman   const MachineOperand &MO = MI->getOperand(CalleeOpNo);
95*2644d74bSDan Gohman   if (MO.isGlobal()) {
96*2644d74bSDan Gohman     const Constant *GV = MO.getGlobal();
97*2644d74bSDan Gohman     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
98*2644d74bSDan Gohman       if (!GA->isInterposable())
99*2644d74bSDan Gohman         GV = GA->getAliasee();
100*2644d74bSDan Gohman 
101*2644d74bSDan Gohman     if (const Function *F = dyn_cast<Function>(GV)) {
102*2644d74bSDan Gohman       if (!F->doesNotThrow())
103*2644d74bSDan Gohman         Effects = true;
104*2644d74bSDan Gohman       if (F->doesNotAccessMemory())
105*2644d74bSDan Gohman         return;
106*2644d74bSDan Gohman       if (F->onlyReadsMemory()) {
107*2644d74bSDan Gohman         Read = true;
108*2644d74bSDan Gohman         return;
109*2644d74bSDan Gohman       }
110*2644d74bSDan Gohman     }
111*2644d74bSDan Gohman   }
112*2644d74bSDan Gohman 
113*2644d74bSDan Gohman   // Assume the worst.
114*2644d74bSDan Gohman   Write = true;
115*2644d74bSDan Gohman   Read = true;
116*2644d74bSDan Gohman   Effects = true;
117*2644d74bSDan Gohman }
118*2644d74bSDan Gohman 
119*2644d74bSDan Gohman // Determine whether MI reads memory, writes memory, and/or has side
120*2644d74bSDan Gohman // effects.
121*2644d74bSDan Gohman static void Query(const MachineInstr *MI, AliasAnalysis &AA,
122*2644d74bSDan Gohman                   bool &Read, bool &Write, bool &Effects) {
123*2644d74bSDan Gohman   assert(!MI->isPosition());
124*2644d74bSDan Gohman   assert(!MI->isTerminator());
125*2644d74bSDan Gohman   assert(!MI->isDebugValue());
126*2644d74bSDan Gohman 
127*2644d74bSDan Gohman   // Check for loads.
128*2644d74bSDan Gohman   if (MI->mayLoad() && !MI->isInvariantLoad(&AA))
129*2644d74bSDan Gohman     Read = true;
130*2644d74bSDan Gohman 
131*2644d74bSDan Gohman   // Check for stores.
132*2644d74bSDan Gohman   if (MI->mayStore())
133*2644d74bSDan Gohman     Write = true;
134*2644d74bSDan Gohman   else if (MI->hasOrderedMemoryRef()) {
135*2644d74bSDan Gohman     switch (MI->getOpcode()) {
136*2644d74bSDan Gohman     case WebAssembly::DIV_S_I32: case WebAssembly::DIV_S_I64:
137*2644d74bSDan Gohman     case WebAssembly::REM_S_I32: case WebAssembly::REM_S_I64:
138*2644d74bSDan Gohman     case WebAssembly::DIV_U_I32: case WebAssembly::DIV_U_I64:
139*2644d74bSDan Gohman     case WebAssembly::REM_U_I32: case WebAssembly::REM_U_I64:
140*2644d74bSDan Gohman     case WebAssembly::I32_TRUNC_S_F32: case WebAssembly::I64_TRUNC_S_F32:
141*2644d74bSDan Gohman     case WebAssembly::I32_TRUNC_S_F64: case WebAssembly::I64_TRUNC_S_F64:
142*2644d74bSDan Gohman     case WebAssembly::I32_TRUNC_U_F32: case WebAssembly::I64_TRUNC_U_F32:
143*2644d74bSDan Gohman     case WebAssembly::I32_TRUNC_U_F64: case WebAssembly::I64_TRUNC_U_F64:
144*2644d74bSDan Gohman       // These instruction have hasUnmodeledSideEffects() returning true
145*2644d74bSDan Gohman       // because they trap on overflow and invalid so they can't be arbitrarily
146*2644d74bSDan Gohman       // moved, however hasOrderedMemoryRef() interprets this plus their lack
147*2644d74bSDan Gohman       // of memoperands as having a potential unknown memory reference.
148*2644d74bSDan Gohman       break;
149*2644d74bSDan Gohman     default:
150*2644d74bSDan Gohman       // Record potential stores, unless it's a call, as calls are handled
151*2644d74bSDan Gohman       // specially below.
152*2644d74bSDan Gohman       if (!MI->isCall())
153*2644d74bSDan Gohman         Write = true;
154*2644d74bSDan Gohman       break;
155*2644d74bSDan Gohman     }
156*2644d74bSDan Gohman   }
157*2644d74bSDan Gohman 
158*2644d74bSDan Gohman   // Check for side effects.
159*2644d74bSDan Gohman   if (MI->hasUnmodeledSideEffects()) {
160*2644d74bSDan Gohman     switch (MI->getOpcode()) {
161*2644d74bSDan Gohman     case WebAssembly::DIV_S_I32: case WebAssembly::DIV_S_I64:
162*2644d74bSDan Gohman     case WebAssembly::REM_S_I32: case WebAssembly::REM_S_I64:
163*2644d74bSDan Gohman     case WebAssembly::DIV_U_I32: case WebAssembly::DIV_U_I64:
164*2644d74bSDan Gohman     case WebAssembly::REM_U_I32: case WebAssembly::REM_U_I64:
165*2644d74bSDan Gohman     case WebAssembly::I32_TRUNC_S_F32: case WebAssembly::I64_TRUNC_S_F32:
166*2644d74bSDan Gohman     case WebAssembly::I32_TRUNC_S_F64: case WebAssembly::I64_TRUNC_S_F64:
167*2644d74bSDan Gohman     case WebAssembly::I32_TRUNC_U_F32: case WebAssembly::I64_TRUNC_U_F32:
168*2644d74bSDan Gohman     case WebAssembly::I32_TRUNC_U_F64: case WebAssembly::I64_TRUNC_U_F64:
169*2644d74bSDan Gohman       // These instructions have hasUnmodeledSideEffects() returning true
170*2644d74bSDan Gohman       // because they trap on overflow and invalid so they can't be arbitrarily
171*2644d74bSDan Gohman       // moved, however in the specific case of register stackifying, it is safe
172*2644d74bSDan Gohman       // to move them because overflow and invalid are Undefined Behavior.
173*2644d74bSDan Gohman       break;
174*2644d74bSDan Gohman     default:
175*2644d74bSDan Gohman       Effects = true;
176*2644d74bSDan Gohman       break;
177*2644d74bSDan Gohman     }
178*2644d74bSDan Gohman   }
179*2644d74bSDan Gohman 
180*2644d74bSDan Gohman   // Analyze calls.
181*2644d74bSDan Gohman   if (MI->isCall()) {
182*2644d74bSDan Gohman     switch (MI->getOpcode()) {
183*2644d74bSDan Gohman     case WebAssembly::CALL_VOID:
184*2644d74bSDan Gohman       QueryCallee(MI, 0, Read, Write, Effects);
185*2644d74bSDan Gohman       break;
186*2644d74bSDan Gohman     case WebAssembly::CALL_I32:
187*2644d74bSDan Gohman     case WebAssembly::CALL_I64:
188*2644d74bSDan Gohman     case WebAssembly::CALL_F32:
189*2644d74bSDan Gohman     case WebAssembly::CALL_F64:
190*2644d74bSDan Gohman       QueryCallee(MI, 1, Read, Write, Effects);
191*2644d74bSDan Gohman       break;
192*2644d74bSDan Gohman     case WebAssembly::CALL_INDIRECT_VOID:
193*2644d74bSDan Gohman     case WebAssembly::CALL_INDIRECT_I32:
194*2644d74bSDan Gohman     case WebAssembly::CALL_INDIRECT_I64:
195*2644d74bSDan Gohman     case WebAssembly::CALL_INDIRECT_F32:
196*2644d74bSDan Gohman     case WebAssembly::CALL_INDIRECT_F64:
197*2644d74bSDan Gohman       Read = true;
198*2644d74bSDan Gohman       Write = true;
199*2644d74bSDan Gohman       Effects = true;
200*2644d74bSDan Gohman       break;
201*2644d74bSDan Gohman     default:
202*2644d74bSDan Gohman       llvm_unreachable("unexpected call opcode");
203*2644d74bSDan Gohman     }
204*2644d74bSDan Gohman   }
205*2644d74bSDan Gohman }
206*2644d74bSDan Gohman 
207*2644d74bSDan Gohman // Test whether Def is safe and profitable to rematerialize.
208*2644d74bSDan Gohman static bool ShouldRematerialize(const MachineInstr *Def, AliasAnalysis &AA,
209*2644d74bSDan Gohman                                 const WebAssemblyInstrInfo *TII) {
210*2644d74bSDan Gohman   return Def->isAsCheapAsAMove() &&
211*2644d74bSDan Gohman          TII->isTriviallyReMaterializable(Def, &AA);
212*2644d74bSDan Gohman }
213*2644d74bSDan Gohman 
214*2644d74bSDan Gohman /// Identify the definition for this register at this point.
215*2644d74bSDan Gohman static MachineInstr *GetVRegDef(unsigned Reg, const MachineInstr *Insert,
216*2644d74bSDan Gohman                                 const MachineRegisterInfo &MRI,
217*2644d74bSDan Gohman                                 const LiveIntervals &LIS)
218*2644d74bSDan Gohman {
219*2644d74bSDan Gohman   // Most registers are in SSA form here so we try a quick MRI query first.
220*2644d74bSDan Gohman   if (MachineInstr *Def = MRI.getUniqueVRegDef(Reg))
221*2644d74bSDan Gohman     return Def;
222*2644d74bSDan Gohman 
223*2644d74bSDan Gohman   // MRI doesn't know what the Def is. Try asking LIS.
224*2644d74bSDan Gohman   if (const VNInfo *ValNo = LIS.getInterval(Reg).getVNInfoBefore(
225*2644d74bSDan Gohman           LIS.getInstructionIndex(*Insert)))
226*2644d74bSDan Gohman     return LIS.getInstructionFromIndex(ValNo->def);
227*2644d74bSDan Gohman 
228*2644d74bSDan Gohman   return nullptr;
229*2644d74bSDan Gohman }
230*2644d74bSDan Gohman 
2318887d1faSDan Gohman // Test whether it's safe to move Def to just before Insert.
23281719f85SDan Gohman // TODO: Compute memory dependencies in a way that doesn't require always
23381719f85SDan Gohman // walking the block.
23481719f85SDan Gohman // TODO: Compute memory dependencies in a way that uses AliasAnalysis to be
23581719f85SDan Gohman // more precise.
23681719f85SDan Gohman static bool IsSafeToMove(const MachineInstr *Def, const MachineInstr *Insert,
237adf28177SDan Gohman                          AliasAnalysis &AA, const LiveIntervals &LIS,
238adf28177SDan Gohman                          const MachineRegisterInfo &MRI) {
239391a98afSDan Gohman   assert(Def->getParent() == Insert->getParent());
2408887d1faSDan Gohman 
2418887d1faSDan Gohman   // Check for register dependencies.
2428887d1faSDan Gohman   for (const MachineOperand &MO : Def->operands()) {
2438887d1faSDan Gohman     if (!MO.isReg() || MO.isUndef())
2448887d1faSDan Gohman       continue;
2458887d1faSDan Gohman     unsigned Reg = MO.getReg();
2468887d1faSDan Gohman 
2478887d1faSDan Gohman     // If the register is dead here and at Insert, ignore it.
2488887d1faSDan Gohman     if (MO.isDead() && Insert->definesRegister(Reg) &&
2498887d1faSDan Gohman         !Insert->readsRegister(Reg))
2508887d1faSDan Gohman       continue;
2518887d1faSDan Gohman 
2528887d1faSDan Gohman     if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
2530cfb5f85SDan Gohman       // Ignore ARGUMENTS; it's just used to keep the ARGUMENT_* instructions
2540cfb5f85SDan Gohman       // from moving down, and we've already checked for that.
2550cfb5f85SDan Gohman       if (Reg == WebAssembly::ARGUMENTS)
2560cfb5f85SDan Gohman         continue;
2578887d1faSDan Gohman       // If the physical register is never modified, ignore it.
2588887d1faSDan Gohman       if (!MRI.isPhysRegModified(Reg))
2598887d1faSDan Gohman         continue;
2608887d1faSDan Gohman       // Otherwise, it's a physical register with unknown liveness.
2618887d1faSDan Gohman       return false;
2628887d1faSDan Gohman     }
2638887d1faSDan Gohman 
2648887d1faSDan Gohman     // Ask LiveIntervals whether moving this virtual register use or def to
2650cfb5f85SDan Gohman     // Insert will change which value numbers are seen.
2668887d1faSDan Gohman     const LiveInterval &LI = LIS.getInterval(Reg);
267b6fd39a3SDan Gohman     VNInfo *DefVNI =
26813d3b9b7SJF Bastien         MO.isDef() ? LI.getVNInfoAt(LIS.getInstructionIndex(*Def).getRegSlot())
26913d3b9b7SJF Bastien                    : LI.getVNInfoBefore(LIS.getInstructionIndex(*Def));
2708887d1faSDan Gohman     assert(DefVNI && "Instruction input missing value number");
27113d3b9b7SJF Bastien     VNInfo *InsVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*Insert));
2728887d1faSDan Gohman     if (InsVNI && DefVNI != InsVNI)
2738887d1faSDan Gohman       return false;
2748887d1faSDan Gohman   }
2758887d1faSDan Gohman 
276*2644d74bSDan Gohman   bool Read = false, Write = false, Effects = false;
277*2644d74bSDan Gohman   Query(Def, AA, Read, Write, Effects);
278*2644d74bSDan Gohman 
279*2644d74bSDan Gohman   // If the instruction does not access memory and has no side effects, it has
280*2644d74bSDan Gohman   // no additional dependencies.
281*2644d74bSDan Gohman   if (!Read && !Write && !Effects)
282*2644d74bSDan Gohman     return true;
283*2644d74bSDan Gohman 
284*2644d74bSDan Gohman   // Scan through the intervening instructions between Def and Insert.
285*2644d74bSDan Gohman   MachineBasicBlock::const_iterator D(Def), I(Insert);
286*2644d74bSDan Gohman   for (--I; I != D; --I) {
287*2644d74bSDan Gohman     bool InterveningRead = false;
288*2644d74bSDan Gohman     bool InterveningWrite = false;
289*2644d74bSDan Gohman     bool InterveningEffects = false;
290*2644d74bSDan Gohman     Query(I, AA, InterveningRead, InterveningWrite, InterveningEffects);
291*2644d74bSDan Gohman     if (Effects && InterveningEffects)
292*2644d74bSDan Gohman       return false;
293*2644d74bSDan Gohman     if (Read && InterveningWrite)
294*2644d74bSDan Gohman       return false;
295*2644d74bSDan Gohman     if (Write && (InterveningRead || InterveningWrite))
296*2644d74bSDan Gohman       return false;
297*2644d74bSDan Gohman   }
298*2644d74bSDan Gohman 
299*2644d74bSDan Gohman   return true;
30081719f85SDan Gohman }
30181719f85SDan Gohman 
302adf28177SDan Gohman /// Test whether OneUse, a use of Reg, dominates all of Reg's other uses.
303adf28177SDan Gohman static bool OneUseDominatesOtherUses(unsigned Reg, const MachineOperand &OneUse,
304adf28177SDan Gohman                                      const MachineBasicBlock &MBB,
305adf28177SDan Gohman                                      const MachineRegisterInfo &MRI,
3060cfb5f85SDan Gohman                                      const MachineDominatorTree &MDT,
3070cfb5f85SDan Gohman                                      LiveIntervals &LIS) {
3080cfb5f85SDan Gohman   const LiveInterval &LI = LIS.getInterval(Reg);
3090cfb5f85SDan Gohman 
3100cfb5f85SDan Gohman   const MachineInstr *OneUseInst = OneUse.getParent();
3110cfb5f85SDan Gohman   VNInfo *OneUseVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*OneUseInst));
3120cfb5f85SDan Gohman 
313adf28177SDan Gohman   for (const MachineOperand &Use : MRI.use_operands(Reg)) {
314adf28177SDan Gohman     if (&Use == &OneUse)
315adf28177SDan Gohman       continue;
3160cfb5f85SDan Gohman 
317adf28177SDan Gohman     const MachineInstr *UseInst = Use.getParent();
3180cfb5f85SDan Gohman     VNInfo *UseVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*UseInst));
3190cfb5f85SDan Gohman 
3200cfb5f85SDan Gohman     if (UseVNI != OneUseVNI)
3210cfb5f85SDan Gohman       continue;
3220cfb5f85SDan Gohman 
323adf28177SDan Gohman     const MachineInstr *OneUseInst = OneUse.getParent();
324adf28177SDan Gohman     if (UseInst->getOpcode() == TargetOpcode::PHI) {
325adf28177SDan Gohman       // Test that the PHI use, which happens on the CFG edge rather than
326adf28177SDan Gohman       // within the PHI's own block, is dominated by the one selected use.
327adf28177SDan Gohman       const MachineBasicBlock *Pred =
328adf28177SDan Gohman           UseInst->getOperand(&Use - &UseInst->getOperand(0) + 1).getMBB();
329adf28177SDan Gohman       if (!MDT.dominates(&MBB, Pred))
330adf28177SDan Gohman         return false;
331adf28177SDan Gohman     } else if (UseInst == OneUseInst) {
332adf28177SDan Gohman       // Another use in the same instruction. We need to ensure that the one
333adf28177SDan Gohman       // selected use happens "before" it.
334adf28177SDan Gohman       if (&OneUse > &Use)
335adf28177SDan Gohman         return false;
336adf28177SDan Gohman     } else {
337adf28177SDan Gohman       // Test that the use is dominated by the one selected use.
338adf28177SDan Gohman       if (!MDT.dominates(OneUseInst, UseInst))
339adf28177SDan Gohman         return false;
340adf28177SDan Gohman     }
341adf28177SDan Gohman   }
342adf28177SDan Gohman   return true;
343adf28177SDan Gohman }
344adf28177SDan Gohman 
345adf28177SDan Gohman /// Get the appropriate tee_local opcode for the given register class.
346adf28177SDan Gohman static unsigned GetTeeLocalOpcode(const TargetRegisterClass *RC) {
347adf28177SDan Gohman   if (RC == &WebAssembly::I32RegClass)
348adf28177SDan Gohman     return WebAssembly::TEE_LOCAL_I32;
349adf28177SDan Gohman   if (RC == &WebAssembly::I64RegClass)
350adf28177SDan Gohman     return WebAssembly::TEE_LOCAL_I64;
351adf28177SDan Gohman   if (RC == &WebAssembly::F32RegClass)
352adf28177SDan Gohman     return WebAssembly::TEE_LOCAL_F32;
353adf28177SDan Gohman   if (RC == &WebAssembly::F64RegClass)
354adf28177SDan Gohman     return WebAssembly::TEE_LOCAL_F64;
355adf28177SDan Gohman   llvm_unreachable("Unexpected register class");
356adf28177SDan Gohman }
357adf28177SDan Gohman 
358*2644d74bSDan Gohman // Shrink LI to its uses, cleaning up LI.
359*2644d74bSDan Gohman static void ShrinkToUses(LiveInterval &LI, LiveIntervals &LIS) {
360*2644d74bSDan Gohman   if (LIS.shrinkToUses(&LI)) {
361*2644d74bSDan Gohman     SmallVector<LiveInterval*, 4> SplitLIs;
362*2644d74bSDan Gohman     LIS.splitSeparateComponents(LI, SplitLIs);
363*2644d74bSDan Gohman   }
364*2644d74bSDan Gohman }
365*2644d74bSDan Gohman 
366adf28177SDan Gohman /// A single-use def in the same block with no intervening memory or register
367adf28177SDan Gohman /// dependencies; move the def down and nest it with the current instruction.
3680cfb5f85SDan Gohman static MachineInstr *MoveForSingleUse(unsigned Reg, MachineOperand& Op,
3690cfb5f85SDan Gohman                                       MachineInstr *Def,
370adf28177SDan Gohman                                       MachineBasicBlock &MBB,
371adf28177SDan Gohman                                       MachineInstr *Insert, LiveIntervals &LIS,
3720cfb5f85SDan Gohman                                       WebAssemblyFunctionInfo &MFI,
3730cfb5f85SDan Gohman                                       MachineRegisterInfo &MRI) {
374*2644d74bSDan Gohman   DEBUG(dbgs() << "Move for single use: "; Def->dump());
375*2644d74bSDan Gohman 
376adf28177SDan Gohman   MBB.splice(Insert, &MBB, Def);
3771afd1e2bSJF Bastien   LIS.handleMove(*Def);
3780cfb5f85SDan Gohman 
3790cfb5f85SDan Gohman   if (MRI.hasOneDef(Reg)) {
380adf28177SDan Gohman     MFI.stackifyVReg(Reg);
3810cfb5f85SDan Gohman   } else {
3820cfb5f85SDan Gohman     unsigned NewReg = MRI.createVirtualRegister(MRI.getRegClass(Reg));
3830cfb5f85SDan Gohman     Def->getOperand(0).setReg(NewReg);
3840cfb5f85SDan Gohman     Op.setReg(NewReg);
3850cfb5f85SDan Gohman 
3860cfb5f85SDan Gohman     // Tell LiveIntervals about the new register.
3870cfb5f85SDan Gohman     LIS.createAndComputeVirtRegInterval(NewReg);
3880cfb5f85SDan Gohman 
3890cfb5f85SDan Gohman     // Tell LiveIntervals about the changes to the old register.
3900cfb5f85SDan Gohman     LiveInterval &LI = LIS.getInterval(Reg);
3910cfb5f85SDan Gohman     LIS.removeVRegDefAt(LI, LIS.getInstructionIndex(*Def).getRegSlot());
392*2644d74bSDan Gohman     ShrinkToUses(LI, LIS);
3930cfb5f85SDan Gohman 
3940cfb5f85SDan Gohman     MFI.stackifyVReg(NewReg);
395*2644d74bSDan Gohman 
396*2644d74bSDan Gohman     DEBUG(dbgs() << " - Replaced register: "; Def->dump());
3970cfb5f85SDan Gohman   }
3980cfb5f85SDan Gohman 
399adf28177SDan Gohman   ImposeStackOrdering(Def);
400adf28177SDan Gohman   return Def;
401adf28177SDan Gohman }
402adf28177SDan Gohman 
403adf28177SDan Gohman /// A trivially cloneable instruction; clone it and nest the new copy with the
404adf28177SDan Gohman /// current instruction.
405adf28177SDan Gohman static MachineInstr *
406adf28177SDan Gohman RematerializeCheapDef(unsigned Reg, MachineOperand &Op, MachineInstr *Def,
407adf28177SDan Gohman                       MachineBasicBlock &MBB, MachineInstr *Insert,
408adf28177SDan Gohman                       LiveIntervals &LIS, WebAssemblyFunctionInfo &MFI,
409adf28177SDan Gohman                       MachineRegisterInfo &MRI, const WebAssemblyInstrInfo *TII,
410adf28177SDan Gohman                       const WebAssemblyRegisterInfo *TRI) {
411*2644d74bSDan Gohman   DEBUG(dbgs() << "Rematerializing cheap def: "; Def->dump());
412*2644d74bSDan Gohman   DEBUG(dbgs() << " - for use in "; Op.getParent()->dump());
413*2644d74bSDan Gohman 
414adf28177SDan Gohman   unsigned NewReg = MRI.createVirtualRegister(MRI.getRegClass(Reg));
415adf28177SDan Gohman   TII->reMaterialize(MBB, Insert, NewReg, 0, Def, *TRI);
416adf28177SDan Gohman   Op.setReg(NewReg);
417adf28177SDan Gohman   MachineInstr *Clone = &*std::prev(MachineBasicBlock::instr_iterator(Insert));
41813d3b9b7SJF Bastien   LIS.InsertMachineInstrInMaps(*Clone);
419adf28177SDan Gohman   LIS.createAndComputeVirtRegInterval(NewReg);
420adf28177SDan Gohman   MFI.stackifyVReg(NewReg);
421adf28177SDan Gohman   ImposeStackOrdering(Clone);
422adf28177SDan Gohman 
423*2644d74bSDan Gohman   DEBUG(dbgs() << " - Cloned to "; Clone->dump());
424*2644d74bSDan Gohman 
4250cfb5f85SDan Gohman   // Shrink the interval.
4260cfb5f85SDan Gohman   bool IsDead = MRI.use_empty(Reg);
4270cfb5f85SDan Gohman   if (!IsDead) {
4280cfb5f85SDan Gohman     LiveInterval &LI = LIS.getInterval(Reg);
429*2644d74bSDan Gohman     ShrinkToUses(LI, LIS);
4300cfb5f85SDan Gohman     IsDead = !LI.liveAt(LIS.getInstructionIndex(*Def).getDeadSlot());
4310cfb5f85SDan Gohman   }
4320cfb5f85SDan Gohman 
433adf28177SDan Gohman   // If that was the last use of the original, delete the original.
4340cfb5f85SDan Gohman   if (IsDead) {
435*2644d74bSDan Gohman     DEBUG(dbgs() << " - Deleting original\n");
43613d3b9b7SJF Bastien     SlotIndex Idx = LIS.getInstructionIndex(*Def).getRegSlot();
437adf28177SDan Gohman     LIS.removePhysRegDefAt(WebAssembly::ARGUMENTS, Idx);
438adf28177SDan Gohman     LIS.removeInterval(Reg);
43913d3b9b7SJF Bastien     LIS.RemoveMachineInstrFromMaps(*Def);
440adf28177SDan Gohman     Def->eraseFromParent();
441adf28177SDan Gohman   }
4420cfb5f85SDan Gohman 
443adf28177SDan Gohman   return Clone;
444adf28177SDan Gohman }
445adf28177SDan Gohman 
446adf28177SDan Gohman /// A multiple-use def in the same block with no intervening memory or register
447adf28177SDan Gohman /// dependencies; move the def down, nest it with the current instruction, and
448adf28177SDan Gohman /// insert a tee_local to satisfy the rest of the uses. As an illustration,
449adf28177SDan Gohman /// rewrite this:
450adf28177SDan Gohman ///
451adf28177SDan Gohman ///    Reg = INST ...        // Def
452adf28177SDan Gohman ///    INST ..., Reg, ...    // Insert
453adf28177SDan Gohman ///    INST ..., Reg, ...
454adf28177SDan Gohman ///    INST ..., Reg, ...
455adf28177SDan Gohman ///
456adf28177SDan Gohman /// to this:
457adf28177SDan Gohman ///
4588aa237c3SDan Gohman ///    DefReg = INST ...     // Def (to become the new Insert)
4598aa237c3SDan Gohman ///    TeeReg, NewReg = TEE_LOCAL_... DefReg
460adf28177SDan Gohman ///    INST ..., TeeReg, ... // Insert
461adf28177SDan Gohman ///    INST ..., NewReg, ...
462adf28177SDan Gohman ///    INST ..., NewReg, ...
463adf28177SDan Gohman ///
4648aa237c3SDan Gohman /// with DefReg and TeeReg stackified. This eliminates a get_local from the
465adf28177SDan Gohman /// resulting code.
466adf28177SDan Gohman static MachineInstr *MoveAndTeeForMultiUse(
467adf28177SDan Gohman     unsigned Reg, MachineOperand &Op, MachineInstr *Def, MachineBasicBlock &MBB,
468adf28177SDan Gohman     MachineInstr *Insert, LiveIntervals &LIS, WebAssemblyFunctionInfo &MFI,
469adf28177SDan Gohman     MachineRegisterInfo &MRI, const WebAssemblyInstrInfo *TII) {
470*2644d74bSDan Gohman   DEBUG(dbgs() << "Move and tee for multi-use:"; Def->dump());
471*2644d74bSDan Gohman 
472adf28177SDan Gohman   MBB.splice(Insert, &MBB, Def);
4731afd1e2bSJF Bastien   LIS.handleMove(*Def);
474adf28177SDan Gohman   const auto *RegClass = MRI.getRegClass(Reg);
475adf28177SDan Gohman   unsigned NewReg = MRI.createVirtualRegister(RegClass);
476adf28177SDan Gohman   unsigned TeeReg = MRI.createVirtualRegister(RegClass);
4778aa237c3SDan Gohman   unsigned DefReg = MRI.createVirtualRegister(RegClass);
47833e694a8SDan Gohman   MachineOperand &DefMO = Def->getOperand(0);
479adf28177SDan Gohman   MRI.replaceRegWith(Reg, NewReg);
480adf28177SDan Gohman   MachineInstr *Tee = BuildMI(MBB, Insert, Insert->getDebugLoc(),
481adf28177SDan Gohman                               TII->get(GetTeeLocalOpcode(RegClass)), TeeReg)
482adf28177SDan Gohman                           .addReg(NewReg, RegState::Define)
48333e694a8SDan Gohman                           .addReg(DefReg, getUndefRegState(DefMO.isDead()));
484adf28177SDan Gohman   Op.setReg(TeeReg);
48533e694a8SDan Gohman   DefMO.setReg(DefReg);
48613d3b9b7SJF Bastien   LIS.InsertMachineInstrInMaps(*Tee);
4878aa237c3SDan Gohman   LIS.removeInterval(Reg);
488adf28177SDan Gohman   LIS.createAndComputeVirtRegInterval(NewReg);
489adf28177SDan Gohman   LIS.createAndComputeVirtRegInterval(TeeReg);
4908aa237c3SDan Gohman   LIS.createAndComputeVirtRegInterval(DefReg);
4918aa237c3SDan Gohman   MFI.stackifyVReg(DefReg);
492adf28177SDan Gohman   MFI.stackifyVReg(TeeReg);
493adf28177SDan Gohman   ImposeStackOrdering(Def);
494adf28177SDan Gohman   ImposeStackOrdering(Tee);
495adf28177SDan Gohman   return Def;
496adf28177SDan Gohman }
497adf28177SDan Gohman 
498adf28177SDan Gohman namespace {
499adf28177SDan Gohman /// A stack for walking the tree of instructions being built, visiting the
500adf28177SDan Gohman /// MachineOperands in DFS order.
501adf28177SDan Gohman class TreeWalkerState {
502adf28177SDan Gohman   typedef MachineInstr::mop_iterator mop_iterator;
503adf28177SDan Gohman   typedef std::reverse_iterator<mop_iterator> mop_reverse_iterator;
504adf28177SDan Gohman   typedef iterator_range<mop_reverse_iterator> RangeTy;
505adf28177SDan Gohman   SmallVector<RangeTy, 4> Worklist;
506adf28177SDan Gohman 
507adf28177SDan Gohman public:
508adf28177SDan Gohman   explicit TreeWalkerState(MachineInstr *Insert) {
509adf28177SDan Gohman     const iterator_range<mop_iterator> &Range = Insert->explicit_uses();
510adf28177SDan Gohman     if (Range.begin() != Range.end())
511adf28177SDan Gohman       Worklist.push_back(reverse(Range));
512adf28177SDan Gohman   }
513adf28177SDan Gohman 
514adf28177SDan Gohman   bool Done() const { return Worklist.empty(); }
515adf28177SDan Gohman 
516adf28177SDan Gohman   MachineOperand &Pop() {
517adf28177SDan Gohman     RangeTy &Range = Worklist.back();
518adf28177SDan Gohman     MachineOperand &Op = *Range.begin();
519adf28177SDan Gohman     Range = drop_begin(Range, 1);
520adf28177SDan Gohman     if (Range.begin() == Range.end())
521adf28177SDan Gohman       Worklist.pop_back();
522adf28177SDan Gohman     assert((Worklist.empty() ||
523adf28177SDan Gohman             Worklist.back().begin() != Worklist.back().end()) &&
524adf28177SDan Gohman            "Empty ranges shouldn't remain in the worklist");
525adf28177SDan Gohman     return Op;
526adf28177SDan Gohman   }
527adf28177SDan Gohman 
528adf28177SDan Gohman   /// Push Instr's operands onto the stack to be visited.
529adf28177SDan Gohman   void PushOperands(MachineInstr *Instr) {
530adf28177SDan Gohman     const iterator_range<mop_iterator> &Range(Instr->explicit_uses());
531adf28177SDan Gohman     if (Range.begin() != Range.end())
532adf28177SDan Gohman       Worklist.push_back(reverse(Range));
533adf28177SDan Gohman   }
534adf28177SDan Gohman 
535adf28177SDan Gohman   /// Some of Instr's operands are on the top of the stack; remove them and
536adf28177SDan Gohman   /// re-insert them starting from the beginning (because we've commuted them).
537adf28177SDan Gohman   void ResetTopOperands(MachineInstr *Instr) {
538adf28177SDan Gohman     assert(HasRemainingOperands(Instr) &&
539adf28177SDan Gohman            "Reseting operands should only be done when the instruction has "
540adf28177SDan Gohman            "an operand still on the stack");
541adf28177SDan Gohman     Worklist.back() = reverse(Instr->explicit_uses());
542adf28177SDan Gohman   }
543adf28177SDan Gohman 
544adf28177SDan Gohman   /// Test whether Instr has operands remaining to be visited at the top of
545adf28177SDan Gohman   /// the stack.
546adf28177SDan Gohman   bool HasRemainingOperands(const MachineInstr *Instr) const {
547adf28177SDan Gohman     if (Worklist.empty())
548adf28177SDan Gohman       return false;
549adf28177SDan Gohman     const RangeTy &Range = Worklist.back();
550adf28177SDan Gohman     return Range.begin() != Range.end() && Range.begin()->getParent() == Instr;
551adf28177SDan Gohman   }
552fbfe5ec4SDan Gohman 
553fbfe5ec4SDan Gohman   /// Test whether the given register is present on the stack, indicating an
554fbfe5ec4SDan Gohman   /// operand in the tree that we haven't visited yet. Moving a definition of
555fbfe5ec4SDan Gohman   /// Reg to a point in the tree after that would change its value.
556fbfe5ec4SDan Gohman   bool IsOnStack(unsigned Reg) const {
557fbfe5ec4SDan Gohman     for (const RangeTy &Range : Worklist)
558fbfe5ec4SDan Gohman       for (const MachineOperand &MO : Range)
559fbfe5ec4SDan Gohman         if (MO.isReg() && MO.getReg() == Reg)
560fbfe5ec4SDan Gohman           return true;
561fbfe5ec4SDan Gohman     return false;
562fbfe5ec4SDan Gohman   }
563adf28177SDan Gohman };
564adf28177SDan Gohman 
565adf28177SDan Gohman /// State to keep track of whether commuting is in flight or whether it's been
566adf28177SDan Gohman /// tried for the current instruction and didn't work.
567adf28177SDan Gohman class CommutingState {
568adf28177SDan Gohman   /// There are effectively three states: the initial state where we haven't
569adf28177SDan Gohman   /// started commuting anything and we don't know anything yet, the tenative
570adf28177SDan Gohman   /// state where we've commuted the operands of the current instruction and are
571adf28177SDan Gohman   /// revisting it, and the declined state where we've reverted the operands
572adf28177SDan Gohman   /// back to their original order and will no longer commute it further.
573adf28177SDan Gohman   bool TentativelyCommuting;
574adf28177SDan Gohman   bool Declined;
575adf28177SDan Gohman 
576adf28177SDan Gohman   /// During the tentative state, these hold the operand indices of the commuted
577adf28177SDan Gohman   /// operands.
578adf28177SDan Gohman   unsigned Operand0, Operand1;
579adf28177SDan Gohman 
580adf28177SDan Gohman public:
581adf28177SDan Gohman   CommutingState() : TentativelyCommuting(false), Declined(false) {}
582adf28177SDan Gohman 
583adf28177SDan Gohman   /// Stackification for an operand was not successful due to ordering
584adf28177SDan Gohman   /// constraints. If possible, and if we haven't already tried it and declined
585adf28177SDan Gohman   /// it, commute Insert's operands and prepare to revisit it.
586adf28177SDan Gohman   void MaybeCommute(MachineInstr *Insert, TreeWalkerState &TreeWalker,
587adf28177SDan Gohman                     const WebAssemblyInstrInfo *TII) {
588adf28177SDan Gohman     if (TentativelyCommuting) {
589adf28177SDan Gohman       assert(!Declined &&
590adf28177SDan Gohman              "Don't decline commuting until you've finished trying it");
591adf28177SDan Gohman       // Commuting didn't help. Revert it.
592adf28177SDan Gohman       TII->commuteInstruction(Insert, /*NewMI=*/false, Operand0, Operand1);
593adf28177SDan Gohman       TentativelyCommuting = false;
594adf28177SDan Gohman       Declined = true;
595adf28177SDan Gohman     } else if (!Declined && TreeWalker.HasRemainingOperands(Insert)) {
596adf28177SDan Gohman       Operand0 = TargetInstrInfo::CommuteAnyOperandIndex;
597adf28177SDan Gohman       Operand1 = TargetInstrInfo::CommuteAnyOperandIndex;
598adf28177SDan Gohman       if (TII->findCommutedOpIndices(Insert, Operand0, Operand1)) {
599adf28177SDan Gohman         // Tentatively commute the operands and try again.
600adf28177SDan Gohman         TII->commuteInstruction(Insert, /*NewMI=*/false, Operand0, Operand1);
601adf28177SDan Gohman         TreeWalker.ResetTopOperands(Insert);
602adf28177SDan Gohman         TentativelyCommuting = true;
603adf28177SDan Gohman         Declined = false;
604adf28177SDan Gohman       }
605adf28177SDan Gohman     }
606adf28177SDan Gohman   }
607adf28177SDan Gohman 
608adf28177SDan Gohman   /// Stackification for some operand was successful. Reset to the default
609adf28177SDan Gohman   /// state.
610adf28177SDan Gohman   void Reset() {
611adf28177SDan Gohman     TentativelyCommuting = false;
612adf28177SDan Gohman     Declined = false;
613adf28177SDan Gohman   }
614adf28177SDan Gohman };
615adf28177SDan Gohman } // end anonymous namespace
616adf28177SDan Gohman 
6171462faadSDan Gohman bool WebAssemblyRegStackify::runOnMachineFunction(MachineFunction &MF) {
6181462faadSDan Gohman   DEBUG(dbgs() << "********** Register Stackifying **********\n"
6191462faadSDan Gohman                   "********** Function: "
6201462faadSDan Gohman                << MF.getName() << '\n');
6211462faadSDan Gohman 
6221462faadSDan Gohman   bool Changed = false;
6231462faadSDan Gohman   MachineRegisterInfo &MRI = MF.getRegInfo();
6241462faadSDan Gohman   WebAssemblyFunctionInfo &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
625b6fd39a3SDan Gohman   const auto *TII = MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
626b6fd39a3SDan Gohman   const auto *TRI = MF.getSubtarget<WebAssemblySubtarget>().getRegisterInfo();
62781719f85SDan Gohman   AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
628adf28177SDan Gohman   MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
6298887d1faSDan Gohman   LiveIntervals &LIS = getAnalysis<LiveIntervals>();
630d70e5907SDan Gohman 
6311462faadSDan Gohman   // Walk the instructions from the bottom up. Currently we don't look past
6321462faadSDan Gohman   // block boundaries, and the blocks aren't ordered so the block visitation
6331462faadSDan Gohman   // order isn't significant, but we may want to change this in the future.
6341462faadSDan Gohman   for (MachineBasicBlock &MBB : MF) {
6358f59cf75SDan Gohman     // Don't use a range-based for loop, because we modify the list as we're
6368f59cf75SDan Gohman     // iterating over it and the end iterator may change.
6378f59cf75SDan Gohman     for (auto MII = MBB.rbegin(); MII != MBB.rend(); ++MII) {
6388f59cf75SDan Gohman       MachineInstr *Insert = &*MII;
6391462faadSDan Gohman       // Don't nest anything inside a phi.
6401462faadSDan Gohman       if (Insert->getOpcode() == TargetOpcode::PHI)
6411462faadSDan Gohman         break;
6421462faadSDan Gohman 
64381719f85SDan Gohman       // Don't nest anything inside an inline asm, because we don't have
64481719f85SDan Gohman       // constraints for $push inputs.
64581719f85SDan Gohman       if (Insert->getOpcode() == TargetOpcode::INLINEASM)
646595e8ab2SDan Gohman         continue;
647595e8ab2SDan Gohman 
648595e8ab2SDan Gohman       // Ignore debugging intrinsics.
649595e8ab2SDan Gohman       if (Insert->getOpcode() == TargetOpcode::DBG_VALUE)
650595e8ab2SDan Gohman         continue;
65181719f85SDan Gohman 
6521462faadSDan Gohman       // Iterate through the inputs in reverse order, since we'll be pulling
65353d13997SDan Gohman       // operands off the stack in LIFO order.
654adf28177SDan Gohman       CommutingState Commuting;
655adf28177SDan Gohman       TreeWalkerState TreeWalker(Insert);
656adf28177SDan Gohman       while (!TreeWalker.Done()) {
657adf28177SDan Gohman         MachineOperand &Op = TreeWalker.Pop();
658adf28177SDan Gohman 
6591462faadSDan Gohman         // We're only interested in explicit virtual register operands.
660adf28177SDan Gohman         if (!Op.isReg())
6611462faadSDan Gohman           continue;
6621462faadSDan Gohman 
6631462faadSDan Gohman         unsigned Reg = Op.getReg();
664adf28177SDan Gohman         assert(Op.isUse() && "explicit_uses() should only iterate over uses");
665adf28177SDan Gohman         assert(!Op.isImplicit() &&
666adf28177SDan Gohman                "explicit_uses() should only iterate over explicit operands");
667adf28177SDan Gohman         if (TargetRegisterInfo::isPhysicalRegister(Reg))
668adf28177SDan Gohman           continue;
6691462faadSDan Gohman 
670adf28177SDan Gohman         // Identify the definition for this register at this point. Most
671adf28177SDan Gohman         // registers are in SSA form here so we try a quick MRI query first.
672*2644d74bSDan Gohman         MachineInstr *Def = GetVRegDef(Reg, Insert, MRI, LIS);
6731462faadSDan Gohman         if (!Def)
6741462faadSDan Gohman           continue;
6751462faadSDan Gohman 
67681719f85SDan Gohman         // Don't nest an INLINE_ASM def into anything, because we don't have
67781719f85SDan Gohman         // constraints for $pop outputs.
67881719f85SDan Gohman         if (Def->getOpcode() == TargetOpcode::INLINEASM)
67981719f85SDan Gohman           continue;
68081719f85SDan Gohman 
68181719f85SDan Gohman         // Don't nest PHIs inside of anything.
68281719f85SDan Gohman         if (Def->getOpcode() == TargetOpcode::PHI)
68381719f85SDan Gohman           continue;
68481719f85SDan Gohman 
6854ba4816bSDan Gohman         // Argument instructions represent live-in registers and not real
6864ba4816bSDan Gohman         // instructions.
6874ba4816bSDan Gohman         if (Def->getOpcode() == WebAssembly::ARGUMENT_I32 ||
6884ba4816bSDan Gohman             Def->getOpcode() == WebAssembly::ARGUMENT_I64 ||
6894ba4816bSDan Gohman             Def->getOpcode() == WebAssembly::ARGUMENT_F32 ||
6904ba4816bSDan Gohman             Def->getOpcode() == WebAssembly::ARGUMENT_F64)
6914ba4816bSDan Gohman           continue;
6924ba4816bSDan Gohman 
693adf28177SDan Gohman         // Decide which strategy to take. Prefer to move a single-use value
694adf28177SDan Gohman         // over cloning it, and prefer cloning over introducing a tee_local.
695adf28177SDan Gohman         // For moving, we require the def to be in the same block as the use;
696adf28177SDan Gohman         // this makes things simpler (LiveIntervals' handleMove function only
697adf28177SDan Gohman         // supports intra-block moves) and it's MachineSink's job to catch all
698adf28177SDan Gohman         // the sinking opportunities anyway.
699adf28177SDan Gohman         bool SameBlock = Def->getParent() == &MBB;
700fbfe5ec4SDan Gohman         bool CanMove = SameBlock && IsSafeToMove(Def, Insert, AA, LIS, MRI) &&
701fbfe5ec4SDan Gohman                        !TreeWalker.IsOnStack(Reg);
702adf28177SDan Gohman         if (CanMove && MRI.hasOneUse(Reg)) {
7030cfb5f85SDan Gohman           Insert = MoveForSingleUse(Reg, Op, Def, MBB, Insert, LIS, MFI, MRI);
704*2644d74bSDan Gohman         } else if (ShouldRematerialize(Def, AA, TII)) {
705adf28177SDan Gohman           Insert = RematerializeCheapDef(Reg, Op, Def, MBB, Insert, LIS, MFI,
706adf28177SDan Gohman                                          MRI, TII, TRI);
707adf28177SDan Gohman         } else if (CanMove &&
7080cfb5f85SDan Gohman                    OneUseDominatesOtherUses(Reg, Op, MBB, MRI, MDT, LIS)) {
709adf28177SDan Gohman           Insert = MoveAndTeeForMultiUse(Reg, Op, Def, MBB, Insert, LIS, MFI,
710adf28177SDan Gohman                                          MRI, TII);
711b6fd39a3SDan Gohman         } else {
712adf28177SDan Gohman           // We failed to stackify the operand. If the problem was ordering
713adf28177SDan Gohman           // constraints, Commuting may be able to help.
714adf28177SDan Gohman           if (!CanMove && SameBlock)
715adf28177SDan Gohman             Commuting.MaybeCommute(Insert, TreeWalker, TII);
716adf28177SDan Gohman           // Proceed to the next operand.
717adf28177SDan Gohman           continue;
718b6fd39a3SDan Gohman         }
719adf28177SDan Gohman 
720adf28177SDan Gohman         // We stackified an operand. Add the defining instruction's operands to
721adf28177SDan Gohman         // the worklist stack now to continue to build an ever deeper tree.
722adf28177SDan Gohman         Commuting.Reset();
723adf28177SDan Gohman         TreeWalker.PushOperands(Insert);
724b6fd39a3SDan Gohman       }
725adf28177SDan Gohman 
726adf28177SDan Gohman       // If we stackified any operands, skip over the tree to start looking for
727adf28177SDan Gohman       // the next instruction we can build a tree on.
728adf28177SDan Gohman       if (Insert != &*MII) {
7298f59cf75SDan Gohman         ImposeStackOrdering(&*MII);
730adf28177SDan Gohman         MII = std::prev(
731369ebfe4SHans Wennborg             llvm::make_reverse_iterator(MachineBasicBlock::iterator(Insert)));
732adf28177SDan Gohman         Changed = true;
733adf28177SDan Gohman       }
7341462faadSDan Gohman     }
7351462faadSDan Gohman   }
7361462faadSDan Gohman 
737adf28177SDan Gohman   // If we used EXPR_STACK anywhere, add it to the live-in sets everywhere so
738adf28177SDan Gohman   // that it never looks like a use-before-def.
739b0992dafSDan Gohman   if (Changed) {
740b0992dafSDan Gohman     MF.getRegInfo().addLiveIn(WebAssembly::EXPR_STACK);
741b0992dafSDan Gohman     for (MachineBasicBlock &MBB : MF)
742b0992dafSDan Gohman       MBB.addLiveIn(WebAssembly::EXPR_STACK);
743b0992dafSDan Gohman   }
744b0992dafSDan Gohman 
7457bafa0eaSDan Gohman #ifndef NDEBUG
746b6fd39a3SDan Gohman   // Verify that pushes and pops are performed in LIFO order.
7477bafa0eaSDan Gohman   SmallVector<unsigned, 0> Stack;
7487bafa0eaSDan Gohman   for (MachineBasicBlock &MBB : MF) {
7497bafa0eaSDan Gohman     for (MachineInstr &MI : MBB) {
7500cfb5f85SDan Gohman       if (MI.isDebugValue())
7510cfb5f85SDan Gohman         continue;
7527bafa0eaSDan Gohman       for (MachineOperand &MO : reverse(MI.explicit_operands())) {
7537a6b9825SDan Gohman         if (!MO.isReg())
7547a6b9825SDan Gohman           continue;
755adf28177SDan Gohman         unsigned Reg = MO.getReg();
7567bafa0eaSDan Gohman 
757adf28177SDan Gohman         if (MFI.isVRegStackified(Reg)) {
7587bafa0eaSDan Gohman           if (MO.isDef())
759adf28177SDan Gohman             Stack.push_back(Reg);
7607bafa0eaSDan Gohman           else
761adf28177SDan Gohman             assert(Stack.pop_back_val() == Reg &&
762adf28177SDan Gohman                    "Register stack pop should be paired with a push");
7637bafa0eaSDan Gohman         }
7647bafa0eaSDan Gohman       }
7657bafa0eaSDan Gohman     }
7667bafa0eaSDan Gohman     // TODO: Generalize this code to support keeping values on the stack across
7677bafa0eaSDan Gohman     // basic block boundaries.
768adf28177SDan Gohman     assert(Stack.empty() &&
769adf28177SDan Gohman            "Register stack pushes and pops should be balanced");
7707bafa0eaSDan Gohman   }
7717bafa0eaSDan Gohman #endif
7727bafa0eaSDan Gohman 
7731462faadSDan Gohman   return Changed;
7741462faadSDan Gohman }
775