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