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