WebAssemblyFixBrTableDefaults.cpp 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. //=- WebAssemblyFixBrTableDefaults.cpp - Fix br_table default branch targets -//
  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 This file implements a pass that eliminates redundant range checks
  10. /// guarding br_table instructions. Since jump tables on most targets cannot
  11. /// handle out of range indices, LLVM emits these checks before most jump
  12. /// tables. But br_table takes a default branch target as an argument, so it
  13. /// does not need the range checks.
  14. ///
  15. //===----------------------------------------------------------------------===//
  16. #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
  17. #include "WebAssembly.h"
  18. #include "llvm/CodeGen/MachineFunction.h"
  19. #include "llvm/CodeGen/MachineFunctionPass.h"
  20. #include "llvm/CodeGen/MachineRegisterInfo.h"
  21. #include "llvm/Pass.h"
  22. using namespace llvm;
  23. #define DEBUG_TYPE "wasm-fix-br-table-defaults"
  24. namespace {
  25. class WebAssemblyFixBrTableDefaults final : public MachineFunctionPass {
  26. StringRef getPassName() const override {
  27. return "WebAssembly Fix br_table Defaults";
  28. }
  29. bool runOnMachineFunction(MachineFunction &MF) override;
  30. public:
  31. static char ID; // Pass identification, replacement for typeid
  32. WebAssemblyFixBrTableDefaults() : MachineFunctionPass(ID) {}
  33. };
  34. char WebAssemblyFixBrTableDefaults::ID = 0;
  35. // Target indepedent selection dag assumes that it is ok to use PointerTy
  36. // as the index for a "switch", whereas Wasm so far only has a 32-bit br_table.
  37. // See e.g. SelectionDAGBuilder::visitJumpTableHeader
  38. // We have a 64-bit br_table in the tablegen defs as a result, which does get
  39. // selected, and thus we get incorrect truncates/extensions happening on
  40. // wasm64. Here we fix that.
  41. void fixBrTableIndex(MachineInstr &MI, MachineBasicBlock *MBB,
  42. MachineFunction &MF) {
  43. // Only happens on wasm64.
  44. auto &WST = MF.getSubtarget<WebAssemblySubtarget>();
  45. if (!WST.hasAddr64())
  46. return;
  47. assert(MI.getDesc().getOpcode() == WebAssembly::BR_TABLE_I64 &&
  48. "64-bit br_table pseudo instruction expected");
  49. // Find extension op, if any. It sits in the previous BB before the branch.
  50. auto ExtMI = MF.getRegInfo().getVRegDef(MI.getOperand(0).getReg());
  51. if (ExtMI->getOpcode() == WebAssembly::I64_EXTEND_U_I32) {
  52. // Unnecessarily extending a 32-bit value to 64, remove it.
  53. auto ExtDefReg = ExtMI->getOperand(0).getReg();
  54. assert(MI.getOperand(0).getReg() == ExtDefReg);
  55. MI.getOperand(0).setReg(ExtMI->getOperand(1).getReg());
  56. if (MF.getRegInfo().use_nodbg_empty(ExtDefReg)) {
  57. // No more users of extend, delete it.
  58. ExtMI->eraseFromParent();
  59. }
  60. } else {
  61. // Incoming 64-bit value that needs to be truncated.
  62. Register Reg32 =
  63. MF.getRegInfo().createVirtualRegister(&WebAssembly::I32RegClass);
  64. BuildMI(*MBB, MI.getIterator(), MI.getDebugLoc(),
  65. WST.getInstrInfo()->get(WebAssembly::I32_WRAP_I64), Reg32)
  66. .addReg(MI.getOperand(0).getReg());
  67. MI.getOperand(0).setReg(Reg32);
  68. }
  69. // We now have a 32-bit operand in all cases, so change the instruction
  70. // accordingly.
  71. MI.setDesc(WST.getInstrInfo()->get(WebAssembly::BR_TABLE_I32));
  72. }
  73. // `MI` is a br_table instruction with a dummy default target argument. This
  74. // function finds and adds the default target argument and removes any redundant
  75. // range check preceding the br_table. Returns the MBB that the br_table is
  76. // moved into so it can be removed from further consideration, or nullptr if the
  77. // br_table cannot be optimized.
  78. MachineBasicBlock *fixBrTableDefault(MachineInstr &MI, MachineBasicBlock *MBB,
  79. MachineFunction &MF) {
  80. // Get the header block, which contains the redundant range check.
  81. assert(MBB->pred_size() == 1 && "Expected a single guard predecessor");
  82. auto *HeaderMBB = *MBB->pred_begin();
  83. // Find the conditional jump to the default target. If it doesn't exist, the
  84. // default target is unreachable anyway, so we can keep the existing dummy
  85. // target.
  86. MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
  87. SmallVector<MachineOperand, 2> Cond;
  88. const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
  89. bool Analyzed = !TII.analyzeBranch(*HeaderMBB, TBB, FBB, Cond);
  90. assert(Analyzed && "Could not analyze jump header branches");
  91. (void)Analyzed;
  92. // Here are the possible outcomes. '_' is nullptr, `J` is the jump table block
  93. // aka MBB, 'D' is the default block.
  94. //
  95. // TBB | FBB | Meaning
  96. // _ | _ | No default block, header falls through to jump table
  97. // J | _ | No default block, header jumps to the jump table
  98. // D | _ | Header jumps to the default and falls through to the jump table
  99. // D | J | Header jumps to the default and also to the jump table
  100. if (TBB && TBB != MBB) {
  101. assert((FBB == nullptr || FBB == MBB) &&
  102. "Expected jump or fallthrough to br_table block");
  103. assert(Cond.size() == 2 && Cond[1].isReg() && "Unexpected condition info");
  104. // If the range check checks an i64 value, we cannot optimize it out because
  105. // the i64 index is truncated to an i32, making values over 2^32
  106. // indistinguishable from small numbers. There are also other strange edge
  107. // cases that can arise in practice that we don't want to reason about, so
  108. // conservatively only perform the optimization if the range check is the
  109. // normal case of an i32.gt_u.
  110. MachineRegisterInfo &MRI = MF.getRegInfo();
  111. auto *RangeCheck = MRI.getVRegDef(Cond[1].getReg());
  112. assert(RangeCheck != nullptr);
  113. if (RangeCheck->getOpcode() != WebAssembly::GT_U_I32)
  114. return nullptr;
  115. // Remove the dummy default target and install the real one.
  116. MI.removeOperand(MI.getNumExplicitOperands() - 1);
  117. MI.addOperand(MF, MachineOperand::CreateMBB(TBB));
  118. }
  119. // Remove any branches from the header and splice in the jump table instead
  120. TII.removeBranch(*HeaderMBB, nullptr);
  121. HeaderMBB->splice(HeaderMBB->end(), MBB, MBB->begin(), MBB->end());
  122. // Update CFG to skip the old jump table block. Remove shared successors
  123. // before transferring to avoid duplicated successors.
  124. HeaderMBB->removeSuccessor(MBB);
  125. for (auto &Succ : MBB->successors())
  126. if (HeaderMBB->isSuccessor(Succ))
  127. HeaderMBB->removeSuccessor(Succ);
  128. HeaderMBB->transferSuccessorsAndUpdatePHIs(MBB);
  129. // Remove the old jump table block from the function
  130. MF.erase(MBB);
  131. return HeaderMBB;
  132. }
  133. bool WebAssemblyFixBrTableDefaults::runOnMachineFunction(MachineFunction &MF) {
  134. LLVM_DEBUG(dbgs() << "********** Fixing br_table Default Targets **********\n"
  135. "********** Function: "
  136. << MF.getName() << '\n');
  137. bool Changed = false;
  138. SmallPtrSet<MachineBasicBlock *, 16> MBBSet;
  139. for (auto &MBB : MF)
  140. MBBSet.insert(&MBB);
  141. while (!MBBSet.empty()) {
  142. MachineBasicBlock *MBB = *MBBSet.begin();
  143. MBBSet.erase(MBB);
  144. for (auto &MI : *MBB) {
  145. if (WebAssembly::isBrTable(MI)) {
  146. fixBrTableIndex(MI, MBB, MF);
  147. auto *Fixed = fixBrTableDefault(MI, MBB, MF);
  148. if (Fixed != nullptr) {
  149. MBBSet.erase(Fixed);
  150. Changed = true;
  151. }
  152. break;
  153. }
  154. }
  155. }
  156. if (Changed) {
  157. // We rewrote part of the function; recompute relevant things.
  158. MF.RenumberBlocks();
  159. return true;
  160. }
  161. return false;
  162. }
  163. } // end anonymous namespace
  164. INITIALIZE_PASS(WebAssemblyFixBrTableDefaults, DEBUG_TYPE,
  165. "Removes range checks and sets br_table default targets", false,
  166. false)
  167. FunctionPass *llvm::createWebAssemblyFixBrTableDefaults() {
  168. return new WebAssemblyFixBrTableDefaults();
  169. }