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