Path: blob/main/contrib/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyFixBrTableDefaults.cpp
35266 views
//=- WebAssemblyFixBrTableDefaults.cpp - Fix br_table default branch targets -//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7///8/// \file This file implements a pass that eliminates redundant range checks9/// guarding br_table instructions. Since jump tables on most targets cannot10/// handle out of range indices, LLVM emits these checks before most jump11/// tables. But br_table takes a default branch target as an argument, so it12/// does not need the range checks.13///14//===----------------------------------------------------------------------===//1516#include "MCTargetDesc/WebAssemblyMCTargetDesc.h"17#include "WebAssembly.h"18#include "WebAssemblySubtarget.h"19#include "llvm/CodeGen/MachineFunction.h"20#include "llvm/CodeGen/MachineFunctionPass.h"21#include "llvm/CodeGen/MachineRegisterInfo.h"22#include "llvm/Pass.h"2324using namespace llvm;2526#define DEBUG_TYPE "wasm-fix-br-table-defaults"2728namespace {2930class WebAssemblyFixBrTableDefaults final : public MachineFunctionPass {31StringRef getPassName() const override {32return "WebAssembly Fix br_table Defaults";33}3435bool runOnMachineFunction(MachineFunction &MF) override;3637public:38static char ID; // Pass identification, replacement for typeid39WebAssemblyFixBrTableDefaults() : MachineFunctionPass(ID) {}40};4142char WebAssemblyFixBrTableDefaults::ID = 0;4344// Target indepedent selection dag assumes that it is ok to use PointerTy45// as the index for a "switch", whereas Wasm so far only has a 32-bit br_table.46// See e.g. SelectionDAGBuilder::visitJumpTableHeader47// We have a 64-bit br_table in the tablegen defs as a result, which does get48// selected, and thus we get incorrect truncates/extensions happening on49// wasm64. Here we fix that.50void fixBrTableIndex(MachineInstr &MI, MachineBasicBlock *MBB,51MachineFunction &MF) {52// Only happens on wasm64.53auto &WST = MF.getSubtarget<WebAssemblySubtarget>();54if (!WST.hasAddr64())55return;5657assert(MI.getDesc().getOpcode() == WebAssembly::BR_TABLE_I64 &&58"64-bit br_table pseudo instruction expected");5960// Find extension op, if any. It sits in the previous BB before the branch.61auto ExtMI = MF.getRegInfo().getVRegDef(MI.getOperand(0).getReg());62if (ExtMI->getOpcode() == WebAssembly::I64_EXTEND_U_I32) {63// Unnecessarily extending a 32-bit value to 64, remove it.64auto ExtDefReg = ExtMI->getOperand(0).getReg();65assert(MI.getOperand(0).getReg() == ExtDefReg);66MI.getOperand(0).setReg(ExtMI->getOperand(1).getReg());67if (MF.getRegInfo().use_nodbg_empty(ExtDefReg)) {68// No more users of extend, delete it.69ExtMI->eraseFromParent();70}71} else {72// Incoming 64-bit value that needs to be truncated.73Register Reg32 =74MF.getRegInfo().createVirtualRegister(&WebAssembly::I32RegClass);75BuildMI(*MBB, MI.getIterator(), MI.getDebugLoc(),76WST.getInstrInfo()->get(WebAssembly::I32_WRAP_I64), Reg32)77.addReg(MI.getOperand(0).getReg());78MI.getOperand(0).setReg(Reg32);79}8081// We now have a 32-bit operand in all cases, so change the instruction82// accordingly.83MI.setDesc(WST.getInstrInfo()->get(WebAssembly::BR_TABLE_I32));84}8586// `MI` is a br_table instruction with a dummy default target argument. This87// function finds and adds the default target argument and removes any redundant88// range check preceding the br_table. Returns the MBB that the br_table is89// moved into so it can be removed from further consideration, or nullptr if the90// br_table cannot be optimized.91MachineBasicBlock *fixBrTableDefault(MachineInstr &MI, MachineBasicBlock *MBB,92MachineFunction &MF) {93// Get the header block, which contains the redundant range check.94assert(MBB->pred_size() == 1 && "Expected a single guard predecessor");95auto *HeaderMBB = *MBB->pred_begin();9697// Find the conditional jump to the default target. If it doesn't exist, the98// default target is unreachable anyway, so we can keep the existing dummy99// target.100MachineBasicBlock *TBB = nullptr, *FBB = nullptr;101SmallVector<MachineOperand, 2> Cond;102const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();103bool Analyzed = !TII.analyzeBranch(*HeaderMBB, TBB, FBB, Cond);104assert(Analyzed && "Could not analyze jump header branches");105(void)Analyzed;106107// Here are the possible outcomes. '_' is nullptr, `J` is the jump table block108// aka MBB, 'D' is the default block.109//110// TBB | FBB | Meaning111// _ | _ | No default block, header falls through to jump table112// J | _ | No default block, header jumps to the jump table113// D | _ | Header jumps to the default and falls through to the jump table114// D | J | Header jumps to the default and also to the jump table115if (TBB && TBB != MBB) {116assert((FBB == nullptr || FBB == MBB) &&117"Expected jump or fallthrough to br_table block");118assert(Cond.size() == 2 && Cond[1].isReg() && "Unexpected condition info");119120// If the range check checks an i64 value, we cannot optimize it out because121// the i64 index is truncated to an i32, making values over 2^32122// indistinguishable from small numbers. There are also other strange edge123// cases that can arise in practice that we don't want to reason about, so124// conservatively only perform the optimization if the range check is the125// normal case of an i32.gt_u.126MachineRegisterInfo &MRI = MF.getRegInfo();127auto *RangeCheck = MRI.getVRegDef(Cond[1].getReg());128assert(RangeCheck != nullptr);129if (RangeCheck->getOpcode() != WebAssembly::GT_U_I32)130return nullptr;131132// Remove the dummy default target and install the real one.133MI.removeOperand(MI.getNumExplicitOperands() - 1);134MI.addOperand(MF, MachineOperand::CreateMBB(TBB));135}136137// Remove any branches from the header and splice in the jump table instead138TII.removeBranch(*HeaderMBB, nullptr);139HeaderMBB->splice(HeaderMBB->end(), MBB, MBB->begin(), MBB->end());140141// Update CFG to skip the old jump table block. Remove shared successors142// before transferring to avoid duplicated successors.143HeaderMBB->removeSuccessor(MBB);144for (auto &Succ : MBB->successors())145if (HeaderMBB->isSuccessor(Succ))146HeaderMBB->removeSuccessor(Succ);147HeaderMBB->transferSuccessorsAndUpdatePHIs(MBB);148149// Remove the old jump table block from the function150MF.erase(MBB);151152return HeaderMBB;153}154155bool WebAssemblyFixBrTableDefaults::runOnMachineFunction(MachineFunction &MF) {156LLVM_DEBUG(dbgs() << "********** Fixing br_table Default Targets **********\n"157"********** Function: "158<< MF.getName() << '\n');159160bool Changed = false;161SetVector<MachineBasicBlock *, SmallVector<MachineBasicBlock *, 16>,162DenseSet<MachineBasicBlock *>, 16>163MBBSet;164for (auto &MBB : MF)165MBBSet.insert(&MBB);166167while (!MBBSet.empty()) {168MachineBasicBlock *MBB = *MBBSet.begin();169MBBSet.remove(MBB);170for (auto &MI : *MBB) {171if (WebAssembly::isBrTable(MI.getOpcode())) {172fixBrTableIndex(MI, MBB, MF);173auto *Fixed = fixBrTableDefault(MI, MBB, MF);174if (Fixed != nullptr) {175MBBSet.remove(Fixed);176Changed = true;177}178break;179}180}181}182183if (Changed) {184// We rewrote part of the function; recompute relevant things.185MF.RenumberBlocks();186return true;187}188189return false;190}191192} // end anonymous namespace193194INITIALIZE_PASS(WebAssemblyFixBrTableDefaults, DEBUG_TYPE,195"Removes range checks and sets br_table default targets", false,196false)197198FunctionPass *llvm::createWebAssemblyFixBrTableDefaults() {199return new WebAssemblyFixBrTableDefaults();200}201202203