xref: /freebsd/contrib/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyFixBrTableDefaults.cpp (revision b3512b30dbec579da28028e29d8b33ec7242af68)
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 // `MI` is a br_table instruction with a dummy default target argument. This
45 // function finds and adds the default target argument and removes any redundant
46 // range check preceding the br_table. Returns the MBB that the br_table is
47 // moved into so it can be removed from further consideration, or nullptr if the
48 // br_table cannot be optimized.
49 MachineBasicBlock *fixBrTable(MachineInstr &MI, MachineBasicBlock *MBB,
50                               MachineFunction &MF) {
51   // Get the header block, which contains the redundant range check.
52   assert(MBB->pred_size() == 1 && "Expected a single guard predecessor");
53   auto *HeaderMBB = *MBB->pred_begin();
54 
55   // Find the conditional jump to the default target. If it doesn't exist, the
56   // default target is unreachable anyway, so we can keep the existing dummy
57   // target.
58   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
59   SmallVector<MachineOperand, 2> Cond;
60   const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
61   bool Analyzed = !TII.analyzeBranch(*HeaderMBB, TBB, FBB, Cond);
62   assert(Analyzed && "Could not analyze jump header branches");
63   (void)Analyzed;
64 
65   // Here are the possible outcomes. '_' is nullptr, `J` is the jump table block
66   // aka MBB, 'D' is the default block.
67   //
68   // TBB | FBB | Meaning
69   //  _  |  _  | No default block, header falls through to jump table
70   //  J  |  _  | No default block, header jumps to the jump table
71   //  D  |  _  | Header jumps to the default and falls through to the jump table
72   //  D  |  J  | Header jumps to the default and also to the jump table
73   if (TBB && TBB != MBB) {
74     assert((FBB == nullptr || FBB == MBB) &&
75            "Expected jump or fallthrough to br_table block");
76     assert(Cond.size() == 2 && Cond[1].isReg() && "Unexpected condition info");
77 
78     // If the range check checks an i64 value, we cannot optimize it out because
79     // the i64 index is truncated to an i32, making values over 2^32
80     // indistinguishable from small numbers. There are also other strange edge
81     // cases that can arise in practice that we don't want to reason about, so
82     // conservatively only perform the optimization if the range check is the
83     // normal case of an i32.gt_u.
84     MachineRegisterInfo &MRI = MF.getRegInfo();
85     auto *RangeCheck = MRI.getVRegDef(Cond[1].getReg());
86     assert(RangeCheck != nullptr);
87     if (RangeCheck->getOpcode() != WebAssembly::GT_U_I32)
88       return nullptr;
89 
90     // Remove the dummy default target and install the real one.
91     MI.RemoveOperand(MI.getNumExplicitOperands() - 1);
92     MI.addOperand(MF, MachineOperand::CreateMBB(TBB));
93   }
94 
95   // Remove any branches from the header and splice in the jump table instead
96   TII.removeBranch(*HeaderMBB, nullptr);
97   HeaderMBB->splice(HeaderMBB->end(), MBB, MBB->begin(), MBB->end());
98 
99   // Update CFG to skip the old jump table block. Remove shared successors
100   // before transferring to avoid duplicated successors.
101   HeaderMBB->removeSuccessor(MBB);
102   for (auto &Succ : MBB->successors())
103     if (HeaderMBB->isSuccessor(Succ))
104       HeaderMBB->removeSuccessor(Succ);
105   HeaderMBB->transferSuccessorsAndUpdatePHIs(MBB);
106 
107   // Remove the old jump table block from the function
108   MF.erase(MBB);
109 
110   return HeaderMBB;
111 }
112 
113 bool WebAssemblyFixBrTableDefaults::runOnMachineFunction(MachineFunction &MF) {
114   LLVM_DEBUG(dbgs() << "********** Fixing br_table Default Targets **********\n"
115                        "********** Function: "
116                     << MF.getName() << '\n');
117 
118   bool Changed = false;
119   SmallPtrSet<MachineBasicBlock *, 16> MBBSet;
120   for (auto &MBB : MF)
121     MBBSet.insert(&MBB);
122 
123   while (!MBBSet.empty()) {
124     MachineBasicBlock *MBB = *MBBSet.begin();
125     MBBSet.erase(MBB);
126     for (auto &MI : *MBB) {
127       if (WebAssembly::isBrTable(MI)) {
128         auto *Fixed = fixBrTable(MI, MBB, MF);
129         if (Fixed != nullptr) {
130           MBBSet.erase(Fixed);
131           Changed = true;
132         }
133         break;
134       }
135     }
136   }
137 
138   if (Changed) {
139     // We rewrote part of the function; recompute relevant things.
140     MF.RenumberBlocks();
141     return true;
142   }
143 
144   return false;
145 }
146 
147 } // end anonymous namespace
148 
149 INITIALIZE_PASS(WebAssemblyFixBrTableDefaults, DEBUG_TYPE,
150                 "Removes range checks and sets br_table default targets", false,
151                 false)
152 
153 FunctionPass *llvm::createWebAssemblyFixBrTableDefaults() {
154   return new WebAssemblyFixBrTableDefaults();
155 }
156