11462faadSDan Gohman //===-- WebAssemblyRegStackify.cpp - Register Stackification --------------===// 21462faadSDan Gohman // 31462faadSDan Gohman // The LLVM Compiler Infrastructure 41462faadSDan Gohman // 51462faadSDan Gohman // This file is distributed under the University of Illinois Open Source 61462faadSDan Gohman // License. See LICENSE.TXT for details. 71462faadSDan Gohman // 81462faadSDan Gohman //===----------------------------------------------------------------------===// 91462faadSDan Gohman /// 101462faadSDan Gohman /// \file 111462faadSDan Gohman /// \brief This file implements a register stacking pass. 121462faadSDan Gohman /// 131462faadSDan Gohman /// This pass reorders instructions to put register uses and defs in an order 141462faadSDan Gohman /// such that they form single-use expression trees. Registers fitting this form 151462faadSDan Gohman /// are then marked as "stackified", meaning references to them are replaced by 161462faadSDan Gohman /// "push" and "pop" from the stack. 171462faadSDan Gohman /// 1831448f16SDan Gohman /// This is primarily a code size optimization, since temporary values on the 191462faadSDan Gohman /// expression don't need to be named. 201462faadSDan Gohman /// 211462faadSDan Gohman //===----------------------------------------------------------------------===// 221462faadSDan Gohman 231462faadSDan Gohman #include "WebAssembly.h" 244ba4816bSDan Gohman #include "MCTargetDesc/WebAssemblyMCTargetDesc.h" // for WebAssembly::ARGUMENT_* 257a6b9825SDan Gohman #include "WebAssemblyMachineFunctionInfo.h" 26b6fd39a3SDan Gohman #include "WebAssemblySubtarget.h" 2781719f85SDan Gohman #include "llvm/Analysis/AliasAnalysis.h" 288887d1faSDan Gohman #include "llvm/CodeGen/LiveIntervalAnalysis.h" 291462faadSDan Gohman #include "llvm/CodeGen/MachineBlockFrequencyInfo.h" 30adf28177SDan Gohman #include "llvm/CodeGen/MachineDominators.h" 31adf28177SDan Gohman #include "llvm/CodeGen/MachineInstrBuilder.h" 321462faadSDan Gohman #include "llvm/CodeGen/MachineRegisterInfo.h" 331462faadSDan Gohman #include "llvm/CodeGen/Passes.h" 341462faadSDan Gohman #include "llvm/Support/Debug.h" 351462faadSDan Gohman #include "llvm/Support/raw_ostream.h" 361462faadSDan Gohman using namespace llvm; 371462faadSDan Gohman 381462faadSDan Gohman #define DEBUG_TYPE "wasm-reg-stackify" 391462faadSDan Gohman 401462faadSDan Gohman namespace { 411462faadSDan Gohman class WebAssemblyRegStackify final : public MachineFunctionPass { 421462faadSDan Gohman const char *getPassName() const override { 431462faadSDan Gohman return "WebAssembly Register Stackify"; 441462faadSDan Gohman } 451462faadSDan Gohman 461462faadSDan Gohman void getAnalysisUsage(AnalysisUsage &AU) const override { 471462faadSDan Gohman AU.setPreservesCFG(); 4881719f85SDan Gohman AU.addRequired<AAResultsWrapperPass>(); 49adf28177SDan Gohman AU.addRequired<MachineDominatorTree>(); 508887d1faSDan Gohman AU.addRequired<LiveIntervals>(); 511462faadSDan Gohman AU.addPreserved<MachineBlockFrequencyInfo>(); 528887d1faSDan Gohman AU.addPreserved<SlotIndexes>(); 538887d1faSDan Gohman AU.addPreserved<LiveIntervals>(); 548887d1faSDan Gohman AU.addPreservedID(LiveVariablesID); 55adf28177SDan Gohman AU.addPreserved<MachineDominatorTree>(); 561462faadSDan Gohman MachineFunctionPass::getAnalysisUsage(AU); 571462faadSDan Gohman } 581462faadSDan Gohman 591462faadSDan Gohman bool runOnMachineFunction(MachineFunction &MF) override; 601462faadSDan Gohman 611462faadSDan Gohman public: 621462faadSDan Gohman static char ID; // Pass identification, replacement for typeid 631462faadSDan Gohman WebAssemblyRegStackify() : MachineFunctionPass(ID) {} 641462faadSDan Gohman }; 651462faadSDan Gohman } // end anonymous namespace 661462faadSDan Gohman 671462faadSDan Gohman char WebAssemblyRegStackify::ID = 0; 681462faadSDan Gohman FunctionPass *llvm::createWebAssemblyRegStackify() { 691462faadSDan Gohman return new WebAssemblyRegStackify(); 701462faadSDan Gohman } 711462faadSDan Gohman 72b0992dafSDan Gohman // Decorate the given instruction with implicit operands that enforce the 738887d1faSDan Gohman // expression stack ordering constraints for an instruction which is on 748887d1faSDan Gohman // the expression stack. 758887d1faSDan Gohman static void ImposeStackOrdering(MachineInstr *MI) { 764da4abd8SDan Gohman // Write the opaque EXPR_STACK register. 774da4abd8SDan Gohman if (!MI->definesRegister(WebAssembly::EXPR_STACK)) 78b0992dafSDan Gohman MI->addOperand(MachineOperand::CreateReg(WebAssembly::EXPR_STACK, 79b0992dafSDan Gohman /*isDef=*/true, 80b0992dafSDan Gohman /*isImp=*/true)); 814da4abd8SDan Gohman 824da4abd8SDan Gohman // Also read the opaque EXPR_STACK register. 83a712a6c4SDan Gohman if (!MI->readsRegister(WebAssembly::EXPR_STACK)) 84b0992dafSDan Gohman MI->addOperand(MachineOperand::CreateReg(WebAssembly::EXPR_STACK, 85b0992dafSDan Gohman /*isDef=*/false, 86b0992dafSDan Gohman /*isImp=*/true)); 87b0992dafSDan Gohman } 88b0992dafSDan Gohman 898887d1faSDan Gohman // Test whether it's safe to move Def to just before Insert. 9081719f85SDan Gohman // TODO: Compute memory dependencies in a way that doesn't require always 9181719f85SDan Gohman // walking the block. 9281719f85SDan Gohman // TODO: Compute memory dependencies in a way that uses AliasAnalysis to be 9381719f85SDan Gohman // more precise. 9481719f85SDan Gohman static bool IsSafeToMove(const MachineInstr *Def, const MachineInstr *Insert, 95adf28177SDan Gohman AliasAnalysis &AA, const LiveIntervals &LIS, 96adf28177SDan Gohman const MachineRegisterInfo &MRI) { 97391a98afSDan Gohman assert(Def->getParent() == Insert->getParent()); 9881719f85SDan Gohman bool SawStore = false, SawSideEffects = false; 9981719f85SDan Gohman MachineBasicBlock::const_iterator D(Def), I(Insert); 1008887d1faSDan Gohman 1018887d1faSDan Gohman // Check for register dependencies. 1028887d1faSDan Gohman for (const MachineOperand &MO : Def->operands()) { 1038887d1faSDan Gohman if (!MO.isReg() || MO.isUndef()) 1048887d1faSDan Gohman continue; 1058887d1faSDan Gohman unsigned Reg = MO.getReg(); 1068887d1faSDan Gohman 1078887d1faSDan Gohman // If the register is dead here and at Insert, ignore it. 1088887d1faSDan Gohman if (MO.isDead() && Insert->definesRegister(Reg) && 1098887d1faSDan Gohman !Insert->readsRegister(Reg)) 1108887d1faSDan Gohman continue; 1118887d1faSDan Gohman 1128887d1faSDan Gohman if (TargetRegisterInfo::isPhysicalRegister(Reg)) { 1130cfb5f85SDan Gohman // Ignore ARGUMENTS; it's just used to keep the ARGUMENT_* instructions 1140cfb5f85SDan Gohman // from moving down, and we've already checked for that. 1150cfb5f85SDan Gohman if (Reg == WebAssembly::ARGUMENTS) 1160cfb5f85SDan Gohman continue; 1178887d1faSDan Gohman // If the physical register is never modified, ignore it. 1188887d1faSDan Gohman if (!MRI.isPhysRegModified(Reg)) 1198887d1faSDan Gohman continue; 1208887d1faSDan Gohman // Otherwise, it's a physical register with unknown liveness. 1218887d1faSDan Gohman return false; 1228887d1faSDan Gohman } 1238887d1faSDan Gohman 1248887d1faSDan Gohman // Ask LiveIntervals whether moving this virtual register use or def to 1250cfb5f85SDan Gohman // Insert will change which value numbers are seen. 1268887d1faSDan Gohman const LiveInterval &LI = LIS.getInterval(Reg); 127b6fd39a3SDan Gohman VNInfo *DefVNI = 12813d3b9b7SJF Bastien MO.isDef() ? LI.getVNInfoAt(LIS.getInstructionIndex(*Def).getRegSlot()) 12913d3b9b7SJF Bastien : LI.getVNInfoBefore(LIS.getInstructionIndex(*Def)); 1308887d1faSDan Gohman assert(DefVNI && "Instruction input missing value number"); 13113d3b9b7SJF Bastien VNInfo *InsVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*Insert)); 1328887d1faSDan Gohman if (InsVNI && DefVNI != InsVNI) 1338887d1faSDan Gohman return false; 1348887d1faSDan Gohman } 1358887d1faSDan Gohman 136f8f8f093SDerek Schuff SawStore = Def->isCall() || Def->mayStore(); 1378887d1faSDan Gohman // Check for memory dependencies and side effects. 13881719f85SDan Gohman for (--I; I != D; --I) 1397e64917fSDan Gohman SawSideEffects |= !I->isSafeToMove(&AA, SawStore); 14081719f85SDan Gohman return !(SawStore && Def->mayLoad() && !Def->isInvariantLoad(&AA)) && 14181719f85SDan Gohman !(SawSideEffects && !Def->isSafeToMove(&AA, SawStore)); 14281719f85SDan Gohman } 14381719f85SDan Gohman 144adf28177SDan Gohman /// Test whether OneUse, a use of Reg, dominates all of Reg's other uses. 145adf28177SDan Gohman static bool OneUseDominatesOtherUses(unsigned Reg, const MachineOperand &OneUse, 146adf28177SDan Gohman const MachineBasicBlock &MBB, 147adf28177SDan Gohman const MachineRegisterInfo &MRI, 1480cfb5f85SDan Gohman const MachineDominatorTree &MDT, 1490cfb5f85SDan Gohman LiveIntervals &LIS) { 1500cfb5f85SDan Gohman const LiveInterval &LI = LIS.getInterval(Reg); 1510cfb5f85SDan Gohman 1520cfb5f85SDan Gohman const MachineInstr *OneUseInst = OneUse.getParent(); 1530cfb5f85SDan Gohman VNInfo *OneUseVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*OneUseInst)); 1540cfb5f85SDan Gohman 155adf28177SDan Gohman for (const MachineOperand &Use : MRI.use_operands(Reg)) { 156adf28177SDan Gohman if (&Use == &OneUse) 157adf28177SDan Gohman continue; 1580cfb5f85SDan Gohman 159adf28177SDan Gohman const MachineInstr *UseInst = Use.getParent(); 1600cfb5f85SDan Gohman VNInfo *UseVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*UseInst)); 1610cfb5f85SDan Gohman 1620cfb5f85SDan Gohman if (UseVNI != OneUseVNI) 1630cfb5f85SDan Gohman continue; 1640cfb5f85SDan Gohman 165adf28177SDan Gohman const MachineInstr *OneUseInst = OneUse.getParent(); 166adf28177SDan Gohman if (UseInst->getOpcode() == TargetOpcode::PHI) { 167adf28177SDan Gohman // Test that the PHI use, which happens on the CFG edge rather than 168adf28177SDan Gohman // within the PHI's own block, is dominated by the one selected use. 169adf28177SDan Gohman const MachineBasicBlock *Pred = 170adf28177SDan Gohman UseInst->getOperand(&Use - &UseInst->getOperand(0) + 1).getMBB(); 171adf28177SDan Gohman if (!MDT.dominates(&MBB, Pred)) 172adf28177SDan Gohman return false; 173adf28177SDan Gohman } else if (UseInst == OneUseInst) { 174adf28177SDan Gohman // Another use in the same instruction. We need to ensure that the one 175adf28177SDan Gohman // selected use happens "before" it. 176adf28177SDan Gohman if (&OneUse > &Use) 177adf28177SDan Gohman return false; 178adf28177SDan Gohman } else { 179adf28177SDan Gohman // Test that the use is dominated by the one selected use. 180adf28177SDan Gohman if (!MDT.dominates(OneUseInst, UseInst)) 181adf28177SDan Gohman return false; 182adf28177SDan Gohman } 183adf28177SDan Gohman } 184adf28177SDan Gohman return true; 185adf28177SDan Gohman } 186adf28177SDan Gohman 187adf28177SDan Gohman /// Get the appropriate tee_local opcode for the given register class. 188adf28177SDan Gohman static unsigned GetTeeLocalOpcode(const TargetRegisterClass *RC) { 189adf28177SDan Gohman if (RC == &WebAssembly::I32RegClass) 190adf28177SDan Gohman return WebAssembly::TEE_LOCAL_I32; 191adf28177SDan Gohman if (RC == &WebAssembly::I64RegClass) 192adf28177SDan Gohman return WebAssembly::TEE_LOCAL_I64; 193adf28177SDan Gohman if (RC == &WebAssembly::F32RegClass) 194adf28177SDan Gohman return WebAssembly::TEE_LOCAL_F32; 195adf28177SDan Gohman if (RC == &WebAssembly::F64RegClass) 196adf28177SDan Gohman return WebAssembly::TEE_LOCAL_F64; 197adf28177SDan Gohman llvm_unreachable("Unexpected register class"); 198adf28177SDan Gohman } 199adf28177SDan Gohman 200adf28177SDan Gohman /// A single-use def in the same block with no intervening memory or register 201adf28177SDan Gohman /// dependencies; move the def down and nest it with the current instruction. 2020cfb5f85SDan Gohman static MachineInstr *MoveForSingleUse(unsigned Reg, MachineOperand& Op, 2030cfb5f85SDan Gohman MachineInstr *Def, 204adf28177SDan Gohman MachineBasicBlock &MBB, 205adf28177SDan Gohman MachineInstr *Insert, LiveIntervals &LIS, 2060cfb5f85SDan Gohman WebAssemblyFunctionInfo &MFI, 2070cfb5f85SDan Gohman MachineRegisterInfo &MRI) { 208adf28177SDan Gohman MBB.splice(Insert, &MBB, Def); 2091afd1e2bSJF Bastien LIS.handleMove(*Def); 2100cfb5f85SDan Gohman 2110cfb5f85SDan Gohman if (MRI.hasOneDef(Reg)) { 212adf28177SDan Gohman MFI.stackifyVReg(Reg); 2130cfb5f85SDan Gohman } else { 2140cfb5f85SDan Gohman unsigned NewReg = MRI.createVirtualRegister(MRI.getRegClass(Reg)); 2150cfb5f85SDan Gohman Def->getOperand(0).setReg(NewReg); 2160cfb5f85SDan Gohman Op.setReg(NewReg); 2170cfb5f85SDan Gohman 2180cfb5f85SDan Gohman // Tell LiveIntervals about the new register. 2190cfb5f85SDan Gohman LIS.createAndComputeVirtRegInterval(NewReg); 2200cfb5f85SDan Gohman 2210cfb5f85SDan Gohman // Tell LiveIntervals about the changes to the old register. 2220cfb5f85SDan Gohman LiveInterval &LI = LIS.getInterval(Reg); 2230cfb5f85SDan Gohman LIS.removeVRegDefAt(LI, LIS.getInstructionIndex(*Def).getRegSlot()); 2240cfb5f85SDan Gohman LIS.shrinkToUses(&LI); 2250cfb5f85SDan Gohman 2260cfb5f85SDan Gohman MFI.stackifyVReg(NewReg); 2270cfb5f85SDan Gohman } 2280cfb5f85SDan Gohman 229adf28177SDan Gohman ImposeStackOrdering(Def); 230adf28177SDan Gohman return Def; 231adf28177SDan Gohman } 232adf28177SDan Gohman 233adf28177SDan Gohman /// A trivially cloneable instruction; clone it and nest the new copy with the 234adf28177SDan Gohman /// current instruction. 235adf28177SDan Gohman static MachineInstr * 236adf28177SDan Gohman RematerializeCheapDef(unsigned Reg, MachineOperand &Op, MachineInstr *Def, 237adf28177SDan Gohman MachineBasicBlock &MBB, MachineInstr *Insert, 238adf28177SDan Gohman LiveIntervals &LIS, WebAssemblyFunctionInfo &MFI, 239adf28177SDan Gohman MachineRegisterInfo &MRI, const WebAssemblyInstrInfo *TII, 240adf28177SDan Gohman const WebAssemblyRegisterInfo *TRI) { 241adf28177SDan Gohman unsigned NewReg = MRI.createVirtualRegister(MRI.getRegClass(Reg)); 242adf28177SDan Gohman TII->reMaterialize(MBB, Insert, NewReg, 0, Def, *TRI); 243adf28177SDan Gohman Op.setReg(NewReg); 244adf28177SDan Gohman MachineInstr *Clone = &*std::prev(MachineBasicBlock::instr_iterator(Insert)); 24513d3b9b7SJF Bastien LIS.InsertMachineInstrInMaps(*Clone); 246adf28177SDan Gohman LIS.createAndComputeVirtRegInterval(NewReg); 247adf28177SDan Gohman MFI.stackifyVReg(NewReg); 248adf28177SDan Gohman ImposeStackOrdering(Clone); 249adf28177SDan Gohman 2500cfb5f85SDan Gohman // Shrink the interval. 2510cfb5f85SDan Gohman bool IsDead = MRI.use_empty(Reg); 2520cfb5f85SDan Gohman if (!IsDead) { 2530cfb5f85SDan Gohman LiveInterval &LI = LIS.getInterval(Reg); 2540cfb5f85SDan Gohman LIS.shrinkToUses(&LI); 2550cfb5f85SDan Gohman IsDead = !LI.liveAt(LIS.getInstructionIndex(*Def).getDeadSlot()); 2560cfb5f85SDan Gohman } 2570cfb5f85SDan Gohman 258adf28177SDan Gohman // If that was the last use of the original, delete the original. 2590cfb5f85SDan Gohman if (IsDead) { 26013d3b9b7SJF Bastien SlotIndex Idx = LIS.getInstructionIndex(*Def).getRegSlot(); 261adf28177SDan Gohman LIS.removePhysRegDefAt(WebAssembly::ARGUMENTS, Idx); 262adf28177SDan Gohman LIS.removeInterval(Reg); 26313d3b9b7SJF Bastien LIS.RemoveMachineInstrFromMaps(*Def); 264adf28177SDan Gohman Def->eraseFromParent(); 265adf28177SDan Gohman } 2660cfb5f85SDan Gohman 267adf28177SDan Gohman return Clone; 268adf28177SDan Gohman } 269adf28177SDan Gohman 270adf28177SDan Gohman /// A multiple-use def in the same block with no intervening memory or register 271adf28177SDan Gohman /// dependencies; move the def down, nest it with the current instruction, and 272adf28177SDan Gohman /// insert a tee_local to satisfy the rest of the uses. As an illustration, 273adf28177SDan Gohman /// rewrite this: 274adf28177SDan Gohman /// 275adf28177SDan Gohman /// Reg = INST ... // Def 276adf28177SDan Gohman /// INST ..., Reg, ... // Insert 277adf28177SDan Gohman /// INST ..., Reg, ... 278adf28177SDan Gohman /// INST ..., Reg, ... 279adf28177SDan Gohman /// 280adf28177SDan Gohman /// to this: 281adf28177SDan Gohman /// 2828aa237c3SDan Gohman /// DefReg = INST ... // Def (to become the new Insert) 2838aa237c3SDan Gohman /// TeeReg, NewReg = TEE_LOCAL_... DefReg 284adf28177SDan Gohman /// INST ..., TeeReg, ... // Insert 285adf28177SDan Gohman /// INST ..., NewReg, ... 286adf28177SDan Gohman /// INST ..., NewReg, ... 287adf28177SDan Gohman /// 2888aa237c3SDan Gohman /// with DefReg and TeeReg stackified. This eliminates a get_local from the 289adf28177SDan Gohman /// resulting code. 290adf28177SDan Gohman static MachineInstr *MoveAndTeeForMultiUse( 291adf28177SDan Gohman unsigned Reg, MachineOperand &Op, MachineInstr *Def, MachineBasicBlock &MBB, 292adf28177SDan Gohman MachineInstr *Insert, LiveIntervals &LIS, WebAssemblyFunctionInfo &MFI, 293adf28177SDan Gohman MachineRegisterInfo &MRI, const WebAssemblyInstrInfo *TII) { 294adf28177SDan Gohman MBB.splice(Insert, &MBB, Def); 2951afd1e2bSJF Bastien LIS.handleMove(*Def); 296adf28177SDan Gohman const auto *RegClass = MRI.getRegClass(Reg); 297adf28177SDan Gohman unsigned NewReg = MRI.createVirtualRegister(RegClass); 298adf28177SDan Gohman unsigned TeeReg = MRI.createVirtualRegister(RegClass); 2998aa237c3SDan Gohman unsigned DefReg = MRI.createVirtualRegister(RegClass); 300*33e694a8SDan Gohman MachineOperand &DefMO = Def->getOperand(0); 301adf28177SDan Gohman MRI.replaceRegWith(Reg, NewReg); 302adf28177SDan Gohman MachineInstr *Tee = BuildMI(MBB, Insert, Insert->getDebugLoc(), 303adf28177SDan Gohman TII->get(GetTeeLocalOpcode(RegClass)), TeeReg) 304adf28177SDan Gohman .addReg(NewReg, RegState::Define) 305*33e694a8SDan Gohman .addReg(DefReg, getUndefRegState(DefMO.isDead())); 306adf28177SDan Gohman Op.setReg(TeeReg); 307*33e694a8SDan Gohman DefMO.setReg(DefReg); 30813d3b9b7SJF Bastien LIS.InsertMachineInstrInMaps(*Tee); 3098aa237c3SDan Gohman LIS.removeInterval(Reg); 310adf28177SDan Gohman LIS.createAndComputeVirtRegInterval(NewReg); 311adf28177SDan Gohman LIS.createAndComputeVirtRegInterval(TeeReg); 3128aa237c3SDan Gohman LIS.createAndComputeVirtRegInterval(DefReg); 3138aa237c3SDan Gohman MFI.stackifyVReg(DefReg); 314adf28177SDan Gohman MFI.stackifyVReg(TeeReg); 315adf28177SDan Gohman ImposeStackOrdering(Def); 316adf28177SDan Gohman ImposeStackOrdering(Tee); 317adf28177SDan Gohman return Def; 318adf28177SDan Gohman } 319adf28177SDan Gohman 320adf28177SDan Gohman namespace { 321adf28177SDan Gohman /// A stack for walking the tree of instructions being built, visiting the 322adf28177SDan Gohman /// MachineOperands in DFS order. 323adf28177SDan Gohman class TreeWalkerState { 324adf28177SDan Gohman typedef MachineInstr::mop_iterator mop_iterator; 325adf28177SDan Gohman typedef std::reverse_iterator<mop_iterator> mop_reverse_iterator; 326adf28177SDan Gohman typedef iterator_range<mop_reverse_iterator> RangeTy; 327adf28177SDan Gohman SmallVector<RangeTy, 4> Worklist; 328adf28177SDan Gohman 329adf28177SDan Gohman public: 330adf28177SDan Gohman explicit TreeWalkerState(MachineInstr *Insert) { 331adf28177SDan Gohman const iterator_range<mop_iterator> &Range = Insert->explicit_uses(); 332adf28177SDan Gohman if (Range.begin() != Range.end()) 333adf28177SDan Gohman Worklist.push_back(reverse(Range)); 334adf28177SDan Gohman } 335adf28177SDan Gohman 336adf28177SDan Gohman bool Done() const { return Worklist.empty(); } 337adf28177SDan Gohman 338adf28177SDan Gohman MachineOperand &Pop() { 339adf28177SDan Gohman RangeTy &Range = Worklist.back(); 340adf28177SDan Gohman MachineOperand &Op = *Range.begin(); 341adf28177SDan Gohman Range = drop_begin(Range, 1); 342adf28177SDan Gohman if (Range.begin() == Range.end()) 343adf28177SDan Gohman Worklist.pop_back(); 344adf28177SDan Gohman assert((Worklist.empty() || 345adf28177SDan Gohman Worklist.back().begin() != Worklist.back().end()) && 346adf28177SDan Gohman "Empty ranges shouldn't remain in the worklist"); 347adf28177SDan Gohman return Op; 348adf28177SDan Gohman } 349adf28177SDan Gohman 350adf28177SDan Gohman /// Push Instr's operands onto the stack to be visited. 351adf28177SDan Gohman void PushOperands(MachineInstr *Instr) { 352adf28177SDan Gohman const iterator_range<mop_iterator> &Range(Instr->explicit_uses()); 353adf28177SDan Gohman if (Range.begin() != Range.end()) 354adf28177SDan Gohman Worklist.push_back(reverse(Range)); 355adf28177SDan Gohman } 356adf28177SDan Gohman 357adf28177SDan Gohman /// Some of Instr's operands are on the top of the stack; remove them and 358adf28177SDan Gohman /// re-insert them starting from the beginning (because we've commuted them). 359adf28177SDan Gohman void ResetTopOperands(MachineInstr *Instr) { 360adf28177SDan Gohman assert(HasRemainingOperands(Instr) && 361adf28177SDan Gohman "Reseting operands should only be done when the instruction has " 362adf28177SDan Gohman "an operand still on the stack"); 363adf28177SDan Gohman Worklist.back() = reverse(Instr->explicit_uses()); 364adf28177SDan Gohman } 365adf28177SDan Gohman 366adf28177SDan Gohman /// Test whether Instr has operands remaining to be visited at the top of 367adf28177SDan Gohman /// the stack. 368adf28177SDan Gohman bool HasRemainingOperands(const MachineInstr *Instr) const { 369adf28177SDan Gohman if (Worklist.empty()) 370adf28177SDan Gohman return false; 371adf28177SDan Gohman const RangeTy &Range = Worklist.back(); 372adf28177SDan Gohman return Range.begin() != Range.end() && Range.begin()->getParent() == Instr; 373adf28177SDan Gohman } 374fbfe5ec4SDan Gohman 375fbfe5ec4SDan Gohman /// Test whether the given register is present on the stack, indicating an 376fbfe5ec4SDan Gohman /// operand in the tree that we haven't visited yet. Moving a definition of 377fbfe5ec4SDan Gohman /// Reg to a point in the tree after that would change its value. 378fbfe5ec4SDan Gohman bool IsOnStack(unsigned Reg) const { 379fbfe5ec4SDan Gohman for (const RangeTy &Range : Worklist) 380fbfe5ec4SDan Gohman for (const MachineOperand &MO : Range) 381fbfe5ec4SDan Gohman if (MO.isReg() && MO.getReg() == Reg) 382fbfe5ec4SDan Gohman return true; 383fbfe5ec4SDan Gohman return false; 384fbfe5ec4SDan Gohman } 385adf28177SDan Gohman }; 386adf28177SDan Gohman 387adf28177SDan Gohman /// State to keep track of whether commuting is in flight or whether it's been 388adf28177SDan Gohman /// tried for the current instruction and didn't work. 389adf28177SDan Gohman class CommutingState { 390adf28177SDan Gohman /// There are effectively three states: the initial state where we haven't 391adf28177SDan Gohman /// started commuting anything and we don't know anything yet, the tenative 392adf28177SDan Gohman /// state where we've commuted the operands of the current instruction and are 393adf28177SDan Gohman /// revisting it, and the declined state where we've reverted the operands 394adf28177SDan Gohman /// back to their original order and will no longer commute it further. 395adf28177SDan Gohman bool TentativelyCommuting; 396adf28177SDan Gohman bool Declined; 397adf28177SDan Gohman 398adf28177SDan Gohman /// During the tentative state, these hold the operand indices of the commuted 399adf28177SDan Gohman /// operands. 400adf28177SDan Gohman unsigned Operand0, Operand1; 401adf28177SDan Gohman 402adf28177SDan Gohman public: 403adf28177SDan Gohman CommutingState() : TentativelyCommuting(false), Declined(false) {} 404adf28177SDan Gohman 405adf28177SDan Gohman /// Stackification for an operand was not successful due to ordering 406adf28177SDan Gohman /// constraints. If possible, and if we haven't already tried it and declined 407adf28177SDan Gohman /// it, commute Insert's operands and prepare to revisit it. 408adf28177SDan Gohman void MaybeCommute(MachineInstr *Insert, TreeWalkerState &TreeWalker, 409adf28177SDan Gohman const WebAssemblyInstrInfo *TII) { 410adf28177SDan Gohman if (TentativelyCommuting) { 411adf28177SDan Gohman assert(!Declined && 412adf28177SDan Gohman "Don't decline commuting until you've finished trying it"); 413adf28177SDan Gohman // Commuting didn't help. Revert it. 414adf28177SDan Gohman TII->commuteInstruction(Insert, /*NewMI=*/false, Operand0, Operand1); 415adf28177SDan Gohman TentativelyCommuting = false; 416adf28177SDan Gohman Declined = true; 417adf28177SDan Gohman } else if (!Declined && TreeWalker.HasRemainingOperands(Insert)) { 418adf28177SDan Gohman Operand0 = TargetInstrInfo::CommuteAnyOperandIndex; 419adf28177SDan Gohman Operand1 = TargetInstrInfo::CommuteAnyOperandIndex; 420adf28177SDan Gohman if (TII->findCommutedOpIndices(Insert, Operand0, Operand1)) { 421adf28177SDan Gohman // Tentatively commute the operands and try again. 422adf28177SDan Gohman TII->commuteInstruction(Insert, /*NewMI=*/false, Operand0, Operand1); 423adf28177SDan Gohman TreeWalker.ResetTopOperands(Insert); 424adf28177SDan Gohman TentativelyCommuting = true; 425adf28177SDan Gohman Declined = false; 426adf28177SDan Gohman } 427adf28177SDan Gohman } 428adf28177SDan Gohman } 429adf28177SDan Gohman 430adf28177SDan Gohman /// Stackification for some operand was successful. Reset to the default 431adf28177SDan Gohman /// state. 432adf28177SDan Gohman void Reset() { 433adf28177SDan Gohman TentativelyCommuting = false; 434adf28177SDan Gohman Declined = false; 435adf28177SDan Gohman } 436adf28177SDan Gohman }; 437adf28177SDan Gohman } // end anonymous namespace 438adf28177SDan Gohman 4391462faadSDan Gohman bool WebAssemblyRegStackify::runOnMachineFunction(MachineFunction &MF) { 4401462faadSDan Gohman DEBUG(dbgs() << "********** Register Stackifying **********\n" 4411462faadSDan Gohman "********** Function: " 4421462faadSDan Gohman << MF.getName() << '\n'); 4431462faadSDan Gohman 4441462faadSDan Gohman bool Changed = false; 4451462faadSDan Gohman MachineRegisterInfo &MRI = MF.getRegInfo(); 4461462faadSDan Gohman WebAssemblyFunctionInfo &MFI = *MF.getInfo<WebAssemblyFunctionInfo>(); 447b6fd39a3SDan Gohman const auto *TII = MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 448b6fd39a3SDan Gohman const auto *TRI = MF.getSubtarget<WebAssemblySubtarget>().getRegisterInfo(); 44981719f85SDan Gohman AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults(); 450adf28177SDan Gohman MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>(); 4518887d1faSDan Gohman LiveIntervals &LIS = getAnalysis<LiveIntervals>(); 452d70e5907SDan Gohman 4531462faadSDan Gohman // Walk the instructions from the bottom up. Currently we don't look past 4541462faadSDan Gohman // block boundaries, and the blocks aren't ordered so the block visitation 4551462faadSDan Gohman // order isn't significant, but we may want to change this in the future. 4561462faadSDan Gohman for (MachineBasicBlock &MBB : MF) { 4578f59cf75SDan Gohman // Don't use a range-based for loop, because we modify the list as we're 4588f59cf75SDan Gohman // iterating over it and the end iterator may change. 4598f59cf75SDan Gohman for (auto MII = MBB.rbegin(); MII != MBB.rend(); ++MII) { 4608f59cf75SDan Gohman MachineInstr *Insert = &*MII; 4611462faadSDan Gohman // Don't nest anything inside a phi. 4621462faadSDan Gohman if (Insert->getOpcode() == TargetOpcode::PHI) 4631462faadSDan Gohman break; 4641462faadSDan Gohman 46581719f85SDan Gohman // Don't nest anything inside an inline asm, because we don't have 46681719f85SDan Gohman // constraints for $push inputs. 46781719f85SDan Gohman if (Insert->getOpcode() == TargetOpcode::INLINEASM) 468595e8ab2SDan Gohman continue; 469595e8ab2SDan Gohman 470595e8ab2SDan Gohman // Ignore debugging intrinsics. 471595e8ab2SDan Gohman if (Insert->getOpcode() == TargetOpcode::DBG_VALUE) 472595e8ab2SDan Gohman continue; 47381719f85SDan Gohman 4741462faadSDan Gohman // Iterate through the inputs in reverse order, since we'll be pulling 47553d13997SDan Gohman // operands off the stack in LIFO order. 476adf28177SDan Gohman CommutingState Commuting; 477adf28177SDan Gohman TreeWalkerState TreeWalker(Insert); 478adf28177SDan Gohman while (!TreeWalker.Done()) { 479adf28177SDan Gohman MachineOperand &Op = TreeWalker.Pop(); 480adf28177SDan Gohman 4811462faadSDan Gohman // We're only interested in explicit virtual register operands. 482adf28177SDan Gohman if (!Op.isReg()) 4831462faadSDan Gohman continue; 4841462faadSDan Gohman 4851462faadSDan Gohman unsigned Reg = Op.getReg(); 486adf28177SDan Gohman assert(Op.isUse() && "explicit_uses() should only iterate over uses"); 487adf28177SDan Gohman assert(!Op.isImplicit() && 488adf28177SDan Gohman "explicit_uses() should only iterate over explicit operands"); 489adf28177SDan Gohman if (TargetRegisterInfo::isPhysicalRegister(Reg)) 490adf28177SDan Gohman continue; 4911462faadSDan Gohman 492adf28177SDan Gohman // Identify the definition for this register at this point. Most 493adf28177SDan Gohman // registers are in SSA form here so we try a quick MRI query first. 4948887d1faSDan Gohman MachineInstr *Def = MRI.getUniqueVRegDef(Reg); 495adf28177SDan Gohman if (!Def) { 496adf28177SDan Gohman // MRI doesn't know what the Def is. Try asking LIS. 497adf28177SDan Gohman const VNInfo *ValNo = LIS.getInterval(Reg).getVNInfoBefore( 49813d3b9b7SJF Bastien LIS.getInstructionIndex(*Insert)); 499adf28177SDan Gohman if (!ValNo) 500adf28177SDan Gohman continue; 501adf28177SDan Gohman Def = LIS.getInstructionFromIndex(ValNo->def); 5021462faadSDan Gohman if (!Def) 5031462faadSDan Gohman continue; 504adf28177SDan Gohman } 5051462faadSDan Gohman 50681719f85SDan Gohman // Don't nest an INLINE_ASM def into anything, because we don't have 50781719f85SDan Gohman // constraints for $pop outputs. 50881719f85SDan Gohman if (Def->getOpcode() == TargetOpcode::INLINEASM) 50981719f85SDan Gohman continue; 51081719f85SDan Gohman 51181719f85SDan Gohman // Don't nest PHIs inside of anything. 51281719f85SDan Gohman if (Def->getOpcode() == TargetOpcode::PHI) 51381719f85SDan Gohman continue; 51481719f85SDan Gohman 5154ba4816bSDan Gohman // Argument instructions represent live-in registers and not real 5164ba4816bSDan Gohman // instructions. 5174ba4816bSDan Gohman if (Def->getOpcode() == WebAssembly::ARGUMENT_I32 || 5184ba4816bSDan Gohman Def->getOpcode() == WebAssembly::ARGUMENT_I64 || 5194ba4816bSDan Gohman Def->getOpcode() == WebAssembly::ARGUMENT_F32 || 5204ba4816bSDan Gohman Def->getOpcode() == WebAssembly::ARGUMENT_F64) 5214ba4816bSDan Gohman continue; 5224ba4816bSDan Gohman 523adf28177SDan Gohman // Decide which strategy to take. Prefer to move a single-use value 524adf28177SDan Gohman // over cloning it, and prefer cloning over introducing a tee_local. 525adf28177SDan Gohman // For moving, we require the def to be in the same block as the use; 526adf28177SDan Gohman // this makes things simpler (LiveIntervals' handleMove function only 527adf28177SDan Gohman // supports intra-block moves) and it's MachineSink's job to catch all 528adf28177SDan Gohman // the sinking opportunities anyway. 529adf28177SDan Gohman bool SameBlock = Def->getParent() == &MBB; 530fbfe5ec4SDan Gohman bool CanMove = SameBlock && IsSafeToMove(Def, Insert, AA, LIS, MRI) && 531fbfe5ec4SDan Gohman !TreeWalker.IsOnStack(Reg); 532adf28177SDan Gohman if (CanMove && MRI.hasOneUse(Reg)) { 5330cfb5f85SDan Gohman Insert = MoveForSingleUse(Reg, Op, Def, MBB, Insert, LIS, MFI, MRI); 534b6fd39a3SDan Gohman } else if (Def->isAsCheapAsAMove() && 535b6fd39a3SDan Gohman TII->isTriviallyReMaterializable(Def, &AA)) { 536adf28177SDan Gohman Insert = RematerializeCheapDef(Reg, Op, Def, MBB, Insert, LIS, MFI, 537adf28177SDan Gohman MRI, TII, TRI); 538adf28177SDan Gohman } else if (CanMove && 5390cfb5f85SDan Gohman OneUseDominatesOtherUses(Reg, Op, MBB, MRI, MDT, LIS)) { 540adf28177SDan Gohman Insert = MoveAndTeeForMultiUse(Reg, Op, Def, MBB, Insert, LIS, MFI, 541adf28177SDan Gohman MRI, TII); 542b6fd39a3SDan Gohman } else { 543adf28177SDan Gohman // We failed to stackify the operand. If the problem was ordering 544adf28177SDan Gohman // constraints, Commuting may be able to help. 545adf28177SDan Gohman if (!CanMove && SameBlock) 546adf28177SDan Gohman Commuting.MaybeCommute(Insert, TreeWalker, TII); 547adf28177SDan Gohman // Proceed to the next operand. 548adf28177SDan Gohman continue; 549b6fd39a3SDan Gohman } 550adf28177SDan Gohman 551adf28177SDan Gohman // We stackified an operand. Add the defining instruction's operands to 552adf28177SDan Gohman // the worklist stack now to continue to build an ever deeper tree. 553adf28177SDan Gohman Commuting.Reset(); 554adf28177SDan Gohman TreeWalker.PushOperands(Insert); 555b6fd39a3SDan Gohman } 556adf28177SDan Gohman 557adf28177SDan Gohman // If we stackified any operands, skip over the tree to start looking for 558adf28177SDan Gohman // the next instruction we can build a tree on. 559adf28177SDan Gohman if (Insert != &*MII) { 5608f59cf75SDan Gohman ImposeStackOrdering(&*MII); 561adf28177SDan Gohman MII = std::prev( 562369ebfe4SHans Wennborg llvm::make_reverse_iterator(MachineBasicBlock::iterator(Insert))); 563adf28177SDan Gohman Changed = true; 564adf28177SDan Gohman } 5651462faadSDan Gohman } 5661462faadSDan Gohman } 5671462faadSDan Gohman 568adf28177SDan Gohman // If we used EXPR_STACK anywhere, add it to the live-in sets everywhere so 569adf28177SDan Gohman // that it never looks like a use-before-def. 570b0992dafSDan Gohman if (Changed) { 571b0992dafSDan Gohman MF.getRegInfo().addLiveIn(WebAssembly::EXPR_STACK); 572b0992dafSDan Gohman for (MachineBasicBlock &MBB : MF) 573b0992dafSDan Gohman MBB.addLiveIn(WebAssembly::EXPR_STACK); 574b0992dafSDan Gohman } 575b0992dafSDan Gohman 5767bafa0eaSDan Gohman #ifndef NDEBUG 577b6fd39a3SDan Gohman // Verify that pushes and pops are performed in LIFO order. 5787bafa0eaSDan Gohman SmallVector<unsigned, 0> Stack; 5797bafa0eaSDan Gohman for (MachineBasicBlock &MBB : MF) { 5807bafa0eaSDan Gohman for (MachineInstr &MI : MBB) { 5810cfb5f85SDan Gohman if (MI.isDebugValue()) 5820cfb5f85SDan Gohman continue; 5837bafa0eaSDan Gohman for (MachineOperand &MO : reverse(MI.explicit_operands())) { 5847a6b9825SDan Gohman if (!MO.isReg()) 5857a6b9825SDan Gohman continue; 586adf28177SDan Gohman unsigned Reg = MO.getReg(); 5877bafa0eaSDan Gohman 588adf28177SDan Gohman if (MFI.isVRegStackified(Reg)) { 5897bafa0eaSDan Gohman if (MO.isDef()) 590adf28177SDan Gohman Stack.push_back(Reg); 5917bafa0eaSDan Gohman else 592adf28177SDan Gohman assert(Stack.pop_back_val() == Reg && 593adf28177SDan Gohman "Register stack pop should be paired with a push"); 5947bafa0eaSDan Gohman } 5957bafa0eaSDan Gohman } 5967bafa0eaSDan Gohman } 5977bafa0eaSDan Gohman // TODO: Generalize this code to support keeping values on the stack across 5987bafa0eaSDan Gohman // basic block boundaries. 599adf28177SDan Gohman assert(Stack.empty() && 600adf28177SDan Gohman "Register stack pushes and pops should be balanced"); 6017bafa0eaSDan Gohman } 6027bafa0eaSDan Gohman #endif 6037bafa0eaSDan Gohman 6041462faadSDan Gohman return Changed; 6051462faadSDan Gohman } 606