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