15ffd83dbSDimitry Andric //=- WebAssemblyFixBrTableDefaults.cpp - Fix br_table default branch targets -//
25ffd83dbSDimitry Andric //
35ffd83dbSDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
45ffd83dbSDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
55ffd83dbSDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
65ffd83dbSDimitry Andric //
75ffd83dbSDimitry Andric //===----------------------------------------------------------------------===//
85ffd83dbSDimitry Andric ///
95ffd83dbSDimitry Andric /// \file This file implements a pass that eliminates redundant range checks
105ffd83dbSDimitry Andric /// guarding br_table instructions. Since jump tables on most targets cannot
115ffd83dbSDimitry Andric /// handle out of range indices, LLVM emits these checks before most jump
125ffd83dbSDimitry Andric /// tables. But br_table takes a default branch target as an argument, so it
135ffd83dbSDimitry Andric /// does not need the range checks.
145ffd83dbSDimitry Andric ///
155ffd83dbSDimitry Andric //===----------------------------------------------------------------------===//
165ffd83dbSDimitry Andric
175ffd83dbSDimitry Andric #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
185ffd83dbSDimitry Andric #include "WebAssembly.h"
195f757f3fSDimitry Andric #include "WebAssemblySubtarget.h"
205ffd83dbSDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
215ffd83dbSDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
225ffd83dbSDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
235ffd83dbSDimitry Andric #include "llvm/Pass.h"
245ffd83dbSDimitry Andric
255ffd83dbSDimitry Andric using namespace llvm;
265ffd83dbSDimitry Andric
275ffd83dbSDimitry Andric #define DEBUG_TYPE "wasm-fix-br-table-defaults"
285ffd83dbSDimitry Andric
295ffd83dbSDimitry Andric namespace {
305ffd83dbSDimitry Andric
315ffd83dbSDimitry Andric class WebAssemblyFixBrTableDefaults final : public MachineFunctionPass {
getPassName() const325ffd83dbSDimitry Andric StringRef getPassName() const override {
335ffd83dbSDimitry Andric return "WebAssembly Fix br_table Defaults";
345ffd83dbSDimitry Andric }
355ffd83dbSDimitry Andric
365ffd83dbSDimitry Andric bool runOnMachineFunction(MachineFunction &MF) override;
375ffd83dbSDimitry Andric
385ffd83dbSDimitry Andric public:
395ffd83dbSDimitry Andric static char ID; // Pass identification, replacement for typeid
WebAssemblyFixBrTableDefaults()405ffd83dbSDimitry Andric WebAssemblyFixBrTableDefaults() : MachineFunctionPass(ID) {}
415ffd83dbSDimitry Andric };
425ffd83dbSDimitry Andric
435ffd83dbSDimitry Andric char WebAssemblyFixBrTableDefaults::ID = 0;
445ffd83dbSDimitry Andric
45e8d8bef9SDimitry Andric // Target indepedent selection dag assumes that it is ok to use PointerTy
46e8d8bef9SDimitry Andric // as the index for a "switch", whereas Wasm so far only has a 32-bit br_table.
47e8d8bef9SDimitry Andric // See e.g. SelectionDAGBuilder::visitJumpTableHeader
48e8d8bef9SDimitry Andric // We have a 64-bit br_table in the tablegen defs as a result, which does get
49e8d8bef9SDimitry Andric // selected, and thus we get incorrect truncates/extensions happening on
50e8d8bef9SDimitry Andric // wasm64. Here we fix that.
fixBrTableIndex(MachineInstr & MI,MachineBasicBlock * MBB,MachineFunction & MF)51e8d8bef9SDimitry Andric void fixBrTableIndex(MachineInstr &MI, MachineBasicBlock *MBB,
52e8d8bef9SDimitry Andric MachineFunction &MF) {
53e8d8bef9SDimitry Andric // Only happens on wasm64.
54e8d8bef9SDimitry Andric auto &WST = MF.getSubtarget<WebAssemblySubtarget>();
55e8d8bef9SDimitry Andric if (!WST.hasAddr64())
56e8d8bef9SDimitry Andric return;
57e8d8bef9SDimitry Andric
58e8d8bef9SDimitry Andric assert(MI.getDesc().getOpcode() == WebAssembly::BR_TABLE_I64 &&
59e8d8bef9SDimitry Andric "64-bit br_table pseudo instruction expected");
60e8d8bef9SDimitry Andric
61e8d8bef9SDimitry Andric // Find extension op, if any. It sits in the previous BB before the branch.
62e8d8bef9SDimitry Andric auto ExtMI = MF.getRegInfo().getVRegDef(MI.getOperand(0).getReg());
63e8d8bef9SDimitry Andric if (ExtMI->getOpcode() == WebAssembly::I64_EXTEND_U_I32) {
64e8d8bef9SDimitry Andric // Unnecessarily extending a 32-bit value to 64, remove it.
65349cc55cSDimitry Andric auto ExtDefReg = ExtMI->getOperand(0).getReg();
66349cc55cSDimitry Andric assert(MI.getOperand(0).getReg() == ExtDefReg);
67e8d8bef9SDimitry Andric MI.getOperand(0).setReg(ExtMI->getOperand(1).getReg());
68349cc55cSDimitry Andric if (MF.getRegInfo().use_nodbg_empty(ExtDefReg)) {
69349cc55cSDimitry Andric // No more users of extend, delete it.
70e8d8bef9SDimitry Andric ExtMI->eraseFromParent();
71349cc55cSDimitry Andric }
72e8d8bef9SDimitry Andric } else {
73e8d8bef9SDimitry Andric // Incoming 64-bit value that needs to be truncated.
74e8d8bef9SDimitry Andric Register Reg32 =
75e8d8bef9SDimitry Andric MF.getRegInfo().createVirtualRegister(&WebAssembly::I32RegClass);
76e8d8bef9SDimitry Andric BuildMI(*MBB, MI.getIterator(), MI.getDebugLoc(),
77e8d8bef9SDimitry Andric WST.getInstrInfo()->get(WebAssembly::I32_WRAP_I64), Reg32)
78e8d8bef9SDimitry Andric .addReg(MI.getOperand(0).getReg());
79e8d8bef9SDimitry Andric MI.getOperand(0).setReg(Reg32);
80e8d8bef9SDimitry Andric }
81e8d8bef9SDimitry Andric
82e8d8bef9SDimitry Andric // We now have a 32-bit operand in all cases, so change the instruction
83e8d8bef9SDimitry Andric // accordingly.
84e8d8bef9SDimitry Andric MI.setDesc(WST.getInstrInfo()->get(WebAssembly::BR_TABLE_I32));
85e8d8bef9SDimitry Andric }
86e8d8bef9SDimitry Andric
875ffd83dbSDimitry Andric // `MI` is a br_table instruction with a dummy default target argument. This
885ffd83dbSDimitry Andric // function finds and adds the default target argument and removes any redundant
895ffd83dbSDimitry Andric // range check preceding the br_table. Returns the MBB that the br_table is
905ffd83dbSDimitry Andric // moved into so it can be removed from further consideration, or nullptr if the
915ffd83dbSDimitry Andric // br_table cannot be optimized.
fixBrTableDefault(MachineInstr & MI,MachineBasicBlock * MBB,MachineFunction & MF)92e8d8bef9SDimitry Andric MachineBasicBlock *fixBrTableDefault(MachineInstr &MI, MachineBasicBlock *MBB,
935ffd83dbSDimitry Andric MachineFunction &MF) {
945ffd83dbSDimitry Andric // Get the header block, which contains the redundant range check.
955ffd83dbSDimitry Andric assert(MBB->pred_size() == 1 && "Expected a single guard predecessor");
965ffd83dbSDimitry Andric auto *HeaderMBB = *MBB->pred_begin();
975ffd83dbSDimitry Andric
985ffd83dbSDimitry Andric // Find the conditional jump to the default target. If it doesn't exist, the
995ffd83dbSDimitry Andric // default target is unreachable anyway, so we can keep the existing dummy
1005ffd83dbSDimitry Andric // target.
1015ffd83dbSDimitry Andric MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
1025ffd83dbSDimitry Andric SmallVector<MachineOperand, 2> Cond;
1035ffd83dbSDimitry Andric const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
1045ffd83dbSDimitry Andric bool Analyzed = !TII.analyzeBranch(*HeaderMBB, TBB, FBB, Cond);
1055ffd83dbSDimitry Andric assert(Analyzed && "Could not analyze jump header branches");
1065ffd83dbSDimitry Andric (void)Analyzed;
1075ffd83dbSDimitry Andric
1085ffd83dbSDimitry Andric // Here are the possible outcomes. '_' is nullptr, `J` is the jump table block
1095ffd83dbSDimitry Andric // aka MBB, 'D' is the default block.
1105ffd83dbSDimitry Andric //
1115ffd83dbSDimitry Andric // TBB | FBB | Meaning
1125ffd83dbSDimitry Andric // _ | _ | No default block, header falls through to jump table
1135ffd83dbSDimitry Andric // J | _ | No default block, header jumps to the jump table
1145ffd83dbSDimitry Andric // D | _ | Header jumps to the default and falls through to the jump table
1155ffd83dbSDimitry Andric // D | J | Header jumps to the default and also to the jump table
1165ffd83dbSDimitry Andric if (TBB && TBB != MBB) {
1175ffd83dbSDimitry Andric assert((FBB == nullptr || FBB == MBB) &&
1185ffd83dbSDimitry Andric "Expected jump or fallthrough to br_table block");
1195ffd83dbSDimitry Andric assert(Cond.size() == 2 && Cond[1].isReg() && "Unexpected condition info");
1205ffd83dbSDimitry Andric
1215ffd83dbSDimitry Andric // If the range check checks an i64 value, we cannot optimize it out because
1225ffd83dbSDimitry Andric // the i64 index is truncated to an i32, making values over 2^32
1235ffd83dbSDimitry Andric // indistinguishable from small numbers. There are also other strange edge
1245ffd83dbSDimitry Andric // cases that can arise in practice that we don't want to reason about, so
1255ffd83dbSDimitry Andric // conservatively only perform the optimization if the range check is the
1265ffd83dbSDimitry Andric // normal case of an i32.gt_u.
1275ffd83dbSDimitry Andric MachineRegisterInfo &MRI = MF.getRegInfo();
1285ffd83dbSDimitry Andric auto *RangeCheck = MRI.getVRegDef(Cond[1].getReg());
1295ffd83dbSDimitry Andric assert(RangeCheck != nullptr);
1305ffd83dbSDimitry Andric if (RangeCheck->getOpcode() != WebAssembly::GT_U_I32)
1315ffd83dbSDimitry Andric return nullptr;
1325ffd83dbSDimitry Andric
1335ffd83dbSDimitry Andric // Remove the dummy default target and install the real one.
13481ad6265SDimitry Andric MI.removeOperand(MI.getNumExplicitOperands() - 1);
1355ffd83dbSDimitry Andric MI.addOperand(MF, MachineOperand::CreateMBB(TBB));
1365ffd83dbSDimitry Andric }
1375ffd83dbSDimitry Andric
1385ffd83dbSDimitry Andric // Remove any branches from the header and splice in the jump table instead
1395ffd83dbSDimitry Andric TII.removeBranch(*HeaderMBB, nullptr);
1405ffd83dbSDimitry Andric HeaderMBB->splice(HeaderMBB->end(), MBB, MBB->begin(), MBB->end());
1415ffd83dbSDimitry Andric
1425ffd83dbSDimitry Andric // Update CFG to skip the old jump table block. Remove shared successors
1435ffd83dbSDimitry Andric // before transferring to avoid duplicated successors.
1445ffd83dbSDimitry Andric HeaderMBB->removeSuccessor(MBB);
1455ffd83dbSDimitry Andric for (auto &Succ : MBB->successors())
1465ffd83dbSDimitry Andric if (HeaderMBB->isSuccessor(Succ))
1475ffd83dbSDimitry Andric HeaderMBB->removeSuccessor(Succ);
1485ffd83dbSDimitry Andric HeaderMBB->transferSuccessorsAndUpdatePHIs(MBB);
1495ffd83dbSDimitry Andric
1505ffd83dbSDimitry Andric // Remove the old jump table block from the function
1515ffd83dbSDimitry Andric MF.erase(MBB);
1525ffd83dbSDimitry Andric
1535ffd83dbSDimitry Andric return HeaderMBB;
1545ffd83dbSDimitry Andric }
1555ffd83dbSDimitry Andric
runOnMachineFunction(MachineFunction & MF)1565ffd83dbSDimitry Andric bool WebAssemblyFixBrTableDefaults::runOnMachineFunction(MachineFunction &MF) {
1575ffd83dbSDimitry Andric LLVM_DEBUG(dbgs() << "********** Fixing br_table Default Targets **********\n"
1585ffd83dbSDimitry Andric "********** Function: "
1595ffd83dbSDimitry Andric << MF.getName() << '\n');
1605ffd83dbSDimitry Andric
1615ffd83dbSDimitry Andric bool Changed = false;
162*0fca6ea1SDimitry Andric SetVector<MachineBasicBlock *, SmallVector<MachineBasicBlock *, 16>,
163*0fca6ea1SDimitry Andric DenseSet<MachineBasicBlock *>, 16>
164*0fca6ea1SDimitry Andric MBBSet;
1655ffd83dbSDimitry Andric for (auto &MBB : MF)
1665ffd83dbSDimitry Andric MBBSet.insert(&MBB);
1675ffd83dbSDimitry Andric
1685ffd83dbSDimitry Andric while (!MBBSet.empty()) {
1695ffd83dbSDimitry Andric MachineBasicBlock *MBB = *MBBSet.begin();
170*0fca6ea1SDimitry Andric MBBSet.remove(MBB);
1715ffd83dbSDimitry Andric for (auto &MI : *MBB) {
1725f757f3fSDimitry Andric if (WebAssembly::isBrTable(MI.getOpcode())) {
173e8d8bef9SDimitry Andric fixBrTableIndex(MI, MBB, MF);
174e8d8bef9SDimitry Andric auto *Fixed = fixBrTableDefault(MI, MBB, MF);
1755ffd83dbSDimitry Andric if (Fixed != nullptr) {
176*0fca6ea1SDimitry Andric MBBSet.remove(Fixed);
1775ffd83dbSDimitry Andric Changed = true;
1785ffd83dbSDimitry Andric }
1795ffd83dbSDimitry Andric break;
1805ffd83dbSDimitry Andric }
1815ffd83dbSDimitry Andric }
1825ffd83dbSDimitry Andric }
1835ffd83dbSDimitry Andric
1845ffd83dbSDimitry Andric if (Changed) {
1855ffd83dbSDimitry Andric // We rewrote part of the function; recompute relevant things.
1865ffd83dbSDimitry Andric MF.RenumberBlocks();
1875ffd83dbSDimitry Andric return true;
1885ffd83dbSDimitry Andric }
1895ffd83dbSDimitry Andric
1905ffd83dbSDimitry Andric return false;
1915ffd83dbSDimitry Andric }
1925ffd83dbSDimitry Andric
1935ffd83dbSDimitry Andric } // end anonymous namespace
1945ffd83dbSDimitry Andric
1955ffd83dbSDimitry Andric INITIALIZE_PASS(WebAssemblyFixBrTableDefaults, DEBUG_TYPE,
1965ffd83dbSDimitry Andric "Removes range checks and sets br_table default targets", false,
1975ffd83dbSDimitry Andric false)
1985ffd83dbSDimitry Andric
createWebAssemblyFixBrTableDefaults()1995ffd83dbSDimitry Andric FunctionPass *llvm::createWebAssemblyFixBrTableDefaults() {
2005ffd83dbSDimitry Andric return new WebAssemblyFixBrTableDefaults();
2015ffd83dbSDimitry Andric }
202