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