LLVM  16.0.0git
WebAssemblyRegStackify.cpp
Go to the documentation of this file.
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_*
24 #include "WebAssembly.h"
27 #include "WebAssemblySubtarget.h"
28 #include "llvm/ADT/SmallPtrSet.h"
36 #include "llvm/CodeGen/Passes.h"
37 #include "llvm/Support/Debug.h"
39 #include <iterator>
40 using namespace llvm;
41 
42 #define DEBUG_TYPE "wasm-reg-stackify"
43 
44 namespace {
45 class WebAssemblyRegStackify final : public MachineFunctionPass {
46  StringRef getPassName() const override {
47  return "WebAssembly Register Stackify";
48  }
49 
50  void getAnalysisUsage(AnalysisUsage &AU) const override {
51  AU.setPreservesCFG();
60  }
61 
62  bool runOnMachineFunction(MachineFunction &MF) override;
63 
64 public:
65  static char ID; // Pass identification, replacement for typeid
66  WebAssemblyRegStackify() : MachineFunctionPass(ID) {}
67 };
68 } // end anonymous namespace
69 
71 INITIALIZE_PASS(WebAssemblyRegStackify, DEBUG_TYPE,
72  "Reorder instructions to use the WebAssembly value stack",
73  false, false)
74 
76  return new WebAssemblyRegStackify();
77 }
78 
79 // Decorate the given instruction with implicit operands that enforce the
80 // expression stack ordering constraints for an instruction which is on
81 // the expression stack.
83  // Write the opaque VALUE_STACK register.
84  if (!MI->definesRegister(WebAssembly::VALUE_STACK))
85  MI->addOperand(MachineOperand::CreateReg(WebAssembly::VALUE_STACK,
86  /*isDef=*/true,
87  /*isImp=*/true));
88 
89  // Also read the opaque VALUE_STACK register.
90  if (!MI->readsRegister(WebAssembly::VALUE_STACK))
91  MI->addOperand(MachineOperand::CreateReg(WebAssembly::VALUE_STACK,
92  /*isDef=*/false,
93  /*isImp=*/true));
94 }
95 
96 // Convert an IMPLICIT_DEF instruction into an instruction which defines
97 // a constant zero value.
100  const TargetInstrInfo *TII,
101  MachineFunction &MF,
102  LiveIntervals &LIS) {
103  assert(MI->getOpcode() == TargetOpcode::IMPLICIT_DEF);
104 
105  const auto *RegClass = MRI.getRegClass(MI->getOperand(0).getReg());
106  if (RegClass == &WebAssembly::I32RegClass) {
107  MI->setDesc(TII->get(WebAssembly::CONST_I32));
108  MI->addOperand(MachineOperand::CreateImm(0));
109  } else if (RegClass == &WebAssembly::I64RegClass) {
110  MI->setDesc(TII->get(WebAssembly::CONST_I64));
111  MI->addOperand(MachineOperand::CreateImm(0));
112  } else if (RegClass == &WebAssembly::F32RegClass) {
113  MI->setDesc(TII->get(WebAssembly::CONST_F32));
114  auto *Val = cast<ConstantFP>(Constant::getNullValue(
116  MI->addOperand(MachineOperand::CreateFPImm(Val));
117  } else if (RegClass == &WebAssembly::F64RegClass) {
118  MI->setDesc(TII->get(WebAssembly::CONST_F64));
119  auto *Val = cast<ConstantFP>(Constant::getNullValue(
121  MI->addOperand(MachineOperand::CreateFPImm(Val));
122  } else if (RegClass == &WebAssembly::V128RegClass) {
123  MI->setDesc(TII->get(WebAssembly::CONST_V128_I64x2));
124  MI->addOperand(MachineOperand::CreateImm(0));
125  MI->addOperand(MachineOperand::CreateImm(0));
126  } else {
127  llvm_unreachable("Unexpected reg class");
128  }
129 }
130 
131 // Determine whether a call to the callee referenced by
132 // MI->getOperand(CalleeOpNo) reads memory, writes memory, and/or has side
133 // effects.
134 static void queryCallee(const MachineInstr &MI, bool &Read, bool &Write,
135  bool &Effects, bool &StackPointer) {
136  // All calls can use the stack pointer.
137  StackPointer = true;
138 
140  if (MO.isGlobal()) {
141  const Constant *GV = MO.getGlobal();
142  if (const auto *GA = dyn_cast<GlobalAlias>(GV))
143  if (!GA->isInterposable())
144  GV = GA->getAliasee();
145 
146  if (const auto *F = dyn_cast<Function>(GV)) {
147  if (!F->doesNotThrow())
148  Effects = true;
149  if (F->doesNotAccessMemory())
150  return;
151  if (F->onlyReadsMemory()) {
152  Read = true;
153  return;
154  }
155  }
156  }
157 
158  // Assume the worst.
159  Write = true;
160  Read = true;
161  Effects = true;
162 }
163 
164 // Determine whether MI reads memory, writes memory, has side effects,
165 // and/or uses the stack pointer value.
166 static void query(const MachineInstr &MI, bool &Read, bool &Write,
167  bool &Effects, bool &StackPointer) {
168  assert(!MI.isTerminator());
169 
170  if (MI.isDebugInstr() || MI.isPosition())
171  return;
172 
173  // Check for loads.
174  if (MI.mayLoad() && !MI.isDereferenceableInvariantLoad())
175  Read = true;
176 
177  // Check for stores.
178  if (MI.mayStore()) {
179  Write = true;
180  } else if (MI.hasOrderedMemoryRef()) {
181  switch (MI.getOpcode()) {
182  case WebAssembly::DIV_S_I32:
183  case WebAssembly::DIV_S_I64:
184  case WebAssembly::REM_S_I32:
185  case WebAssembly::REM_S_I64:
186  case WebAssembly::DIV_U_I32:
187  case WebAssembly::DIV_U_I64:
188  case WebAssembly::REM_U_I32:
189  case WebAssembly::REM_U_I64:
190  case WebAssembly::I32_TRUNC_S_F32:
191  case WebAssembly::I64_TRUNC_S_F32:
192  case WebAssembly::I32_TRUNC_S_F64:
193  case WebAssembly::I64_TRUNC_S_F64:
194  case WebAssembly::I32_TRUNC_U_F32:
195  case WebAssembly::I64_TRUNC_U_F32:
196  case WebAssembly::I32_TRUNC_U_F64:
197  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:
218  case WebAssembly::DIV_S_I64:
219  case WebAssembly::REM_S_I32:
220  case WebAssembly::REM_S_I64:
221  case WebAssembly::DIV_U_I32:
222  case WebAssembly::DIV_U_I64:
223  case WebAssembly::REM_U_I32:
224  case WebAssembly::REM_U_I64:
225  case WebAssembly::I32_TRUNC_S_F32:
226  case WebAssembly::I64_TRUNC_S_F32:
227  case WebAssembly::I32_TRUNC_S_F64:
228  case WebAssembly::I64_TRUNC_S_F64:
229  case WebAssembly::I32_TRUNC_U_F32:
230  case WebAssembly::I64_TRUNC_U_F32:
231  case WebAssembly::I32_TRUNC_U_F64:
232  case WebAssembly::I64_TRUNC_U_F64:
233  // These instructions have hasUnmodeledSideEffects() returning true
234  // because they trap on overflow and invalid so they can't be arbitrarily
235  // moved, however in the specific case of register stackifying, it is safe
236  // to move them because overflow and invalid are Undefined Behavior.
237  break;
238  default:
239  Effects = true;
240  break;
241  }
242  }
243 
244  // Check for writes to __stack_pointer global.
245  if ((MI.getOpcode() == WebAssembly::GLOBAL_SET_I32 ||
246  MI.getOpcode() == WebAssembly::GLOBAL_SET_I64) &&
247  strcmp(MI.getOperand(0).getSymbolName(), "__stack_pointer") == 0)
248  StackPointer = true;
249 
250  // Analyze calls.
251  if (MI.isCall()) {
252  queryCallee(MI, Read, Write, Effects, StackPointer);
253  }
254 }
255 
256 // Test whether Def is safe and profitable to rematerialize.
258  const WebAssemblyInstrInfo *TII) {
259  return Def.isAsCheapAsAMove() && TII->isTriviallyReMaterializable(Def);
260 }
261 
262 // Identify the definition for this register at this point. This is a
263 // generalization of MachineRegisterInfo::getUniqueVRegDef that uses
264 // LiveIntervals to handle complex cases.
265 static MachineInstr *getVRegDef(unsigned Reg, const MachineInstr *Insert,
266  const MachineRegisterInfo &MRI,
267  const LiveIntervals &LIS) {
268  // Most registers are in SSA form here so we try a quick MRI query first.
270  return Def;
271 
272  // MRI doesn't know what the Def is. Try asking LIS.
273  if (const VNInfo *ValNo = LIS.getInterval(Reg).getVNInfoBefore(
275  return LIS.getInstructionFromIndex(ValNo->def);
276 
277  return nullptr;
278 }
279 
280 // Test whether Reg, as defined at Def, has exactly one use. This is a
281 // generalization of MachineRegisterInfo::hasOneUse that uses LiveIntervals
282 // to handle complex cases.
284  MachineDominatorTree &MDT, LiveIntervals &LIS) {
285  // Most registers are in SSA form here so we try a quick MRI query first.
286  if (MRI.hasOneUse(Reg))
287  return true;
288 
289  bool HasOne = false;
290  const LiveInterval &LI = LIS.getInterval(Reg);
291  const VNInfo *DefVNI =
293  assert(DefVNI);
294  for (auto &I : MRI.use_nodbg_operands(Reg)) {
295  const auto &Result = LI.Query(LIS.getInstructionIndex(*I.getParent()));
296  if (Result.valueIn() == DefVNI) {
297  if (!Result.isKill())
298  return false;
299  if (HasOne)
300  return false;
301  HasOne = true;
302  }
303  }
304  return HasOne;
305 }
306 
307 // Test whether it's safe to move Def to just before Insert.
308 // TODO: Compute memory dependencies in a way that doesn't require always
309 // walking the block.
310 // TODO: Compute memory dependencies in a way that uses AliasAnalysis to be
311 // more precise.
312 static bool isSafeToMove(const MachineOperand *Def, const MachineOperand *Use,
313  const MachineInstr *Insert,
314  const WebAssemblyFunctionInfo &MFI,
315  const MachineRegisterInfo &MRI) {
316  const MachineInstr *DefI = Def->getParent();
317  const MachineInstr *UseI = Use->getParent();
318  assert(DefI->getParent() == Insert->getParent());
319  assert(UseI->getParent() == Insert->getParent());
320 
321  // The first def of a multivalue instruction can be stackified by moving,
322  // since the later defs can always be placed into locals if necessary. Later
323  // defs can only be stackified if all previous defs are already stackified
324  // since ExplicitLocals will not know how to place a def in a local if a
325  // subsequent def is stackified. But only one def can be stackified by moving
326  // the instruction, so it must be the first one.
327  //
328  // TODO: This could be loosened to be the first *live* def, but care would
329  // have to be taken to ensure the drops of the initial dead defs can be
330  // placed. This would require checking that no previous defs are used in the
331  // same instruction as subsequent defs.
332  if (Def != DefI->defs().begin())
333  return false;
334 
335  // If any subsequent def is used prior to the current value by the same
336  // instruction in which the current value is used, we cannot
337  // stackify. Stackifying in this case would require that def moving below the
338  // current def in the stack, which cannot be achieved, even with locals.
339  // Also ensure we don't sink the def past any other prior uses.
340  for (const auto &SubsequentDef : drop_begin(DefI->defs())) {
341  auto I = std::next(MachineBasicBlock::const_iterator(DefI));
342  auto E = std::next(MachineBasicBlock::const_iterator(UseI));
343  for (; I != E; ++I) {
344  for (const auto &PriorUse : I->uses()) {
345  if (&PriorUse == Use)
346  break;
347  if (PriorUse.isReg() && SubsequentDef.getReg() == PriorUse.getReg())
348  return false;
349  }
350  }
351  }
352 
353  // If moving is a semantic nop, it is always allowed
354  const MachineBasicBlock *MBB = DefI->getParent();
355  auto NextI = std::next(MachineBasicBlock::const_iterator(DefI));
356  for (auto E = MBB->end(); NextI != E && NextI->isDebugInstr(); ++NextI)
357  ;
358  if (NextI == Insert)
359  return true;
360 
361  // 'catch' and 'catch_all' should be the first instruction of a BB and cannot
362  // move.
363  if (WebAssembly::isCatch(DefI->getOpcode()))
364  return false;
365 
366  // Check for register dependencies.
367  SmallVector<unsigned, 4> MutableRegisters;
368  for (const MachineOperand &MO : DefI->operands()) {
369  if (!MO.isReg() || MO.isUndef())
370  continue;
371  Register Reg = MO.getReg();
372 
373  // If the register is dead here and at Insert, ignore it.
374  if (MO.isDead() && Insert->definesRegister(Reg) &&
375  !Insert->readsRegister(Reg))
376  continue;
377 
379  // Ignore ARGUMENTS; it's just used to keep the ARGUMENT_* instructions
380  // from moving down, and we've already checked for that.
381  if (Reg == WebAssembly::ARGUMENTS)
382  continue;
383  // If the physical register is never modified, ignore it.
384  if (!MRI.isPhysRegModified(Reg))
385  continue;
386  // Otherwise, it's a physical register with unknown liveness.
387  return false;
388  }
389 
390  // If one of the operands isn't in SSA form, it has different values at
391  // different times, and we need to make sure we don't move our use across
392  // a different def.
393  if (!MO.isDef() && !MRI.hasOneDef(Reg))
394  MutableRegisters.push_back(Reg);
395  }
396 
397  bool Read = false, Write = false, Effects = false, StackPointer = false;
398  query(*DefI, Read, Write, Effects, StackPointer);
399 
400  // If the instruction does not access memory and has no side effects, it has
401  // no additional dependencies.
402  bool HasMutableRegisters = !MutableRegisters.empty();
403  if (!Read && !Write && !Effects && !StackPointer && !HasMutableRegisters)
404  return true;
405 
406  // Scan through the intervening instructions between DefI and Insert.
408  for (--I; I != D; --I) {
409  bool InterveningRead = false;
410  bool InterveningWrite = false;
411  bool InterveningEffects = false;
412  bool InterveningStackPointer = false;
413  query(*I, InterveningRead, InterveningWrite, InterveningEffects,
414  InterveningStackPointer);
415  if (Effects && InterveningEffects)
416  return false;
417  if (Read && InterveningWrite)
418  return false;
419  if (Write && (InterveningRead || InterveningWrite))
420  return false;
421  if (StackPointer && InterveningStackPointer)
422  return false;
423 
424  for (unsigned Reg : MutableRegisters)
425  for (const MachineOperand &MO : I->operands())
426  if (MO.isReg() && MO.isDef() && MO.getReg() == Reg)
427  return false;
428  }
429 
430  return true;
431 }
432 
433 /// Test whether OneUse, a use of Reg, dominates all of Reg's other uses.
434 static bool oneUseDominatesOtherUses(unsigned Reg, const MachineOperand &OneUse,
435  const MachineBasicBlock &MBB,
436  const MachineRegisterInfo &MRI,
437  const MachineDominatorTree &MDT,
438  LiveIntervals &LIS,
440  const LiveInterval &LI = LIS.getInterval(Reg);
441 
442  const MachineInstr *OneUseInst = OneUse.getParent();
443  VNInfo *OneUseVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*OneUseInst));
444 
445  for (const MachineOperand &Use : MRI.use_nodbg_operands(Reg)) {
446  if (&Use == &OneUse)
447  continue;
448 
449  const MachineInstr *UseInst = Use.getParent();
450  VNInfo *UseVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*UseInst));
451 
452  if (UseVNI != OneUseVNI)
453  continue;
454 
455  if (UseInst == OneUseInst) {
456  // Another use in the same instruction. We need to ensure that the one
457  // selected use happens "before" it.
458  if (&OneUse > &Use)
459  return false;
460  } else {
461  // Test that the use is dominated by the one selected use.
462  while (!MDT.dominates(OneUseInst, UseInst)) {
463  // Actually, dominating is over-conservative. Test that the use would
464  // happen after the one selected use in the stack evaluation order.
465  //
466  // This is needed as a consequence of using implicit local.gets for
467  // uses and implicit local.sets for defs.
468  if (UseInst->getDesc().getNumDefs() == 0)
469  return false;
470  const MachineOperand &MO = UseInst->getOperand(0);
471  if (!MO.isReg())
472  return false;
473  Register DefReg = MO.getReg();
474  if (!Register::isVirtualRegister(DefReg) ||
475  !MFI.isVRegStackified(DefReg))
476  return false;
477  assert(MRI.hasOneNonDBGUse(DefReg));
478  const MachineOperand &NewUse = *MRI.use_nodbg_begin(DefReg);
479  const MachineInstr *NewUseInst = NewUse.getParent();
480  if (NewUseInst == OneUseInst) {
481  if (&OneUse > &NewUse)
482  return false;
483  break;
484  }
485  UseInst = NewUseInst;
486  }
487  }
488  }
489  return true;
490 }
491 
492 /// Get the appropriate tee opcode for the given register class.
493 static unsigned getTeeOpcode(const TargetRegisterClass *RC) {
494  if (RC == &WebAssembly::I32RegClass)
495  return WebAssembly::TEE_I32;
496  if (RC == &WebAssembly::I64RegClass)
497  return WebAssembly::TEE_I64;
498  if (RC == &WebAssembly::F32RegClass)
499  return WebAssembly::TEE_F32;
500  if (RC == &WebAssembly::F64RegClass)
501  return WebAssembly::TEE_F64;
502  if (RC == &WebAssembly::V128RegClass)
503  return WebAssembly::TEE_V128;
504  if (RC == &WebAssembly::EXTERNREFRegClass)
505  return WebAssembly::TEE_EXTERNREF;
506  if (RC == &WebAssembly::FUNCREFRegClass)
507  return WebAssembly::TEE_FUNCREF;
508  llvm_unreachable("Unexpected register class");
509 }
510 
511 // Shrink LI to its uses, cleaning up LI.
512 static void shrinkToUses(LiveInterval &LI, LiveIntervals &LIS) {
513  if (LIS.shrinkToUses(&LI)) {
515  LIS.splitSeparateComponents(LI, SplitLIs);
516  }
517 }
518 
519 /// A single-use def in the same block with no intervening memory or register
520 /// dependencies; move the def down and nest it with the current instruction.
523  MachineInstr *Insert, LiveIntervals &LIS,
526  LLVM_DEBUG(dbgs() << "Move for single use: "; Def->dump());
527 
529  MBB.splice(Insert, &MBB, Def);
530  DefDIs.move(Insert);
531  LIS.handleMove(*Def);
532 
533  if (MRI.hasOneDef(Reg) && MRI.hasOneUse(Reg)) {
534  // No one else is using this register for anything so we can just stackify
535  // it in place.
536  MFI.stackifyVReg(MRI, Reg);
537  } else {
538  // The register may have unrelated uses or defs; create a new register for
539  // just our one def and use so that we can stackify it.
541  Def->getOperand(0).setReg(NewReg);
542  Op.setReg(NewReg);
543 
544  // Tell LiveIntervals about the new register.
546 
547  // Tell LiveIntervals about the changes to the old register.
548  LiveInterval &LI = LIS.getInterval(Reg);
550  LIS.getInstructionIndex(*Op.getParent()).getRegSlot(),
551  /*RemoveDeadValNo=*/true);
552 
553  MFI.stackifyVReg(MRI, NewReg);
554 
555  DefDIs.updateReg(NewReg);
556 
557  LLVM_DEBUG(dbgs() << " - Replaced register: "; Def->dump());
558  }
559 
561  return Def;
562 }
563 
564 /// A trivially cloneable instruction; clone it and nest the new copy with the
565 /// current instruction.
571  LLVM_DEBUG(dbgs() << "Rematerializing cheap def: "; Def.dump());
572  LLVM_DEBUG(dbgs() << " - for use in "; Op.getParent()->dump());
573 
575 
577  TII->reMaterialize(MBB, Insert, NewReg, 0, Def, *TRI);
578  Op.setReg(NewReg);
579  MachineInstr *Clone = &*std::prev(Insert);
580  LIS.InsertMachineInstrInMaps(*Clone);
582  MFI.stackifyVReg(MRI, NewReg);
583  imposeStackOrdering(Clone);
584 
585  LLVM_DEBUG(dbgs() << " - Cloned to "; Clone->dump());
586 
587  // Shrink the interval.
588  bool IsDead = MRI.use_empty(Reg);
589  if (!IsDead) {
590  LiveInterval &LI = LIS.getInterval(Reg);
591  shrinkToUses(LI, LIS);
593  }
594 
595  // If that was the last use of the original, delete the original.
596  // Move or clone corresponding DBG_VALUEs to the 'Insert' location.
597  if (IsDead) {
598  LLVM_DEBUG(dbgs() << " - Deleting original\n");
600  LIS.removePhysRegDefAt(MCRegister::from(WebAssembly::ARGUMENTS), Idx);
601  LIS.removeInterval(Reg);
603  Def.eraseFromParent();
604 
605  DefDIs.move(&*Insert);
606  DefDIs.updateReg(NewReg);
607  } else {
608  DefDIs.clone(&*Insert, NewReg);
609  }
610 
611  return Clone;
612 }
613 
614 /// A multiple-use def in the same block with no intervening memory or register
615 /// dependencies; move the def down, nest it with the current instruction, and
616 /// insert a tee to satisfy the rest of the uses. As an illustration, rewrite
617 /// this:
618 ///
619 /// Reg = INST ... // Def
620 /// INST ..., Reg, ... // Insert
621 /// INST ..., Reg, ...
622 /// INST ..., Reg, ...
623 ///
624 /// to this:
625 ///
626 /// DefReg = INST ... // Def (to become the new Insert)
627 /// TeeReg, Reg = TEE_... DefReg
628 /// INST ..., TeeReg, ... // Insert
629 /// INST ..., Reg, ...
630 /// INST ..., Reg, ...
631 ///
632 /// with DefReg and TeeReg stackified. This eliminates a local.get from the
633 /// resulting code.
638  LLVM_DEBUG(dbgs() << "Move and tee for multi-use:"; Def->dump());
639 
641 
642  // Move Def into place.
643  MBB.splice(Insert, &MBB, Def);
644  LIS.handleMove(*Def);
645 
646  // Create the Tee and attach the registers.
647  const auto *RegClass = MRI.getRegClass(Reg);
648  Register TeeReg = MRI.createVirtualRegister(RegClass);
649  Register DefReg = MRI.createVirtualRegister(RegClass);
650  MachineOperand &DefMO = Def->getOperand(0);
651  MachineInstr *Tee = BuildMI(MBB, Insert, Insert->getDebugLoc(),
652  TII->get(getTeeOpcode(RegClass)), TeeReg)
654  .addReg(DefReg, getUndefRegState(DefMO.isDead()));
655  Op.setReg(TeeReg);
656  DefMO.setReg(DefReg);
657  SlotIndex TeeIdx = LIS.InsertMachineInstrInMaps(*Tee).getRegSlot();
658  SlotIndex DefIdx = LIS.getInstructionIndex(*Def).getRegSlot();
659 
660  DefDIs.move(Insert);
661 
662  // Tell LiveIntervals we moved the original vreg def from Def to Tee.
663  LiveInterval &LI = LIS.getInterval(Reg);
665  VNInfo *ValNo = LI.getVNInfoAt(DefIdx);
666  I->start = TeeIdx;
667  ValNo->def = TeeIdx;
668  shrinkToUses(LI, LIS);
669 
670  // Finish stackifying the new regs.
673  MFI.stackifyVReg(MRI, DefReg);
674  MFI.stackifyVReg(MRI, TeeReg);
676  imposeStackOrdering(Tee);
677 
678  DefDIs.clone(Tee, DefReg);
679  DefDIs.clone(Insert, TeeReg);
680 
681  LLVM_DEBUG(dbgs() << " - Replaced register: "; Def->dump());
682  LLVM_DEBUG(dbgs() << " - Tee instruction: "; Tee->dump());
683  return Def;
684 }
685 
686 namespace {
687 /// A stack for walking the tree of instructions being built, visiting the
688 /// MachineOperands in DFS order.
689 class TreeWalkerState {
690  using mop_iterator = MachineInstr::mop_iterator;
691  using mop_reverse_iterator = std::reverse_iterator<mop_iterator>;
692  using RangeTy = iterator_range<mop_reverse_iterator>;
693  SmallVector<RangeTy, 4> Worklist;
694 
695 public:
696  explicit TreeWalkerState(MachineInstr *Insert) {
697  const iterator_range<mop_iterator> &Range = Insert->explicit_uses();
698  if (!Range.empty())
699  Worklist.push_back(reverse(Range));
700  }
701 
702  bool done() const { return Worklist.empty(); }
703 
704  MachineOperand &pop() {
705  RangeTy &Range = Worklist.back();
706  MachineOperand &Op = *Range.begin();
707  Range = drop_begin(Range);
708  if (Range.empty())
709  Worklist.pop_back();
710  assert((Worklist.empty() || !Worklist.back().empty()) &&
711  "Empty ranges shouldn't remain in the worklist");
712  return Op;
713  }
714 
715  /// Push Instr's operands onto the stack to be visited.
716  void pushOperands(MachineInstr *Instr) {
718  if (!Range.empty())
719  Worklist.push_back(reverse(Range));
720  }
721 
722  /// Some of Instr's operands are on the top of the stack; remove them and
723  /// re-insert them starting from the beginning (because we've commuted them).
724  void resetTopOperands(MachineInstr *Instr) {
725  assert(hasRemainingOperands(Instr) &&
726  "Reseting operands should only be done when the instruction has "
727  "an operand still on the stack");
728  Worklist.back() = reverse(Instr->explicit_uses());
729  }
730 
731  /// Test whether Instr has operands remaining to be visited at the top of
732  /// the stack.
733  bool hasRemainingOperands(const MachineInstr *Instr) const {
734  if (Worklist.empty())
735  return false;
736  const RangeTy &Range = Worklist.back();
737  return !Range.empty() && Range.begin()->getParent() == Instr;
738  }
739 
740  /// Test whether the given register is present on the stack, indicating an
741  /// operand in the tree that we haven't visited yet. Moving a definition of
742  /// Reg to a point in the tree after that would change its value.
743  ///
744  /// This is needed as a consequence of using implicit local.gets for
745  /// uses and implicit local.sets for defs.
746  bool isOnStack(unsigned Reg) const {
747  for (const RangeTy &Range : Worklist)
748  for (const MachineOperand &MO : Range)
749  if (MO.isReg() && MO.getReg() == Reg)
750  return true;
751  return false;
752  }
753 };
754 
755 /// State to keep track of whether commuting is in flight or whether it's been
756 /// tried for the current instruction and didn't work.
757 class CommutingState {
758  /// There are effectively three states: the initial state where we haven't
759  /// started commuting anything and we don't know anything yet, the tentative
760  /// state where we've commuted the operands of the current instruction and are
761  /// revisiting it, and the declined state where we've reverted the operands
762  /// back to their original order and will no longer commute it further.
763  bool TentativelyCommuting = false;
764  bool Declined = false;
765 
766  /// During the tentative state, these hold the operand indices of the commuted
767  /// operands.
768  unsigned Operand0, Operand1;
769 
770 public:
771  /// Stackification for an operand was not successful due to ordering
772  /// constraints. If possible, and if we haven't already tried it and declined
773  /// it, commute Insert's operands and prepare to revisit it.
774  void maybeCommute(MachineInstr *Insert, TreeWalkerState &TreeWalker,
775  const WebAssemblyInstrInfo *TII) {
776  if (TentativelyCommuting) {
777  assert(!Declined &&
778  "Don't decline commuting until you've finished trying it");
779  // Commuting didn't help. Revert it.
780  TII->commuteInstruction(*Insert, /*NewMI=*/false, Operand0, Operand1);
781  TentativelyCommuting = false;
782  Declined = true;
783  } else if (!Declined && TreeWalker.hasRemainingOperands(Insert)) {
786  if (TII->findCommutedOpIndices(*Insert, Operand0, Operand1)) {
787  // Tentatively commute the operands and try again.
788  TII->commuteInstruction(*Insert, /*NewMI=*/false, Operand0, Operand1);
789  TreeWalker.resetTopOperands(Insert);
790  TentativelyCommuting = true;
791  Declined = false;
792  }
793  }
794  }
795 
796  /// Stackification for some operand was successful. Reset to the default
797  /// state.
798  void reset() {
799  TentativelyCommuting = false;
800  Declined = false;
801  }
802 };
803 } // end anonymous namespace
804 
805 bool WebAssemblyRegStackify::runOnMachineFunction(MachineFunction &MF) {
806  LLVM_DEBUG(dbgs() << "********** Register Stackifying **********\n"
807  "********** Function: "
808  << MF.getName() << '\n');
809 
810  bool Changed = false;
813  const auto *TII = MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
814  const auto *TRI = MF.getSubtarget<WebAssemblySubtarget>().getRegisterInfo();
815  auto &MDT = getAnalysis<MachineDominatorTree>();
816  auto &LIS = getAnalysis<LiveIntervals>();
817 
818  // Walk the instructions from the bottom up. Currently we don't look past
819  // block boundaries, and the blocks aren't ordered so the block visitation
820  // order isn't significant, but we may want to change this in the future.
821  for (MachineBasicBlock &MBB : MF) {
822  // Don't use a range-based for loop, because we modify the list as we're
823  // iterating over it and the end iterator may change.
824  for (auto MII = MBB.rbegin(); MII != MBB.rend(); ++MII) {
825  MachineInstr *Insert = &*MII;
826  // Don't nest anything inside an inline asm, because we don't have
827  // constraints for $push inputs.
828  if (Insert->isInlineAsm())
829  continue;
830 
831  // Ignore debugging intrinsics.
832  if (Insert->isDebugValue())
833  continue;
834 
835  // Iterate through the inputs in reverse order, since we'll be pulling
836  // operands off the stack in LIFO order.
837  CommutingState Commuting;
838  TreeWalkerState TreeWalker(Insert);
839  while (!TreeWalker.done()) {
840  MachineOperand &Use = TreeWalker.pop();
841 
842  // We're only interested in explicit virtual register operands.
843  if (!Use.isReg())
844  continue;
845 
846  Register Reg = Use.getReg();
847  assert(Use.isUse() && "explicit_uses() should only iterate over uses");
848  assert(!Use.isImplicit() &&
849  "explicit_uses() should only iterate over explicit operands");
851  continue;
852 
853  // Identify the definition for this register at this point.
854  MachineInstr *DefI = getVRegDef(Reg, Insert, MRI, LIS);
855  if (!DefI)
856  continue;
857 
858  // Don't nest an INLINE_ASM def into anything, because we don't have
859  // constraints for $pop outputs.
860  if (DefI->isInlineAsm())
861  continue;
862 
863  // Argument instructions represent live-in registers and not real
864  // instructions.
865  if (WebAssembly::isArgument(DefI->getOpcode()))
866  continue;
867 
869  assert(Def != nullptr);
870 
871  // Decide which strategy to take. Prefer to move a single-use value
872  // over cloning it, and prefer cloning over introducing a tee.
873  // For moving, we require the def to be in the same block as the use;
874  // this makes things simpler (LiveIntervals' handleMove function only
875  // supports intra-block moves) and it's MachineSink's job to catch all
876  // the sinking opportunities anyway.
877  bool SameBlock = DefI->getParent() == &MBB;
878  bool CanMove = SameBlock && isSafeToMove(Def, &Use, Insert, MFI, MRI) &&
879  !TreeWalker.isOnStack(Reg);
880  if (CanMove && hasOneUse(Reg, DefI, MRI, MDT, LIS)) {
881  Insert = moveForSingleUse(Reg, Use, DefI, MBB, Insert, LIS, MFI, MRI);
882 
883  // If we are removing the frame base reg completely, remove the debug
884  // info as well.
885  // TODO: Encode this properly as a stackified value.
886  if (MFI.isFrameBaseVirtual() && MFI.getFrameBaseVreg() == Reg)
887  MFI.clearFrameBaseVreg();
888  } else if (shouldRematerialize(*DefI, TII)) {
889  Insert =
890  rematerializeCheapDef(Reg, Use, *DefI, MBB, Insert->getIterator(),
891  LIS, MFI, MRI, TII, TRI);
892  } else if (CanMove && oneUseDominatesOtherUses(Reg, Use, MBB, MRI, MDT,
893  LIS, MFI)) {
894  Insert = moveAndTeeForMultiUse(Reg, Use, DefI, MBB, Insert, LIS, MFI,
895  MRI, TII);
896  } else {
897  // We failed to stackify the operand. If the problem was ordering
898  // constraints, Commuting may be able to help.
899  if (!CanMove && SameBlock)
900  Commuting.maybeCommute(Insert, TreeWalker, TII);
901  // Proceed to the next operand.
902  continue;
903  }
904 
905  // Stackifying a multivalue def may unlock in-place stackification of
906  // subsequent defs. TODO: Handle the case where the consecutive uses are
907  // not all in the same instruction.
908  auto *SubsequentDef = Insert->defs().begin();
909  auto *SubsequentUse = &Use;
910  while (SubsequentDef != Insert->defs().end() &&
911  SubsequentUse != Use.getParent()->uses().end()) {
912  if (!SubsequentDef->isReg() || !SubsequentUse->isReg())
913  break;
914  Register DefReg = SubsequentDef->getReg();
915  Register UseReg = SubsequentUse->getReg();
916  // TODO: This single-use restriction could be relaxed by using tees
917  if (DefReg != UseReg || !MRI.hasOneUse(DefReg))
918  break;
919  MFI.stackifyVReg(MRI, DefReg);
920  ++SubsequentDef;
921  ++SubsequentUse;
922  }
923 
924  // If the instruction we just stackified is an IMPLICIT_DEF, convert it
925  // to a constant 0 so that the def is explicit, and the push/pop
926  // correspondence is maintained.
927  if (Insert->getOpcode() == TargetOpcode::IMPLICIT_DEF)
928  convertImplicitDefToConstZero(Insert, MRI, TII, MF, LIS);
929 
930  // We stackified an operand. Add the defining instruction's operands to
931  // the worklist stack now to continue to build an ever deeper tree.
932  Commuting.reset();
933  TreeWalker.pushOperands(Insert);
934  }
935 
936  // If we stackified any operands, skip over the tree to start looking for
937  // the next instruction we can build a tree on.
938  if (Insert != &*MII) {
939  imposeStackOrdering(&*MII);
940  MII = MachineBasicBlock::iterator(Insert).getReverse();
941  Changed = true;
942  }
943  }
944  }
945 
946  // If we used VALUE_STACK anywhere, add it to the live-in sets everywhere so
947  // that it never looks like a use-before-def.
948  if (Changed) {
949  MF.getRegInfo().addLiveIn(WebAssembly::VALUE_STACK);
950  for (MachineBasicBlock &MBB : MF)
951  MBB.addLiveIn(WebAssembly::VALUE_STACK);
952  }
953 
954 #ifndef NDEBUG
955  // Verify that pushes and pops are performed in LIFO order.
957  for (MachineBasicBlock &MBB : MF) {
958  for (MachineInstr &MI : MBB) {
959  if (MI.isDebugInstr())
960  continue;
961  for (MachineOperand &MO : reverse(MI.explicit_uses())) {
962  if (!MO.isReg())
963  continue;
964  Register Reg = MO.getReg();
965  if (MFI.isVRegStackified(Reg))
966  assert(Stack.pop_back_val() == Reg &&
967  "Register stack pop should be paired with a push");
968  }
969  for (MachineOperand &MO : MI.defs()) {
970  if (!MO.isReg())
971  continue;
972  Register Reg = MO.getReg();
973  if (MFI.isVRegStackified(Reg))
974  Stack.push_back(MO.getReg());
975  }
976  }
977  // TODO: Generalize this code to support keeping values on the stack across
978  // basic block boundaries.
979  assert(Stack.empty() &&
980  "Register stack pushes and pops should be balanced");
981  }
982 #endif
983 
984  return Changed;
985 }
llvm::MCInstrDesc::getNumDefs
unsigned getNumDefs() const
Return the number of MachineOperands that are register definitions.
Definition: MCInstrDesc.h:245
MachineModuleInfoImpls.h
llvm::WebAssembly::isArgument
bool isArgument(unsigned Opc)
Definition: WebAssemblyMCTargetDesc.h:275
IsDead
bool IsDead
Definition: SILowerControlFlow.cpp:168
llvm::WebAssembly::getCalleeOp
const MachineOperand & getCalleeOp(const MachineInstr &MI)
Returns the operand number of a callee, assuming the argument is a call instruction.
Definition: WebAssemblyUtilities.cpp:108
llvm::WebAssemblyDebugValueManager::clone
void clone(MachineInstr *Insert, unsigned NewReg)
Definition: WebAssemblyDebugValueManager.cpp:52
MI
IRTranslator LLVM IR MI
Definition: IRTranslator.cpp:108
llvm
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
llvm::tgtok::Def
@ Def
Definition: TGLexer.h:50
WebAssembly.h
llvm::drop_begin
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition: STLExtras.h:387
llvm::MachineOperand::CreateReg
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
Definition: MachineOperand.h:800
llvm::AArch64PACKey::ID
ID
Definition: AArch64BaseInfo.h:818
llvm::MachineRegisterInfo::createVirtualRegister
Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
Definition: MachineRegisterInfo.cpp:156
Insert
Vector Rotate Left Mask Mask Insert
Definition: README_P9.txt:112
llvm::WebAssembly::isCatch
bool isCatch(unsigned Opc)
Definition: WebAssemblyMCTargetDesc.h:407
llvm::MachineOperand::getGlobal
const GlobalValue * getGlobal() const
Definition: MachineOperand.h:572
llvm::MachineRegisterInfo
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
Definition: MachineRegisterInfo.h:50
llvm::MCRegister::from
static MCRegister from(unsigned Val)
Check the provided unsigned value is a valid MCRegister.
Definition: MCRegister.h:67
imposeStackOrdering
static void imposeStackOrdering(MachineInstr *MI)
Definition: WebAssemblyRegStackify.cpp:82
isSafeToMove
static bool isSafeToMove(const MachineOperand *Def, const MachineOperand *Use, const MachineInstr *Insert, const WebAssemblyFunctionInfo &MFI, const MachineRegisterInfo &MRI)
Definition: WebAssemblyRegStackify.cpp:312
INITIALIZE_PASS
INITIALIZE_PASS(WebAssemblyRegStackify, DEBUG_TYPE, "Reorder instructions to use the WebAssembly value stack", false, false) FunctionPass *llvm
Definition: WebAssemblyRegStackify.cpp:71
llvm::SmallVector< unsigned, 4 >
llvm::LiveIntervals::getInstructionFromIndex
MachineInstr * getInstructionFromIndex(SlotIndex index) const
Returns the instruction associated with the given index.
Definition: LiveIntervals.h:225
llvm::X86Disassembler::Reg
Reg
All possible values of the reg field in the ModR/M byte.
Definition: X86DisassemblerDecoder.h:462
llvm::MachineRegisterInfo::getUniqueVRegDef
MachineInstr * getUniqueVRegDef(Register Reg) const
getUniqueVRegDef - Return the unique machine instr that defines the specified virtual register or nul...
Definition: MachineRegisterInfo.cpp:407
llvm::MachineFunctionPass
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
Definition: MachineFunctionPass.h:30
llvm::RegState::Define
@ Define
Register definition.
Definition: MachineInstrBuilder.h:44
llvm::VNInfo::def
SlotIndex def
The index of the defining instruction.
Definition: LiveInterval.h:61
llvm::MachineInstr::defs
iterator_range< mop_iterator > defs()
Returns a range over all explicit operands that are register definitions.
Definition: MachineInstr.h:678
llvm::Function::getContext
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition: Function.cpp:321
llvm::LiveIntervals::removeInterval
void removeInterval(Register Reg)
Interval removal.
Definition: LiveIntervals.h:143
llvm::MachineInstr::getDesc
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
Definition: MachineInstr.h:513
llvm::dump
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
Definition: SparseBitVector.h:877
llvm::MachineDominatorTree::dominates
bool dominates(const MachineDomTreeNode *A, const MachineDomTreeNode *B) const
Definition: MachineDominators.h:114
llvm::WebAssemblyRegisterInfo
Definition: WebAssemblyRegisterInfo.h:28
TRI
unsigned const TargetRegisterInfo * TRI
Definition: MachineSink.cpp:1628
llvm::LiveIntervals::createAndComputeVirtRegInterval
LiveInterval & createAndComputeVirtRegInterval(Register Reg)
Definition: LiveIntervals.h:136
llvm::MachineFunctionPass::getAnalysisUsage
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
Definition: MachineFunctionPass.cpp:167
LLVM_DEBUG
#define LLVM_DEBUG(X)
Definition: Debug.h:101
F
#define F(x, y, z)
Definition: MD5.cpp:55
llvm::LiveIntervals::getInstructionIndex
SlotIndex getInstructionIndex(const MachineInstr &Instr) const
Returns the base index of the given instruction.
Definition: LiveIntervals.h:220
llvm::MachineRegisterInfo::use_nodbg_begin
use_nodbg_iterator use_nodbg_begin(Register RegNo) const
Definition: MachineRegisterInfo.h:526
llvm::getUndefRegState
unsigned getUndefRegState(bool B)
Definition: MachineInstrBuilder.h:552
MachineRegisterInfo.h
llvm::LiveIntervals::handleMove
void handleMove(MachineInstr &MI, bool UpdateFlags=false)
Call this method to notify LiveIntervals that instruction MI has been moved within a basic block.
Definition: LiveIntervals.cpp:1508
AliasAnalysis.h
llvm::dbgs
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
llvm::MachineFunction::getRegInfo
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Definition: MachineFunction.h:667
llvm::TargetInstrInfo
TargetInstrInfo - Interface to description of machine instruction set.
Definition: TargetInstrInfo.h:98
llvm::MachineRegisterInfo::use_nodbg_operands
iterator_range< use_nodbg_iterator > use_nodbg_operands(Register Reg) const
Definition: MachineRegisterInfo.h:534
llvm::LiveRange::liveAt
bool liveAt(SlotIndex index) const
Definition: LiveInterval.h:401
llvm::MachineBlockFrequencyInfo
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
Definition: MachineBlockFrequencyInfo.h:33
llvm::MachineOperand::CreateImm
static MachineOperand CreateImm(int64_t Val)
Definition: MachineOperand.h:782
E
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
llvm::MachineFunction::getInfo
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
Definition: MachineFunction.h:755
llvm::WebAssemblyFunctionInfo::clearFrameBaseVreg
void clearFrameBaseVreg()
Definition: WebAssemblyMachineFunctionInfo.h:110
shouldRematerialize
static bool shouldRematerialize(const MachineInstr &Def, const WebAssemblyInstrInfo *TII)
Definition: WebAssemblyRegStackify.cpp:257
llvm::Type::getDoubleTy
static Type * getDoubleTy(LLVMContext &C)
Definition: Type.cpp:227
llvm::MachineInstr::getOperand
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:526
llvm::LiveIntervals::InsertMachineInstrInMaps
SlotIndex InsertMachineInstrInMaps(MachineInstr &MI)
Definition: LiveIntervals.h:260
llvm::Register::isPhysicalRegister
static bool isPhysicalRegister(unsigned Reg)
Return true if the specified register number is in the physical register namespace.
Definition: Register.h:65
llvm::TargetRegisterClass
Definition: TargetRegisterInfo.h:46
llvm::AnalysisUsage
Represent the analysis usage information of a pass.
Definition: PassAnalysisSupport.h:47
rematerializeCheapDef
static MachineInstr * rematerializeCheapDef(unsigned Reg, MachineOperand &Op, MachineInstr &Def, MachineBasicBlock &MBB, MachineBasicBlock::instr_iterator Insert, LiveIntervals &LIS, WebAssemblyFunctionInfo &MFI, MachineRegisterInfo &MRI, const WebAssemblyInstrInfo *TII, const WebAssemblyRegisterInfo *TRI)
A trivially cloneable instruction; clone it and nest the new copy with the current instruction.
Definition: WebAssemblyRegStackify.cpp:566
moveAndTeeForMultiUse
static MachineInstr * moveAndTeeForMultiUse(unsigned Reg, MachineOperand &Op, MachineInstr *Def, MachineBasicBlock &MBB, MachineInstr *Insert, LiveIntervals &LIS, WebAssemblyFunctionInfo &MFI, MachineRegisterInfo &MRI, const WebAssemblyInstrInfo *TII)
A multiple-use def in the same block with no intervening memory or register dependencies; move the de...
Definition: WebAssemblyRegStackify.cpp:634
llvm::Value::uses
iterator_range< use_iterator > uses()
Definition: Value.h:376
llvm::createWebAssemblyRegStackify
FunctionPass * createWebAssemblyRegStackify()
TII
const HexagonInstrInfo * TII
Definition: HexagonCopyToCombine.cpp:125
llvm::MachineOperand
MachineOperand class - Representation of each machine instruction operand.
Definition: MachineOperand.h:48
llvm::MachineBasicBlock::rend
reverse_iterator rend()
Definition: MachineBasicBlock.h:315
llvm::SlotIndex::getDeadSlot
SlotIndex getDeadSlot() const
Returns the dead def kill slot for the current instruction.
Definition: SlotIndexes.h:264
llvm::SlotIndexes
SlotIndexes pass.
Definition: SlotIndexes.h:319
SmallPtrSet.h
llvm::LiveInterval
LiveInterval - This class represents the liveness of a register, or stack slot.
Definition: LiveInterval.h:686
llvm::SlotIndex
SlotIndex - An opaque wrapper around machine indexes.
Definition: SlotIndexes.h:82
llvm::MachineOperand::getParent
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
Definition: MachineOperand.h:237
llvm::MachineRegisterInfo::use_empty
bool use_empty(Register RegNo) const
use_empty - Return true if there are no instructions using the specified register.
Definition: MachineRegisterInfo.h:514
llvm::CallingConv::ID
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
llvm::MachineBasicBlock
Definition: MachineBasicBlock.h:94
WebAssemblyUtilities.h
WebAssemblyMCTargetDesc.h
WebAssemblyDebugValueManager.h
llvm::MachineRegisterInfo::getRegClass
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
Definition: MachineRegisterInfo.h:647
Passes.h
llvm::LiveIntervals::removePhysRegDefAt
void removePhysRegDefAt(MCRegister Reg, SlotIndex Pos)
Remove value numbers and related live segments starting at position Pos that are part of any liverang...
Definition: LiveIntervals.cpp:1712
llvm::MachineFunction::getSubtarget
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
Definition: MachineFunction.h:657
llvm::WebAssemblyFunctionInfo::stackifyVReg
void stackifyVReg(MachineRegisterInfo &MRI, unsigned VReg)
Definition: WebAssemblyMachineFunctionInfo.h:122
llvm::Constant
This is an important base class in LLVM.
Definition: Constant.h:41
llvm::LiveRange::getVNInfoBefore
VNInfo * getVNInfoBefore(SlotIndex Idx) const
getVNInfoBefore - Return the VNInfo that is live up to but not necessarilly including Idx,...
Definition: LiveInterval.h:429
llvm::MachineInstrBundleIterator::getReverse
reverse_iterator getReverse() const
Get a reverse iterator to the same node.
Definition: MachineInstrBundleIterator.h:283
llvm::MachineOperand::isReg
bool isReg() const
isReg - Tests if this is a MO_Register operand.
Definition: MachineOperand.h:320
llvm::MachineInstr
Representation of each machine instruction.
Definition: MachineInstr.h:66
LiveIntervals.h
D
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
UseReg
static Register UseReg(const MachineOperand &MO)
Definition: HexagonCopyToCombine.cpp:252
llvm::MachineOperand::isDead
bool isDead() const
Definition: MachineOperand.h:384
I
#define I(x, y, z)
Definition: MD5.cpp:58
convertImplicitDefToConstZero
static void convertImplicitDefToConstZero(MachineInstr *MI, MachineRegisterInfo &MRI, const TargetInstrInfo *TII, MachineFunction &MF, LiveIntervals &LIS)
Definition: WebAssemblyRegStackify.cpp:98
llvm::LiveRange::Query
LiveQueryResult Query(SlotIndex Idx) const
Query Liveness at Idx.
Definition: LiveInterval.h:541
llvm::LiveVariablesID
char & LiveVariablesID
LiveVariables pass - This pass computes the set of blocks in which each variable is life and sets mac...
Definition: LiveVariables.cpp:45
llvm::Register::isVirtualRegister
static bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
Definition: Register.h:71
llvm::pdb::PDB_MemoryType::Stack
@ Stack
llvm::WebAssemblyFunctionInfo::isVRegStackified
bool isVRegStackified(unsigned VReg) const
Definition: WebAssemblyMachineFunctionInfo.h:134
llvm::MachineFunction::getName
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
Definition: MachineFunction.cpp:567
assert
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
llvm::LiveIntervals::shrinkToUses
bool shrinkToUses(LiveInterval *li, SmallVectorImpl< MachineInstr * > *dead=nullptr)
After removing some uses of a register, shrink its live range to just the remaining uses.
Definition: LiveIntervals.cpp:449
llvm::WebAssemblyFunctionInfo
This class is derived from MachineFunctionInfo and contains private WebAssembly-specific information ...
Definition: WebAssemblyMachineFunctionInfo.h:33
llvm::MachineInstrBuilder::addReg
const MachineInstrBuilder & addReg(Register RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
Definition: MachineInstrBuilder.h:97
llvm::MachineOperand::getReg
Register getReg() const
getReg - Returns the register number.
Definition: MachineOperand.h:359
llvm::MachineRegisterInfo::hasOneDef
bool hasOneDef(Register RegNo) const
Return true if there is exactly one operand defining the specified register.
Definition: MachineRegisterInfo.h:452
llvm::WebAssemblyDebugValueManager::move
void move(MachineInstr *Insert)
Definition: WebAssemblyDebugValueManager.cpp:39
moveForSingleUse
static MachineInstr * moveForSingleUse(unsigned Reg, MachineOperand &Op, MachineInstr *Def, MachineBasicBlock &MBB, MachineInstr *Insert, LiveIntervals &LIS, WebAssemblyFunctionInfo &MFI, MachineRegisterInfo &MRI)
A single-use def in the same block with no intervening memory or register dependencies; move the def ...
Definition: WebAssemblyRegStackify.cpp:521
WebAssemblyMachineFunctionInfo.h
llvm::SlotIndex::getRegSlot
SlotIndex getRegSlot(bool EC=false) const
Returns the register use/def slot in the current instruction for a normal or early-clobber def.
Definition: SlotIndexes.h:259
llvm::LiveIntervals::getInterval
LiveInterval & getInterval(Register Reg)
Definition: LiveIntervals.h:112
llvm::MachineFunction
Definition: MachineFunction.h:257
llvm::MachineInstr::dump
void dump() const
Definition: MachineInstr.cpp:1526
llvm::LiveRange::FindSegmentContaining
iterator FindSegmentContaining(SlotIndex Idx)
Return an iterator to the segment that contains the specified index, or end() if there is none.
Definition: LiveInterval.h:436
llvm::WebAssemblyDebugValueManager
Definition: WebAssemblyDebugValueManager.h:24
llvm::MachineBasicBlock::iterator
MachineInstrBundleIterator< MachineInstr > iterator
Definition: MachineBasicBlock.h:269
llvm::logicalview::LVAttributeKind::Range
@ Range
llvm::AnalysisUsage::setPreservesCFG
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:265
llvm::StringRef
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
llvm::MachineBasicBlock::rbegin
reverse_iterator rbegin()
Definition: MachineBasicBlock.h:309
llvm::MachineBasicBlock::splice
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
Definition: MachineBasicBlock.h:1009
llvm::MachineInstr::isInlineAsm
bool isInlineAsm() const
Definition: MachineInstr.h:1306
llvm::AnalysisUsage::addPreservedID
AnalysisUsage & addPreservedID(const void *ID)
Definition: PassAnalysisSupport.h:88
llvm::MachineInstr::getOpcode
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:516
llvm::MachineRegisterInfo::hasOneNonDBGUse
bool hasOneNonDBGUse(Register RegNo) const
hasOneNonDBGUse - Return true if there is exactly one non-Debug use of the specified register.
Definition: MachineRegisterInfo.cpp:415
llvm_unreachable
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Definition: ErrorHandling.h:143
llvm::AnalysisUsage::addPreserved
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
Definition: PassAnalysisSupport.h:98
llvm::WebAssemblySubtarget
Definition: WebAssemblySubtarget.h:35
llvm::MachineInstr::getParent
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:313
queryCallee
static void queryCallee(const MachineInstr &MI, bool &Read, bool &Write, bool &Effects, bool &StackPointer)
Definition: WebAssemblyRegStackify.cpp:134
MRI
unsigned const MachineRegisterInfo * MRI
Definition: AArch64AdvSIMDScalarPass.cpp:105
llvm::Register
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
llvm::MachineInstr::mop_iterator
MachineOperand * mop_iterator
iterator/begin/end - Iterate over all operands of a machine instruction.
Definition: MachineInstr.h:632
llvm::MachineBasicBlock::addLiveIn
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
Definition: MachineBasicBlock.h:404
MBB
MachineBasicBlock & MBB
Definition: AArch64SLSHardening.cpp:74
llvm::WebAssemblyInstrInfo
Definition: WebAssemblyInstrInfo.h:38
llvm::LiveRange::iterator
Segments::iterator iterator
Definition: LiveInterval.h:212
llvm::Constant::getNullValue
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Definition: Constants.cpp:350
llvm::MachineFunction::getFunction
Function & getFunction()
Return the LLVM function that this machine code represents.
Definition: MachineFunction.h:623
llvm::AMDGPU::SendMsg::Op
Op
Definition: SIDefines.h:348
llvm::ilist_iterator
Iterator for intrusive lists based on ilist_node.
Definition: ilist_iterator.h:57
query
static void query(const MachineInstr &MI, bool &Read, bool &Write, bool &Effects, bool &StackPointer)
Definition: WebAssemblyRegStackify.cpp:166
WebAssemblySubtarget.h
llvm::WebAssemblyFunctionInfo::isFrameBaseVirtual
bool isFrameBaseVirtual() const
Definition: WebAssemblyMachineFunctionInfo.h:112
llvm::WebAssemblyDebugValueManager::updateReg
void updateReg(unsigned Reg)
Definition: WebAssemblyDebugValueManager.cpp:45
llvm::LiveIntervals
Definition: LiveIntervals.h:53
llvm::VNInfo
VNInfo - Value Number Information.
Definition: LiveInterval.h:53
llvm::LiveRange::getVNInfoAt
VNInfo * getVNInfoAt(SlotIndex Idx) const
getVNInfoAt - Return the VNInfo that is live at Idx, or NULL.
Definition: LiveInterval.h:421
llvm::MachineRegisterInfo::isPhysRegModified
bool isPhysRegModified(MCRegister PhysReg, bool SkipNoReturnDef=false) const
Return true if the specified register is modified in this function.
Definition: MachineRegisterInfo.cpp:572
llvm::LiveRange::removeSegment
void removeSegment(SlotIndex Start, SlotIndex End, bool RemoveDeadValNo=false)
Remove the specified segment from this range.
Definition: LiveInterval.cpp:568
llvm::MachineInstr::explicit_uses
iterator_range< mop_iterator > explicit_uses()
Definition: MachineInstr.h:696
llvm::BuildMI
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
Definition: MachineInstrBuilder.h:357
llvm::MachineRegisterInfo::hasOneUse
bool hasOneUse(Register RegNo) const
hasOneUse - Return true if there is exactly one instruction using the specified register.
Definition: MachineRegisterInfo.h:518
MachineInstrBuilder.h
llvm::MachineOperand::setReg
void setReg(Register Reg)
Change the register this operand corresponds to.
Definition: MachineOperand.cpp:56
llvm::LiveIntervals::RemoveMachineInstrFromMaps
void RemoveMachineInstrFromMaps(MachineInstr &MI)
Definition: LiveIntervals.h:270
llvm::LiveIntervals::splitSeparateComponents
void splitSeparateComponents(LiveInterval &LI, SmallVectorImpl< LiveInterval * > &SplitLIs)
Split separate components in LiveInterval LI into separate intervals.
Definition: LiveIntervals.cpp:1738
llvm::iterator_range
A range adaptor for a pair of iterators.
Definition: iterator_range.h:30
llvm::reverse
auto reverse(ContainerTy &&C)
Definition: STLExtras.h:485
llvm::FunctionPass
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:308
getTeeOpcode
static unsigned getTeeOpcode(const TargetRegisterClass *RC)
Get the appropriate tee opcode for the given register class.
Definition: WebAssemblyRegStackify.cpp:493
llvm::WebAssemblyFunctionInfo::getFrameBaseVreg
unsigned getFrameBaseVreg() const
Definition: WebAssemblyMachineFunctionInfo.h:106
llvm::AnalysisUsage::addRequired
AnalysisUsage & addRequired()
Definition: PassAnalysisSupport.h:75
DEBUG_TYPE
#define DEBUG_TYPE
Definition: WebAssemblyRegStackify.cpp:42
raw_ostream.h
llvm::TargetInstrInfo::CommuteAnyOperandIndex
static const unsigned CommuteAnyOperandIndex
Definition: TargetInstrInfo.h:441
llvm::MachineDominatorTree
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
Definition: MachineDominators.h:51
oneUseDominatesOtherUses
static bool oneUseDominatesOtherUses(unsigned Reg, const MachineOperand &OneUse, const MachineBasicBlock &MBB, const MachineRegisterInfo &MRI, const MachineDominatorTree &MDT, LiveIntervals &LIS, WebAssemblyFunctionInfo &MFI)
Test whether OneUse, a use of Reg, dominates all of Reg's other uses.
Definition: WebAssemblyRegStackify.cpp:434
llvm::MachineInstr::findRegisterDefOperand
MachineOperand * findRegisterDefOperand(Register Reg, bool isDead=false, bool Overlap=false, const TargetRegisterInfo *TRI=nullptr)
Wrapper for findRegisterDefOperandIdx, it returns a pointer to the MachineOperand rather than an inde...
Definition: MachineInstr.h:1479
llvm::MachineInstrBundleIterator< const MachineInstr >
hasOneUse
static bool hasOneUse(unsigned Reg, MachineInstr *Def, MachineRegisterInfo &MRI, MachineDominatorTree &MDT, LiveIntervals &LIS)
Definition: WebAssemblyRegStackify.cpp:283
llvm::MachineInstr::operands
iterator_range< mop_iterator > operands()
Definition: MachineInstr.h:641
MachineBlockFrequencyInfo.h
Debug.h
getVRegDef
static MachineInstr * getVRegDef(unsigned Reg, const MachineInstr *Insert, const MachineRegisterInfo &MRI, const LiveIntervals &LIS)
Definition: WebAssemblyRegStackify.cpp:265
shrinkToUses
static void shrinkToUses(LiveInterval &LI, LiveIntervals &LIS)
Definition: WebAssemblyRegStackify.cpp:512
llvm::MachineBasicBlock::end
iterator end()
Definition: MachineBasicBlock.h:307
llvm::MachineOperand::CreateFPImm
static MachineOperand CreateFPImm(const ConstantFP *CFP)
Definition: MachineOperand.h:794
llvm::Type::getFloatTy
static Type * getFloatTy(LLVMContext &C)
Definition: Type.cpp:226
llvm::Use
A Use represents the edge between a Value definition and its users.
Definition: Use.h:43
MachineDominators.h
llvm::MachineOperand::isGlobal
bool isGlobal() const
isGlobal - Tests if this is a MO_GlobalAddress operand.
Definition: MachineOperand.h:338