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