1 //===-- WebAssemblyRegStackify.cpp - Register Stackification --------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 ///
10 /// \file
11 /// \brief This file implements a register stacking pass.
12 ///
13 /// This pass reorders instructions to put register uses and defs in an order
14 /// such that they form single-use expression trees. Registers fitting this form
15 /// are then marked as "stackified", meaning references to them are replaced by
16 /// "push" and "pop" from the stack.
17 ///
18 /// This is primarily a code size optimization, since temporary values on the
19 /// expression don't need to be named.
20 ///
21 //===----------------------------------------------------------------------===//
22 
23 #include "WebAssembly.h"
24 #include "MCTargetDesc/WebAssemblyMCTargetDesc.h" // for WebAssembly::ARGUMENT_*
25 #include "WebAssemblyMachineFunctionInfo.h"
26 #include "WebAssemblySubtarget.h"
27 #include "llvm/Analysis/AliasAnalysis.h"
28 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
29 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
30 #include "llvm/CodeGen/MachineDominators.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/CodeGen/Passes.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/raw_ostream.h"
36 using namespace llvm;
37 
38 #define DEBUG_TYPE "wasm-reg-stackify"
39 
40 namespace {
41 class WebAssemblyRegStackify final : public MachineFunctionPass {
42   const char *getPassName() const override {
43     return "WebAssembly Register Stackify";
44   }
45 
46   void getAnalysisUsage(AnalysisUsage &AU) const override {
47     AU.setPreservesCFG();
48     AU.addRequired<AAResultsWrapperPass>();
49     AU.addRequired<MachineDominatorTree>();
50     AU.addRequired<LiveIntervals>();
51     AU.addPreserved<MachineBlockFrequencyInfo>();
52     AU.addPreserved<SlotIndexes>();
53     AU.addPreserved<LiveIntervals>();
54     AU.addPreservedID(LiveVariablesID);
55     AU.addPreserved<MachineDominatorTree>();
56     MachineFunctionPass::getAnalysisUsage(AU);
57   }
58 
59   bool runOnMachineFunction(MachineFunction &MF) override;
60 
61 public:
62   static char ID; // Pass identification, replacement for typeid
63   WebAssemblyRegStackify() : MachineFunctionPass(ID) {}
64 };
65 } // end anonymous namespace
66 
67 char WebAssemblyRegStackify::ID = 0;
68 FunctionPass *llvm::createWebAssemblyRegStackify() {
69   return new WebAssemblyRegStackify();
70 }
71 
72 // Decorate the given instruction with implicit operands that enforce the
73 // expression stack ordering constraints for an instruction which is on
74 // the expression stack.
75 static void ImposeStackOrdering(MachineInstr *MI) {
76   // Write the opaque EXPR_STACK register.
77   if (!MI->definesRegister(WebAssembly::EXPR_STACK))
78     MI->addOperand(MachineOperand::CreateReg(WebAssembly::EXPR_STACK,
79                                              /*isDef=*/true,
80                                              /*isImp=*/true));
81 
82   // Also read the opaque EXPR_STACK register.
83   if (!MI->readsRegister(WebAssembly::EXPR_STACK))
84     MI->addOperand(MachineOperand::CreateReg(WebAssembly::EXPR_STACK,
85                                              /*isDef=*/false,
86                                              /*isImp=*/true));
87 }
88 
89 // Determine whether a call to the callee referenced by
90 // MI->getOperand(CalleeOpNo) reads memory, writes memory, and/or has side
91 // effects.
92 static void QueryCallee(const MachineInstr *MI, unsigned CalleeOpNo,
93                         bool &Read, bool &Write, bool &Effects) {
94   const MachineOperand &MO = MI->getOperand(CalleeOpNo);
95   if (MO.isGlobal()) {
96     const Constant *GV = MO.getGlobal();
97     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
98       if (!GA->isInterposable())
99         GV = GA->getAliasee();
100 
101     if (const Function *F = dyn_cast<Function>(GV)) {
102       if (!F->doesNotThrow())
103         Effects = true;
104       if (F->doesNotAccessMemory())
105         return;
106       if (F->onlyReadsMemory()) {
107         Read = true;
108         return;
109       }
110     }
111   }
112 
113   // Assume the worst.
114   Write = true;
115   Read = true;
116   Effects = true;
117 }
118 
119 // Determine whether MI reads memory, writes memory, and/or has side
120 // effects.
121 static void Query(const MachineInstr *MI, AliasAnalysis &AA,
122                   bool &Read, bool &Write, bool &Effects) {
123   assert(!MI->isPosition());
124   assert(!MI->isTerminator());
125   assert(!MI->isDebugValue());
126 
127   // Check for loads.
128   if (MI->mayLoad() && !MI->isInvariantLoad(&AA))
129     Read = true;
130 
131   // Check for stores.
132   if (MI->mayStore())
133     Write = true;
134   else if (MI->hasOrderedMemoryRef()) {
135     switch (MI->getOpcode()) {
136     case WebAssembly::DIV_S_I32: case WebAssembly::DIV_S_I64:
137     case WebAssembly::REM_S_I32: case WebAssembly::REM_S_I64:
138     case WebAssembly::DIV_U_I32: case WebAssembly::DIV_U_I64:
139     case WebAssembly::REM_U_I32: case WebAssembly::REM_U_I64:
140     case WebAssembly::I32_TRUNC_S_F32: case WebAssembly::I64_TRUNC_S_F32:
141     case WebAssembly::I32_TRUNC_S_F64: case WebAssembly::I64_TRUNC_S_F64:
142     case WebAssembly::I32_TRUNC_U_F32: case WebAssembly::I64_TRUNC_U_F32:
143     case WebAssembly::I32_TRUNC_U_F64: case WebAssembly::I64_TRUNC_U_F64:
144       // These instruction have hasUnmodeledSideEffects() returning true
145       // because they trap on overflow and invalid so they can't be arbitrarily
146       // moved, however hasOrderedMemoryRef() interprets this plus their lack
147       // of memoperands as having a potential unknown memory reference.
148       break;
149     default:
150       // Record potential stores, unless it's a call, as calls are handled
151       // specially below.
152       if (!MI->isCall())
153         Write = true;
154       break;
155     }
156   }
157 
158   // Check for side effects.
159   if (MI->hasUnmodeledSideEffects()) {
160     switch (MI->getOpcode()) {
161     case WebAssembly::DIV_S_I32: case WebAssembly::DIV_S_I64:
162     case WebAssembly::REM_S_I32: case WebAssembly::REM_S_I64:
163     case WebAssembly::DIV_U_I32: case WebAssembly::DIV_U_I64:
164     case WebAssembly::REM_U_I32: case WebAssembly::REM_U_I64:
165     case WebAssembly::I32_TRUNC_S_F32: case WebAssembly::I64_TRUNC_S_F32:
166     case WebAssembly::I32_TRUNC_S_F64: case WebAssembly::I64_TRUNC_S_F64:
167     case WebAssembly::I32_TRUNC_U_F32: case WebAssembly::I64_TRUNC_U_F32:
168     case WebAssembly::I32_TRUNC_U_F64: case WebAssembly::I64_TRUNC_U_F64:
169       // These instructions have hasUnmodeledSideEffects() returning true
170       // because they trap on overflow and invalid so they can't be arbitrarily
171       // moved, however in the specific case of register stackifying, it is safe
172       // to move them because overflow and invalid are Undefined Behavior.
173       break;
174     default:
175       Effects = true;
176       break;
177     }
178   }
179 
180   // Analyze calls.
181   if (MI->isCall()) {
182     switch (MI->getOpcode()) {
183     case WebAssembly::CALL_VOID:
184       QueryCallee(MI, 0, Read, Write, Effects);
185       break;
186     case WebAssembly::CALL_I32:
187     case WebAssembly::CALL_I64:
188     case WebAssembly::CALL_F32:
189     case WebAssembly::CALL_F64:
190       QueryCallee(MI, 1, Read, Write, Effects);
191       break;
192     case WebAssembly::CALL_INDIRECT_VOID:
193     case WebAssembly::CALL_INDIRECT_I32:
194     case WebAssembly::CALL_INDIRECT_I64:
195     case WebAssembly::CALL_INDIRECT_F32:
196     case WebAssembly::CALL_INDIRECT_F64:
197       Read = true;
198       Write = true;
199       Effects = true;
200       break;
201     default:
202       llvm_unreachable("unexpected call opcode");
203     }
204   }
205 }
206 
207 // Test whether Def is safe and profitable to rematerialize.
208 static bool ShouldRematerialize(const MachineInstr *Def, AliasAnalysis &AA,
209                                 const WebAssemblyInstrInfo *TII) {
210   return Def->isAsCheapAsAMove() &&
211          TII->isTriviallyReMaterializable(Def, &AA);
212 }
213 
214 // Identify the definition for this register at this point. This is a
215 // generalization of MachineRegisterInfo::getUniqueVRegDef that uses
216 // LiveIntervals to handle complex cases.
217 static MachineInstr *GetVRegDef(unsigned Reg, const MachineInstr *Insert,
218                                 const MachineRegisterInfo &MRI,
219                                 const LiveIntervals &LIS)
220 {
221   // Most registers are in SSA form here so we try a quick MRI query first.
222   if (MachineInstr *Def = MRI.getUniqueVRegDef(Reg))
223     return Def;
224 
225   // MRI doesn't know what the Def is. Try asking LIS.
226   if (const VNInfo *ValNo = LIS.getInterval(Reg).getVNInfoBefore(
227           LIS.getInstructionIndex(*Insert)))
228     return LIS.getInstructionFromIndex(ValNo->def);
229 
230   return nullptr;
231 }
232 
233 // Test whether Reg, as defined at Def, has exactly one use. This is a
234 // generalization of MachineRegisterInfo::hasOneUse that uses LiveIntervals
235 // to handle complex cases.
236 static bool HasOneUse(unsigned Reg, MachineInstr *Def,
237                       MachineRegisterInfo &MRI, MachineDominatorTree &MDT,
238                       LiveIntervals &LIS) {
239   // Most registers are in SSA form here so we try a quick MRI query first.
240   if (MRI.hasOneUse(Reg))
241     return true;
242 
243   bool HasOne = false;
244   const LiveInterval &LI = LIS.getInterval(Reg);
245   const VNInfo *DefVNI = LI.getVNInfoAt(
246       LIS.getInstructionIndex(*Def).getRegSlot());
247   assert(DefVNI);
248   for (auto I : MRI.use_operands(Reg)) {
249     const auto &Result = LI.Query(LIS.getInstructionIndex(*I.getParent()));
250     if (Result.valueIn() == DefVNI) {
251       if (!Result.isKill())
252         return false;
253       if (HasOne)
254         return false;
255       HasOne = true;
256     }
257   }
258   return HasOne;
259 }
260 
261 // Test whether it's safe to move Def to just before Insert.
262 // TODO: Compute memory dependencies in a way that doesn't require always
263 // walking the block.
264 // TODO: Compute memory dependencies in a way that uses AliasAnalysis to be
265 // more precise.
266 static bool IsSafeToMove(const MachineInstr *Def, const MachineInstr *Insert,
267                          AliasAnalysis &AA, const LiveIntervals &LIS,
268                          const MachineRegisterInfo &MRI) {
269   assert(Def->getParent() == Insert->getParent());
270 
271   // Check for register dependencies.
272   for (const MachineOperand &MO : Def->operands()) {
273     if (!MO.isReg() || MO.isUndef())
274       continue;
275     unsigned Reg = MO.getReg();
276 
277     // If the register is dead here and at Insert, ignore it.
278     if (MO.isDead() && Insert->definesRegister(Reg) &&
279         !Insert->readsRegister(Reg))
280       continue;
281 
282     if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
283       // Ignore ARGUMENTS; it's just used to keep the ARGUMENT_* instructions
284       // from moving down, and we've already checked for that.
285       if (Reg == WebAssembly::ARGUMENTS)
286         continue;
287       // If the physical register is never modified, ignore it.
288       if (!MRI.isPhysRegModified(Reg))
289         continue;
290       // Otherwise, it's a physical register with unknown liveness.
291       return false;
292     }
293 
294     // Ask LiveIntervals whether moving this virtual register use or def to
295     // Insert will change which value numbers are seen.
296     //
297     // If the operand is a use of a register that is also defined in the same
298     // instruction, test that the newly defined value reaches the insert point,
299     // since the operand will be moving along with the def.
300     const LiveInterval &LI = LIS.getInterval(Reg);
301     VNInfo *DefVNI =
302         (MO.isDef() || Def->definesRegister(Reg)) ?
303         LI.getVNInfoAt(LIS.getInstructionIndex(*Def).getRegSlot()) :
304         LI.getVNInfoBefore(LIS.getInstructionIndex(*Def));
305     assert(DefVNI && "Instruction input missing value number");
306     VNInfo *InsVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*Insert));
307     if (InsVNI && DefVNI != InsVNI)
308       return false;
309   }
310 
311   bool Read = false, Write = false, Effects = false;
312   Query(Def, AA, Read, Write, Effects);
313 
314   // If the instruction does not access memory and has no side effects, it has
315   // no additional dependencies.
316   if (!Read && !Write && !Effects)
317     return true;
318 
319   // Scan through the intervening instructions between Def and Insert.
320   MachineBasicBlock::const_iterator D(Def), I(Insert);
321   for (--I; I != D; --I) {
322     bool InterveningRead = false;
323     bool InterveningWrite = false;
324     bool InterveningEffects = false;
325     Query(I, AA, InterveningRead, InterveningWrite, InterveningEffects);
326     if (Effects && InterveningEffects)
327       return false;
328     if (Read && InterveningWrite)
329       return false;
330     if (Write && (InterveningRead || InterveningWrite))
331       return false;
332   }
333 
334   return true;
335 }
336 
337 /// Test whether OneUse, a use of Reg, dominates all of Reg's other uses.
338 static bool OneUseDominatesOtherUses(unsigned Reg, const MachineOperand &OneUse,
339                                      const MachineBasicBlock &MBB,
340                                      const MachineRegisterInfo &MRI,
341                                      const MachineDominatorTree &MDT,
342                                      LiveIntervals &LIS) {
343   const LiveInterval &LI = LIS.getInterval(Reg);
344 
345   const MachineInstr *OneUseInst = OneUse.getParent();
346   VNInfo *OneUseVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*OneUseInst));
347 
348   for (const MachineOperand &Use : MRI.use_operands(Reg)) {
349     if (&Use == &OneUse)
350       continue;
351 
352     const MachineInstr *UseInst = Use.getParent();
353     VNInfo *UseVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*UseInst));
354 
355     if (UseVNI != OneUseVNI)
356       continue;
357 
358     const MachineInstr *OneUseInst = OneUse.getParent();
359     if (UseInst == OneUseInst) {
360       // Another use in the same instruction. We need to ensure that the one
361       // selected use happens "before" it.
362       if (&OneUse > &Use)
363         return false;
364     } else {
365       // Test that the use is dominated by the one selected use.
366       if (!MDT.dominates(OneUseInst, UseInst))
367         return false;
368     }
369   }
370   return true;
371 }
372 
373 /// Get the appropriate tee_local opcode for the given register class.
374 static unsigned GetTeeLocalOpcode(const TargetRegisterClass *RC) {
375   if (RC == &WebAssembly::I32RegClass)
376     return WebAssembly::TEE_LOCAL_I32;
377   if (RC == &WebAssembly::I64RegClass)
378     return WebAssembly::TEE_LOCAL_I64;
379   if (RC == &WebAssembly::F32RegClass)
380     return WebAssembly::TEE_LOCAL_F32;
381   if (RC == &WebAssembly::F64RegClass)
382     return WebAssembly::TEE_LOCAL_F64;
383   llvm_unreachable("Unexpected register class");
384 }
385 
386 // Shrink LI to its uses, cleaning up LI.
387 static void ShrinkToUses(LiveInterval &LI, LiveIntervals &LIS) {
388   if (LIS.shrinkToUses(&LI)) {
389     SmallVector<LiveInterval*, 4> SplitLIs;
390     LIS.splitSeparateComponents(LI, SplitLIs);
391   }
392 }
393 
394 /// A single-use def in the same block with no intervening memory or register
395 /// dependencies; move the def down and nest it with the current instruction.
396 static MachineInstr *MoveForSingleUse(unsigned Reg, MachineOperand& Op,
397                                       MachineInstr *Def,
398                                       MachineBasicBlock &MBB,
399                                       MachineInstr *Insert, LiveIntervals &LIS,
400                                       WebAssemblyFunctionInfo &MFI,
401                                       MachineRegisterInfo &MRI) {
402   DEBUG(dbgs() << "Move for single use: "; Def->dump());
403 
404   MBB.splice(Insert, &MBB, Def);
405   LIS.handleMove(*Def);
406 
407   if (MRI.hasOneDef(Reg) && MRI.hasOneUse(Reg)) {
408     // No one else is using this register for anything so we can just stackify
409     // it in place.
410     MFI.stackifyVReg(Reg);
411   } else {
412     // The register may have unrelated uses or defs; create a new register for
413     // just our one def and use so that we can stackify it.
414     unsigned NewReg = MRI.createVirtualRegister(MRI.getRegClass(Reg));
415     Def->getOperand(0).setReg(NewReg);
416     Op.setReg(NewReg);
417 
418     // Tell LiveIntervals about the new register.
419     LIS.createAndComputeVirtRegInterval(NewReg);
420 
421     // Tell LiveIntervals about the changes to the old register.
422     LiveInterval &LI = LIS.getInterval(Reg);
423     LIS.removeVRegDefAt(LI, LIS.getInstructionIndex(*Def).getRegSlot());
424     ShrinkToUses(LI, LIS);
425 
426     MFI.stackifyVReg(NewReg);
427 
428     DEBUG(dbgs() << " - Replaced register: "; Def->dump());
429   }
430 
431   ImposeStackOrdering(Def);
432   return Def;
433 }
434 
435 /// A trivially cloneable instruction; clone it and nest the new copy with the
436 /// current instruction.
437 static MachineInstr *
438 RematerializeCheapDef(unsigned Reg, MachineOperand &Op, MachineInstr *Def,
439                       MachineBasicBlock &MBB, MachineInstr *Insert,
440                       LiveIntervals &LIS, WebAssemblyFunctionInfo &MFI,
441                       MachineRegisterInfo &MRI, const WebAssemblyInstrInfo *TII,
442                       const WebAssemblyRegisterInfo *TRI) {
443   DEBUG(dbgs() << "Rematerializing cheap def: "; Def->dump());
444   DEBUG(dbgs() << " - for use in "; Op.getParent()->dump());
445 
446   unsigned NewReg = MRI.createVirtualRegister(MRI.getRegClass(Reg));
447   TII->reMaterialize(MBB, Insert, NewReg, 0, Def, *TRI);
448   Op.setReg(NewReg);
449   MachineInstr *Clone = &*std::prev(MachineBasicBlock::instr_iterator(Insert));
450   LIS.InsertMachineInstrInMaps(*Clone);
451   LIS.createAndComputeVirtRegInterval(NewReg);
452   MFI.stackifyVReg(NewReg);
453   ImposeStackOrdering(Clone);
454 
455   DEBUG(dbgs() << " - Cloned to "; Clone->dump());
456 
457   // Shrink the interval.
458   bool IsDead = MRI.use_empty(Reg);
459   if (!IsDead) {
460     LiveInterval &LI = LIS.getInterval(Reg);
461     ShrinkToUses(LI, LIS);
462     IsDead = !LI.liveAt(LIS.getInstructionIndex(*Def).getDeadSlot());
463   }
464 
465   // If that was the last use of the original, delete the original.
466   if (IsDead) {
467     DEBUG(dbgs() << " - Deleting original\n");
468     SlotIndex Idx = LIS.getInstructionIndex(*Def).getRegSlot();
469     LIS.removePhysRegDefAt(WebAssembly::ARGUMENTS, Idx);
470     LIS.removeInterval(Reg);
471     LIS.RemoveMachineInstrFromMaps(*Def);
472     Def->eraseFromParent();
473   }
474 
475   return Clone;
476 }
477 
478 /// A multiple-use def in the same block with no intervening memory or register
479 /// dependencies; move the def down, nest it with the current instruction, and
480 /// insert a tee_local to satisfy the rest of the uses. As an illustration,
481 /// rewrite this:
482 ///
483 ///    Reg = INST ...        // Def
484 ///    INST ..., Reg, ...    // Insert
485 ///    INST ..., Reg, ...
486 ///    INST ..., Reg, ...
487 ///
488 /// to this:
489 ///
490 ///    DefReg = INST ...     // Def (to become the new Insert)
491 ///    TeeReg, Reg = TEE_LOCAL_... DefReg
492 ///    INST ..., TeeReg, ... // Insert
493 ///    INST ..., NewReg, ...
494 ///    INST ..., NewReg, ...
495 ///
496 /// with DefReg and TeeReg stackified. This eliminates a get_local from the
497 /// resulting code.
498 static MachineInstr *MoveAndTeeForMultiUse(
499     unsigned Reg, MachineOperand &Op, MachineInstr *Def, MachineBasicBlock &MBB,
500     MachineInstr *Insert, LiveIntervals &LIS, WebAssemblyFunctionInfo &MFI,
501     MachineRegisterInfo &MRI, const WebAssemblyInstrInfo *TII) {
502   DEBUG(dbgs() << "Move and tee for multi-use:"; Def->dump());
503 
504   // Move Def into place.
505   MBB.splice(Insert, &MBB, Def);
506   LIS.handleMove(*Def);
507 
508   // Create the Tee and attach the registers.
509   const auto *RegClass = MRI.getRegClass(Reg);
510   unsigned TeeReg = MRI.createVirtualRegister(RegClass);
511   unsigned DefReg = MRI.createVirtualRegister(RegClass);
512   MachineOperand &DefMO = Def->getOperand(0);
513   MachineInstr *Tee = BuildMI(MBB, Insert, Insert->getDebugLoc(),
514                               TII->get(GetTeeLocalOpcode(RegClass)), TeeReg)
515                           .addReg(Reg, RegState::Define)
516                           .addReg(DefReg, getUndefRegState(DefMO.isDead()));
517   Op.setReg(TeeReg);
518   DefMO.setReg(DefReg);
519   SlotIndex TeeIdx = LIS.InsertMachineInstrInMaps(*Tee).getRegSlot();
520   SlotIndex DefIdx = LIS.getInstructionIndex(*Def).getRegSlot();
521 
522   // Tell LiveIntervals we moved the original vreg def from Def to Tee.
523   LiveInterval &LI = LIS.getInterval(Reg);
524   LiveInterval::iterator I = LI.FindSegmentContaining(DefIdx);
525   VNInfo *ValNo = LI.getVNInfoAt(DefIdx);
526   I->start = TeeIdx;
527   ValNo->def = TeeIdx;
528   ShrinkToUses(LI, LIS);
529 
530   // Finish stackifying the new regs.
531   LIS.createAndComputeVirtRegInterval(TeeReg);
532   LIS.createAndComputeVirtRegInterval(DefReg);
533   MFI.stackifyVReg(DefReg);
534   MFI.stackifyVReg(TeeReg);
535   ImposeStackOrdering(Def);
536   ImposeStackOrdering(Tee);
537 
538   DEBUG(dbgs() << " - Replaced register: "; Def->dump());
539   DEBUG(dbgs() << " - Tee instruction: "; Tee->dump());
540   return Def;
541 }
542 
543 namespace {
544 /// A stack for walking the tree of instructions being built, visiting the
545 /// MachineOperands in DFS order.
546 class TreeWalkerState {
547   typedef MachineInstr::mop_iterator mop_iterator;
548   typedef std::reverse_iterator<mop_iterator> mop_reverse_iterator;
549   typedef iterator_range<mop_reverse_iterator> RangeTy;
550   SmallVector<RangeTy, 4> Worklist;
551 
552 public:
553   explicit TreeWalkerState(MachineInstr *Insert) {
554     const iterator_range<mop_iterator> &Range = Insert->explicit_uses();
555     if (Range.begin() != Range.end())
556       Worklist.push_back(reverse(Range));
557   }
558 
559   bool Done() const { return Worklist.empty(); }
560 
561   MachineOperand &Pop() {
562     RangeTy &Range = Worklist.back();
563     MachineOperand &Op = *Range.begin();
564     Range = drop_begin(Range, 1);
565     if (Range.begin() == Range.end())
566       Worklist.pop_back();
567     assert((Worklist.empty() ||
568             Worklist.back().begin() != Worklist.back().end()) &&
569            "Empty ranges shouldn't remain in the worklist");
570     return Op;
571   }
572 
573   /// Push Instr's operands onto the stack to be visited.
574   void PushOperands(MachineInstr *Instr) {
575     const iterator_range<mop_iterator> &Range(Instr->explicit_uses());
576     if (Range.begin() != Range.end())
577       Worklist.push_back(reverse(Range));
578   }
579 
580   /// Some of Instr's operands are on the top of the stack; remove them and
581   /// re-insert them starting from the beginning (because we've commuted them).
582   void ResetTopOperands(MachineInstr *Instr) {
583     assert(HasRemainingOperands(Instr) &&
584            "Reseting operands should only be done when the instruction has "
585            "an operand still on the stack");
586     Worklist.back() = reverse(Instr->explicit_uses());
587   }
588 
589   /// Test whether Instr has operands remaining to be visited at the top of
590   /// the stack.
591   bool HasRemainingOperands(const MachineInstr *Instr) const {
592     if (Worklist.empty())
593       return false;
594     const RangeTy &Range = Worklist.back();
595     return Range.begin() != Range.end() && Range.begin()->getParent() == Instr;
596   }
597 
598   /// Test whether the given register is present on the stack, indicating an
599   /// operand in the tree that we haven't visited yet. Moving a definition of
600   /// Reg to a point in the tree after that would change its value.
601   bool IsOnStack(unsigned Reg) const {
602     for (const RangeTy &Range : Worklist)
603       for (const MachineOperand &MO : Range)
604         if (MO.isReg() && MO.getReg() == Reg)
605           return true;
606     return false;
607   }
608 };
609 
610 /// State to keep track of whether commuting is in flight or whether it's been
611 /// tried for the current instruction and didn't work.
612 class CommutingState {
613   /// There are effectively three states: the initial state where we haven't
614   /// started commuting anything and we don't know anything yet, the tenative
615   /// state where we've commuted the operands of the current instruction and are
616   /// revisting it, and the declined state where we've reverted the operands
617   /// back to their original order and will no longer commute it further.
618   bool TentativelyCommuting;
619   bool Declined;
620 
621   /// During the tentative state, these hold the operand indices of the commuted
622   /// operands.
623   unsigned Operand0, Operand1;
624 
625 public:
626   CommutingState() : TentativelyCommuting(false), Declined(false) {}
627 
628   /// Stackification for an operand was not successful due to ordering
629   /// constraints. If possible, and if we haven't already tried it and declined
630   /// it, commute Insert's operands and prepare to revisit it.
631   void MaybeCommute(MachineInstr *Insert, TreeWalkerState &TreeWalker,
632                     const WebAssemblyInstrInfo *TII) {
633     if (TentativelyCommuting) {
634       assert(!Declined &&
635              "Don't decline commuting until you've finished trying it");
636       // Commuting didn't help. Revert it.
637       TII->commuteInstruction(Insert, /*NewMI=*/false, Operand0, Operand1);
638       TentativelyCommuting = false;
639       Declined = true;
640     } else if (!Declined && TreeWalker.HasRemainingOperands(Insert)) {
641       Operand0 = TargetInstrInfo::CommuteAnyOperandIndex;
642       Operand1 = TargetInstrInfo::CommuteAnyOperandIndex;
643       if (TII->findCommutedOpIndices(Insert, Operand0, Operand1)) {
644         // Tentatively commute the operands and try again.
645         TII->commuteInstruction(Insert, /*NewMI=*/false, Operand0, Operand1);
646         TreeWalker.ResetTopOperands(Insert);
647         TentativelyCommuting = true;
648         Declined = false;
649       }
650     }
651   }
652 
653   /// Stackification for some operand was successful. Reset to the default
654   /// state.
655   void Reset() {
656     TentativelyCommuting = false;
657     Declined = false;
658   }
659 };
660 } // end anonymous namespace
661 
662 bool WebAssemblyRegStackify::runOnMachineFunction(MachineFunction &MF) {
663   DEBUG(dbgs() << "********** Register Stackifying **********\n"
664                   "********** Function: "
665                << MF.getName() << '\n');
666 
667   bool Changed = false;
668   MachineRegisterInfo &MRI = MF.getRegInfo();
669   WebAssemblyFunctionInfo &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
670   const auto *TII = MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
671   const auto *TRI = MF.getSubtarget<WebAssemblySubtarget>().getRegisterInfo();
672   AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
673   MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
674   LiveIntervals &LIS = getAnalysis<LiveIntervals>();
675 
676   // Walk the instructions from the bottom up. Currently we don't look past
677   // block boundaries, and the blocks aren't ordered so the block visitation
678   // order isn't significant, but we may want to change this in the future.
679   for (MachineBasicBlock &MBB : MF) {
680     // Don't use a range-based for loop, because we modify the list as we're
681     // iterating over it and the end iterator may change.
682     for (auto MII = MBB.rbegin(); MII != MBB.rend(); ++MII) {
683       MachineInstr *Insert = &*MII;
684       // Don't nest anything inside an inline asm, because we don't have
685       // constraints for $push inputs.
686       if (Insert->getOpcode() == TargetOpcode::INLINEASM)
687         continue;
688 
689       // Ignore debugging intrinsics.
690       if (Insert->getOpcode() == TargetOpcode::DBG_VALUE)
691         continue;
692 
693       // Iterate through the inputs in reverse order, since we'll be pulling
694       // operands off the stack in LIFO order.
695       CommutingState Commuting;
696       TreeWalkerState TreeWalker(Insert);
697       while (!TreeWalker.Done()) {
698         MachineOperand &Op = TreeWalker.Pop();
699 
700         // We're only interested in explicit virtual register operands.
701         if (!Op.isReg())
702           continue;
703 
704         unsigned Reg = Op.getReg();
705         assert(Op.isUse() && "explicit_uses() should only iterate over uses");
706         assert(!Op.isImplicit() &&
707                "explicit_uses() should only iterate over explicit operands");
708         if (TargetRegisterInfo::isPhysicalRegister(Reg))
709           continue;
710 
711         // Identify the definition for this register at this point. Most
712         // registers are in SSA form here so we try a quick MRI query first.
713         MachineInstr *Def = GetVRegDef(Reg, Insert, MRI, LIS);
714         if (!Def)
715           continue;
716 
717         // Don't nest an INLINE_ASM def into anything, because we don't have
718         // constraints for $pop outputs.
719         if (Def->getOpcode() == TargetOpcode::INLINEASM)
720           continue;
721 
722         // Argument instructions represent live-in registers and not real
723         // instructions.
724         if (Def->getOpcode() == WebAssembly::ARGUMENT_I32 ||
725             Def->getOpcode() == WebAssembly::ARGUMENT_I64 ||
726             Def->getOpcode() == WebAssembly::ARGUMENT_F32 ||
727             Def->getOpcode() == WebAssembly::ARGUMENT_F64)
728           continue;
729 
730         // Decide which strategy to take. Prefer to move a single-use value
731         // over cloning it, and prefer cloning over introducing a tee_local.
732         // For moving, we require the def to be in the same block as the use;
733         // this makes things simpler (LiveIntervals' handleMove function only
734         // supports intra-block moves) and it's MachineSink's job to catch all
735         // the sinking opportunities anyway.
736         bool SameBlock = Def->getParent() == &MBB;
737         bool CanMove = SameBlock && IsSafeToMove(Def, Insert, AA, LIS, MRI) &&
738                        !TreeWalker.IsOnStack(Reg);
739         if (CanMove && HasOneUse(Reg, Def, MRI, MDT, LIS)) {
740           Insert = MoveForSingleUse(Reg, Op, Def, MBB, Insert, LIS, MFI, MRI);
741         } else if (ShouldRematerialize(Def, AA, TII)) {
742           Insert = RematerializeCheapDef(Reg, Op, Def, MBB, Insert, LIS, MFI,
743                                          MRI, TII, TRI);
744         } else if (CanMove &&
745                    OneUseDominatesOtherUses(Reg, Op, MBB, MRI, MDT, LIS)) {
746           Insert = MoveAndTeeForMultiUse(Reg, Op, Def, MBB, Insert, LIS, MFI,
747                                          MRI, TII);
748         } else {
749           // We failed to stackify the operand. If the problem was ordering
750           // constraints, Commuting may be able to help.
751           if (!CanMove && SameBlock)
752             Commuting.MaybeCommute(Insert, TreeWalker, TII);
753           // Proceed to the next operand.
754           continue;
755         }
756 
757         // We stackified an operand. Add the defining instruction's operands to
758         // the worklist stack now to continue to build an ever deeper tree.
759         Commuting.Reset();
760         TreeWalker.PushOperands(Insert);
761       }
762 
763       // If we stackified any operands, skip over the tree to start looking for
764       // the next instruction we can build a tree on.
765       if (Insert != &*MII) {
766         ImposeStackOrdering(&*MII);
767         MII = std::prev(
768             llvm::make_reverse_iterator(MachineBasicBlock::iterator(Insert)));
769         Changed = true;
770       }
771     }
772   }
773 
774   // If we used EXPR_STACK anywhere, add it to the live-in sets everywhere so
775   // that it never looks like a use-before-def.
776   if (Changed) {
777     MF.getRegInfo().addLiveIn(WebAssembly::EXPR_STACK);
778     for (MachineBasicBlock &MBB : MF)
779       MBB.addLiveIn(WebAssembly::EXPR_STACK);
780   }
781 
782 #ifndef NDEBUG
783   // Verify that pushes and pops are performed in LIFO order.
784   SmallVector<unsigned, 0> Stack;
785   for (MachineBasicBlock &MBB : MF) {
786     for (MachineInstr &MI : MBB) {
787       if (MI.isDebugValue())
788         continue;
789       for (MachineOperand &MO : reverse(MI.explicit_operands())) {
790         if (!MO.isReg())
791           continue;
792         unsigned Reg = MO.getReg();
793 
794         if (MFI.isVRegStackified(Reg)) {
795           if (MO.isDef())
796             Stack.push_back(Reg);
797           else
798             assert(Stack.pop_back_val() == Reg &&
799                    "Register stack pop should be paired with a push");
800         }
801       }
802     }
803     // TODO: Generalize this code to support keeping values on the stack across
804     // basic block boundaries.
805     assert(Stack.empty() &&
806            "Register stack pushes and pops should be balanced");
807   }
808 #endif
809 
810   return Changed;
811 }
812