1//===-- WebAssemblyInstrInfo.cpp - WebAssembly Instruction Information ----===//
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
10/// This file contains the WebAssembly implementation of the
11/// TargetInstrInfo class.
12///
13//===----------------------------------------------------------------------===//
14
15#include "WebAssemblyInstrInfo.h"
16#include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
17#include "WebAssembly.h"
18#include "WebAssemblyMachineFunctionInfo.h"
19#include "WebAssemblySubtarget.h"
20#include "llvm/CodeGen/MachineFrameInfo.h"
21#include "llvm/CodeGen/MachineInstrBuilder.h"
22#include "llvm/CodeGen/MachineMemOperand.h"
23#include "llvm/CodeGen/MachineRegisterInfo.h"
24using namespace llvm;
25
26#define DEBUG_TYPE "wasm-instr-info"
27
28#define GET_INSTRINFO_CTOR_DTOR
29#include "WebAssemblyGenInstrInfo.inc"
30
31// defines WebAssembly::getNamedOperandIdx
32#define GET_INSTRINFO_NAMED_OPS
33#include "WebAssemblyGenInstrInfo.inc"
34
35WebAssemblyInstrInfo::WebAssemblyInstrInfo(const WebAssemblySubtarget &STI)
36    : WebAssemblyGenInstrInfo(WebAssembly::ADJCALLSTACKDOWN,
37                              WebAssembly::ADJCALLSTACKUP,
38                              WebAssembly::CATCHRET),
39      RI(STI.getTargetTriple()) {}
40
41bool WebAssemblyInstrInfo::isReallyTriviallyReMaterializable(
42    const MachineInstr &MI, AAResults *AA) const {
43  switch (MI.getOpcode()) {
44  case WebAssembly::CONST_I32:
45  case WebAssembly::CONST_I64:
46  case WebAssembly::CONST_F32:
47  case WebAssembly::CONST_F64:
48    // isReallyTriviallyReMaterializableGeneric misses these because of the
49    // ARGUMENTS implicit def, so we manualy override it here.
50    return true;
51  default:
52    return false;
53  }
54}
55
56void WebAssemblyInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
57                                       MachineBasicBlock::iterator I,
58                                       const DebugLoc &DL, MCRegister DestReg,
59                                       MCRegister SrcReg, bool KillSrc) const {
60  // This method is called by post-RA expansion, which expects only pregs to
61  // exist. However we need to handle both here.
62  auto &MRI = MBB.getParent()->getRegInfo();
63  const TargetRegisterClass *RC =
64      Register::isVirtualRegister(DestReg)
65          ? MRI.getRegClass(DestReg)
66          : MRI.getTargetRegisterInfo()->getMinimalPhysRegClass(DestReg);
67
68  unsigned CopyOpcode;
69  if (RC == &WebAssembly::I32RegClass)
70    CopyOpcode = WebAssembly::COPY_I32;
71  else if (RC == &WebAssembly::I64RegClass)
72    CopyOpcode = WebAssembly::COPY_I64;
73  else if (RC == &WebAssembly::F32RegClass)
74    CopyOpcode = WebAssembly::COPY_F32;
75  else if (RC == &WebAssembly::F64RegClass)
76    CopyOpcode = WebAssembly::COPY_F64;
77  else if (RC == &WebAssembly::V128RegClass)
78    CopyOpcode = WebAssembly::COPY_V128;
79  else if (RC == &WebAssembly::EXNREFRegClass)
80    CopyOpcode = WebAssembly::COPY_EXNREF;
81  else
82    llvm_unreachable("Unexpected register class");
83
84  BuildMI(MBB, I, DL, get(CopyOpcode), DestReg)
85      .addReg(SrcReg, KillSrc ? RegState::Kill : 0);
86}
87
88MachineInstr *WebAssemblyInstrInfo::commuteInstructionImpl(
89    MachineInstr &MI, bool NewMI, unsigned OpIdx1, unsigned OpIdx2) const {
90  // If the operands are stackified, we can't reorder them.
91  WebAssemblyFunctionInfo &MFI =
92      *MI.getParent()->getParent()->getInfo<WebAssemblyFunctionInfo>();
93  if (MFI.isVRegStackified(MI.getOperand(OpIdx1).getReg()) ||
94      MFI.isVRegStackified(MI.getOperand(OpIdx2).getReg()))
95    return nullptr;
96
97  // Otherwise use the default implementation.
98  return TargetInstrInfo::commuteInstructionImpl(MI, NewMI, OpIdx1, OpIdx2);
99}
100
101// Branch analysis.
102bool WebAssemblyInstrInfo::analyzeBranch(MachineBasicBlock &MBB,
103                                         MachineBasicBlock *&TBB,
104                                         MachineBasicBlock *&FBB,
105                                         SmallVectorImpl<MachineOperand> &Cond,
106                                         bool /*AllowModify*/) const {
107  const auto &MFI = *MBB.getParent()->getInfo<WebAssemblyFunctionInfo>();
108  // WebAssembly has control flow that doesn't have explicit branches or direct
109  // fallthrough (e.g. try/catch), which can't be modeled by analyzeBranch. It
110  // is created after CFGStackify.
111  if (MFI.isCFGStackified())
112    return true;
113
114  bool HaveCond = false;
115  for (MachineInstr &MI : MBB.terminators()) {
116    switch (MI.getOpcode()) {
117    default:
118      // Unhandled instruction; bail out.
119      return true;
120    case WebAssembly::BR_IF:
121      if (HaveCond)
122        return true;
123      Cond.push_back(MachineOperand::CreateImm(true));
124      Cond.push_back(MI.getOperand(1));
125      TBB = MI.getOperand(0).getMBB();
126      HaveCond = true;
127      break;
128    case WebAssembly::BR_UNLESS:
129      if (HaveCond)
130        return true;
131      Cond.push_back(MachineOperand::CreateImm(false));
132      Cond.push_back(MI.getOperand(1));
133      TBB = MI.getOperand(0).getMBB();
134      HaveCond = true;
135      break;
136    case WebAssembly::BR:
137      if (!HaveCond)
138        TBB = MI.getOperand(0).getMBB();
139      else
140        FBB = MI.getOperand(0).getMBB();
141      break;
142    case WebAssembly::BR_ON_EXN:
143      if (HaveCond)
144        return true;
145      Cond.push_back(MachineOperand::CreateImm(true));
146      Cond.push_back(MI.getOperand(2));
147      TBB = MI.getOperand(0).getMBB();
148      HaveCond = true;
149      break;
150    }
151    if (MI.isBarrier())
152      break;
153  }
154
155  return false;
156}
157
158unsigned WebAssemblyInstrInfo::removeBranch(MachineBasicBlock &MBB,
159                                            int *BytesRemoved) const {
160  assert(!BytesRemoved && "code size not handled");
161
162  MachineBasicBlock::instr_iterator I = MBB.instr_end();
163  unsigned Count = 0;
164
165  while (I != MBB.instr_begin()) {
166    --I;
167    if (I->isDebugInstr())
168      continue;
169    if (!I->isTerminator())
170      break;
171    // Remove the branch.
172    I->eraseFromParent();
173    I = MBB.instr_end();
174    ++Count;
175  }
176
177  return Count;
178}
179
180unsigned WebAssemblyInstrInfo::insertBranch(
181    MachineBasicBlock &MBB, MachineBasicBlock *TBB, MachineBasicBlock *FBB,
182    ArrayRef<MachineOperand> Cond, const DebugLoc &DL, int *BytesAdded) const {
183  assert(!BytesAdded && "code size not handled");
184
185  if (Cond.empty()) {
186    if (!TBB)
187      return 0;
188
189    BuildMI(&MBB, DL, get(WebAssembly::BR)).addMBB(TBB);
190    return 1;
191  }
192
193  assert(Cond.size() == 2 && "Expected a flag and a successor block");
194
195  MachineFunction &MF = *MBB.getParent();
196  auto &MRI = MF.getRegInfo();
197  bool IsBrOnExn = Cond[1].isReg() && MRI.getRegClass(Cond[1].getReg()) ==
198                                          &WebAssembly::EXNREFRegClass;
199
200  if (Cond[0].getImm()) {
201    if (IsBrOnExn) {
202      const char *CPPExnSymbol = MF.createExternalSymbolName("__cpp_exception");
203      BuildMI(&MBB, DL, get(WebAssembly::BR_ON_EXN))
204          .addMBB(TBB)
205          .addExternalSymbol(CPPExnSymbol)
206          .add(Cond[1]);
207    } else
208      BuildMI(&MBB, DL, get(WebAssembly::BR_IF)).addMBB(TBB).add(Cond[1]);
209  } else {
210    assert(!IsBrOnExn && "br_on_exn does not have a reversed condition");
211    BuildMI(&MBB, DL, get(WebAssembly::BR_UNLESS)).addMBB(TBB).add(Cond[1]);
212  }
213  if (!FBB)
214    return 1;
215
216  BuildMI(&MBB, DL, get(WebAssembly::BR)).addMBB(FBB);
217  return 2;
218}
219
220bool WebAssemblyInstrInfo::reverseBranchCondition(
221    SmallVectorImpl<MachineOperand> &Cond) const {
222  assert(Cond.size() == 2 && "Expected a flag and a condition expression");
223
224  // br_on_exn's condition cannot be reversed
225  MachineFunction &MF = *Cond[1].getParent()->getParent()->getParent();
226  auto &MRI = MF.getRegInfo();
227  if (Cond[1].isReg() &&
228      MRI.getRegClass(Cond[1].getReg()) == &WebAssembly::EXNREFRegClass)
229    return true;
230
231  Cond.front() = MachineOperand::CreateImm(!Cond.front().getImm());
232  return false;
233}
234
235ArrayRef<std::pair<int, const char *>>
236WebAssemblyInstrInfo::getSerializableTargetIndices() const {
237  static const std::pair<int, const char *> TargetIndices[] = {
238      {WebAssembly::TI_LOCAL_START, "wasm-local-start"},
239      {WebAssembly::TI_GLOBAL_START, "wasm-global-start"},
240      {WebAssembly::TI_OPERAND_STACK_START, "wasm-operator-stack-start"}};
241  return makeArrayRef(TargetIndices);
242}
243