Adding decoder for g + bit manipulation instructions.

PiperOrigin-RevId: 668938661
Change-Id: I3079a463d9904da97062810c3f7340911ef1fb79
diff --git a/riscv/BUILD b/riscv/BUILD
index f28fa5a..d5a4200 100644
--- a/riscv/BUILD
+++ b/riscv/BUILD
@@ -427,6 +427,32 @@
 )
 
 cc_library(
+    name = "riscv32g_bitmanip_decoder",
+    srcs = [
+        "riscv32g_bitmanip_decoder.cc",
+        "riscv32gzb_encoding.cc",
+    ],
+    hdrs = [
+        "riscv32g_bitmanip_decoder.h",
+        "riscv32gzb_encoding.h",
+    ],
+    copts = ["-O3"],
+    deps = [
+        ":riscv32gzb_bin_fmt",
+        ":riscv32gzb_isa",
+        ":riscv_encoding_common",
+        ":riscv_getters",
+        ":riscv_state",
+        "@com_google_absl//absl/log",
+        "@com_google_absl//absl/strings",
+        "@com_google_mpact-sim//mpact/sim/generic:core",
+        "@com_google_mpact-sim//mpact/sim/generic:instruction",
+        "@com_google_mpact-sim//mpact/sim/generic:type_helpers",
+        "@com_google_mpact-sim//mpact/sim/util/memory",
+    ],
+)
+
+cc_library(
     name = "riscv32g_vec_decoder",
     srcs = [
         "riscv32g_vec_decoder.cc",
diff --git a/riscv/riscv32g_bitmanip_decoder.cc b/riscv/riscv32g_bitmanip_decoder.cc
new file mode 100644
index 0000000..2644ad5
--- /dev/null
+++ b/riscv/riscv32g_bitmanip_decoder.cc
@@ -0,0 +1,103 @@
+// Copyright 2024 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "riscv/riscv32g_bitmanip_decoder.h"
+
+#include <cstdint>
+#include <new>
+#include <string>
+
+#include "mpact/sim/generic/instruction.h"
+#include "mpact/sim/generic/type_helpers.h"
+#include "mpact/sim/util/memory/memory_interface.h"
+#include "riscv/riscv32gzb_decoder.h"
+#include "riscv/riscv32gzb_encoding.h"
+#include "riscv/riscv32gzb_enums.h"
+#include "riscv/riscv_state.h"
+
+namespace mpact {
+namespace sim {
+namespace riscv {
+
+using ::mpact::sim::generic::operator*;  // NOLINT: is used below (clang error).
+
+RiscV32GBitmanipDecoder::RiscV32GBitmanipDecoder(RiscVState *state,
+                                                 util::MemoryInterface *memory)
+    : state_(state), memory_(memory) {
+  // Need a data buffer to load instructions from memory. Allocate a single
+  // buffer that can be reused for each instruction word.
+  inst_db_ = state_->db_factory()->Allocate<uint32_t>(1);
+  // Allocate the isa factory class, the top level isa decoder instance, and
+  // the encoding parser.
+  riscv_isa_factory_ = new RV32GZBIsaFactory();
+  riscv_isa_ =
+      new isa32gzb::RiscV32GZBInstructionSet(state, riscv_isa_factory_);
+  riscv_encoding_ = new isa32gzb::RiscV32GZBEncoding(state);
+}
+
+RiscV32GBitmanipDecoder::~RiscV32GBitmanipDecoder() {
+  delete riscv_isa_;
+  delete riscv_isa_factory_;
+  delete riscv_encoding_;
+  inst_db_->DecRef();
+}
+
+generic::Instruction *RiscV32GBitmanipDecoder::DecodeInstruction(
+    uint64_t address) {
+  // First check that the address is aligned properly. If not, create and return
+  // an instruction object that will raise an exception.
+  if (address & 0x1) {
+    auto *inst = new generic::Instruction(0, state_);
+    inst->set_size(1);
+    inst->SetDisassemblyString("Misaligned instruction address");
+    inst->set_opcode(*isa32gzb::OpcodeEnum::kNone);
+    inst->set_address(address);
+    inst->set_semantic_function([this](generic::Instruction *inst) {
+      state_->Trap(/*is_interrupt*/ false, inst->address(),
+                   *ExceptionCode::kInstructionAddressMisaligned,
+                   inst->address() ^ 0x1, inst);
+    });
+    return inst;
+  }
+
+  // If the address is greater than the max address, return an instruction
+  // that will raise an exception.
+  if (address > state_->max_physical_address()) {
+    auto *inst = new generic::Instruction(0, state_);
+    inst->set_size(0);
+    inst->SetDisassemblyString("Instruction access fault");
+    inst->set_opcode(*isa32gzb::OpcodeEnum::kNone);
+    inst->set_address(address);
+    inst->set_semantic_function([this](generic::Instruction *inst) {
+      state_->Trap(/*is_interrupt*/ false, inst->address(),
+                   *ExceptionCode::kInstructionAccessFault, inst->address(),
+                   nullptr);
+    });
+    return inst;
+  }
+
+  // Read the instruction word from memory and parse it in the encoding parser.
+  memory_->Load(address, inst_db_, nullptr, nullptr);
+  uint32_t iword = inst_db_->Get<uint32_t>(0);
+  riscv_encoding_->ParseInstruction(iword);
+
+  // Call the isa decoder to obtain a new instruction object for the instruction
+  // word that was parsed above.
+  auto *instruction = riscv_isa_->Decode(address, riscv_encoding_);
+  return instruction;
+}
+
+}  // namespace riscv
+}  // namespace sim
+}  // namespace mpact
diff --git a/riscv/riscv32g_bitmanip_decoder.h b/riscv/riscv32g_bitmanip_decoder.h
new file mode 100644
index 0000000..1205872
--- /dev/null
+++ b/riscv/riscv32g_bitmanip_decoder.h
@@ -0,0 +1,89 @@
+// Copyright 2024 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef THIRD_PARTY_MPACT_RISCV_RISCV32G_BITMANIP_DECODER_H_
+#define THIRD_PARTY_MPACT_RISCV_RISCV32G_BITMANIP_DECODER_H_
+
+#include <cstdint>
+#include <memory>
+
+#include "mpact/sim/generic/data_buffer.h"
+#include "mpact/sim/generic/decoder_interface.h"
+#include "mpact/sim/generic/instruction.h"
+#include "mpact/sim/generic/type_helpers.h"
+#include "mpact/sim/util/memory/memory_interface.h"
+#include "riscv/riscv32gzb_decoder.h"
+#include "riscv/riscv32gzb_encoding.h"
+#include "riscv/riscv32gzb_enums.h"
+#include "riscv/riscv_state.h"
+
+namespace mpact {
+namespace sim {
+namespace riscv {
+
+using ::mpact::sim::generic::Instruction;
+using ::mpact::sim::generic::operator*;  // NOLINT: clang-tidy false positive.
+
+// This is the factory class needed by the generated decoder. It is responsible
+// for creating the decoder for each slot instance. Since the riscv architecture
+// only has a single slot, it's a pretty simple class.
+class RV32GZBIsaFactory : public isa32gzb::RiscV32GZBInstructionSetFactory {
+ public:
+  std::unique_ptr<isa32gzb::Riscv32gzbSlot> CreateRiscv32gzbSlot(
+      ArchState *state) override {
+    return std::make_unique<isa32gzb::Riscv32gzbSlot>(state);
+  }
+};
+
+// This class implements the generic DecoderInterface and provides a bridge
+// to the (isa specific) generated decoder classes.
+class RiscV32GBitmanipDecoder : public generic::DecoderInterface {
+ public:
+  using SlotEnum = isa32gzb::SlotEnum;
+  using OpcodeEnum = isa32gzb::OpcodeEnum;
+
+  RiscV32GBitmanipDecoder(RiscVState *state, util::MemoryInterface *memory);
+  RiscV32GBitmanipDecoder() = delete;
+  ~RiscV32GBitmanipDecoder() override;
+
+  // This will always return a valid instruction that can be executed. In the
+  // case of a decode error, the semantic function in the instruction object
+  // instance will raise an internal simulator error when executed.
+  generic::Instruction *DecodeInstruction(uint64_t address) override;
+  // Return the number of opcodes supported by this decoder.
+  int GetNumOpcodes() const override { return *OpcodeEnum::kPastMaxValue; }
+  // Return the name of the opcode at the given index.
+  const char *GetOpcodeName(int index) const override {
+    return isa32gzb::kOpcodeNames[index];
+  }
+
+  // Getter.
+  isa32gzb::RiscV32GZBEncoding *riscv_encoding() const {
+    return riscv_encoding_;
+  }
+
+ private:
+  RiscVState *state_;
+  util::MemoryInterface *memory_;
+  generic::DataBuffer *inst_db_;
+  isa32gzb::RiscV32GZBEncoding *riscv_encoding_;
+  RV32GZBIsaFactory *riscv_isa_factory_;
+  isa32gzb::RiscV32GZBInstructionSet *riscv_isa_;
+};
+
+}  // namespace riscv
+}  // namespace sim
+}  // namespace mpact
+
+#endif  // THIRD_PARTY_MPACT_RISCV_RISCV32G_BITMANIP_DECODER_H_
diff --git a/riscv/riscv32gzb_encoding.cc b/riscv/riscv32gzb_encoding.cc
new file mode 100644
index 0000000..6538bcb
--- /dev/null
+++ b/riscv/riscv32gzb_encoding.cc
@@ -0,0 +1,159 @@
+// Copyright 2024 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "riscv/riscv32gzb_encoding.h"
+
+#include <cstdint>
+#include <new>
+
+#include "absl/log/log.h"
+#include "absl/strings/str_cat.h"
+#include "mpact/sim/generic/simple_resource.h"
+#include "mpact/sim/generic/simple_resource_operand.h"
+#include "mpact/sim/generic/type_helpers.h"
+#include "riscv/riscv32gzb_bin_decoder.h"
+#include "riscv/riscv32gzb_decoder.h"
+#include "riscv/riscv32gzb_enums.h"
+#include "riscv/riscv_encoding_common.h"
+#include "riscv/riscv_getters.h"
+#include "riscv/riscv_register.h"
+#include "riscv/riscv_state.h"
+
+namespace mpact::sim::riscv::isa32gzb {
+
+using ::mpact::sim::generic::operator*;  // NOLINT: clang-tidy false positive.
+
+RiscV32GZBEncoding::RiscV32GZBEncoding(RiscVState *state)
+    : state_(state),
+      inst_word_(0),
+      opcode_(OpcodeEnum::kNone),
+      format_(FormatEnum::kNone) {
+  resource_pool_ = new generic::SimpleResourcePool("RiscV32GZB", 128);
+  resource_delay_line_ =
+      state_->CreateAndAddDelayLine<generic::SimpleResourceDelayLine>(8);
+  // Initialize getters.
+  source_op_getters_.emplace(*SourceOpEnum::kNone, []() { return nullptr; });
+  dest_op_getters_.emplace(*DestOpEnum::kNone,
+                           [](int latency) { return nullptr; });
+  simple_resource_getters_.emplace(*SimpleResourceEnum::kNone,
+                                   []() { return nullptr; });
+  complex_resource_getters_.emplace(
+      *ComplexResourceEnum::kNone,
+      [](int latency, int end) { return nullptr; });
+  AddRiscVSourceGetters<SourceOpEnum, Extractors, RV32Register, RVFpRegister>(
+      source_op_getters_, this);
+  AddRiscVDestGetters<DestOpEnum, Extractors, RV32Register, RVFpRegister>(
+      dest_op_getters_, this);
+  AddRiscVSimpleResourceGetters<SimpleResourceEnum, Extractors>(
+      simple_resource_getters_, this);
+  // Verify that there are getters for each enum value.
+  for (int i = *SourceOpEnum::kNone; i < *SourceOpEnum::kPastMaxValue; ++i) {
+    if (source_op_getters_.find(i) == source_op_getters_.end()) {
+      LOG(ERROR) << "No getter for source op enum value " << i;
+    }
+  }
+  for (int i = *DestOpEnum::kNone; i < *DestOpEnum::kPastMaxValue; ++i) {
+    if (dest_op_getters_.find(i) == dest_op_getters_.end()) {
+      LOG(ERROR) << "No getter for destination op enum value " << i;
+    }
+  }
+  for (int i = *SimpleResourceEnum::kNone;
+       i < *SimpleResourceEnum::kPastMaxValue; ++i) {
+    if (simple_resource_getters_.find(i) == simple_resource_getters_.end()) {
+      LOG(ERROR) << "No getter for simple resource enum value " << i;
+    }
+  }
+}
+
+RiscV32GZBEncoding::~RiscV32GZBEncoding() { delete resource_pool_; }
+
+void RiscV32GZBEncoding::ParseInstruction(uint32_t inst_word) {
+  inst_word_ = inst_word;
+  if ((inst_word_ & 0x3) == 3) {
+    auto [opcode, format] = DecodeRiscV32GZBInst32WithFormat(inst_word_);
+    opcode_ = opcode;
+    format_ = format;
+    return;
+  }
+  auto [opcode, format] = DecodeRiscV32GZBInst16WithFormat(
+      static_cast<uint16_t>(inst_word & 0xffff));
+  opcode_ = opcode;
+  format_ = format;
+}
+
+ResourceOperandInterface *RiscV32GZBEncoding::GetComplexResourceOperand(
+    SlotEnum, int, OpcodeEnum, ComplexResourceEnum resource, int begin,
+    int end) {
+  int index = static_cast<int>(resource);
+  auto iter = complex_resource_getters_.find(index);
+  if (iter == complex_resource_getters_.end()) {
+    LOG(WARNING) << "No complex resource getter found for resource: " << index;
+    return nullptr;
+  }
+  return (iter->second)(begin, end);
+}
+
+ResourceOperandInterface *RiscV32GZBEncoding::GetSimpleResourceOperand(
+    SlotEnum, int, OpcodeEnum, SimpleResourceVector &resource_vec, int end) {
+  if (resource_vec.empty()) return nullptr;
+  auto *resource_set = resource_pool_->CreateResourceSet();
+  for (auto resource_enum : resource_vec) {
+    int index = static_cast<int>(resource_enum);
+    auto iter = simple_resource_getters_.find(index);
+    if (iter == simple_resource_getters_.end()) {
+      LOG(WARNING) << "No getter for simple resource " << index;
+      continue;
+    }
+    auto *resource = (iter->second)();
+    auto status = resource_set->AddResource(resource);
+    if (!status.ok()) {
+      LOG(ERROR) << "Unable to add resource to resource set ("
+                 << static_cast<int>(resource_enum) << ")";
+    }
+  }
+  auto *op = new generic::SimpleResourceOperand(resource_set, end,
+                                                resource_delay_line_);
+  return op;
+}
+
+DestinationOperandInterface *RiscV32GZBEncoding::GetDestination(
+    SlotEnum, int, OpcodeEnum opcode, DestOpEnum dest_op, int dest_no,
+    int latency) {
+  int index = static_cast<int>(dest_op);
+  auto iter = dest_op_getters_.find(index);
+  if (iter == dest_op_getters_.end()) {
+    LOG(ERROR) << absl::StrCat("No getter for destination op enum value ",
+                               index, "for instruction ",
+                               kOpcodeNames[static_cast<int>(opcode)]);
+    return nullptr;
+  }
+  return (iter->second)(latency);
+}
+
+SourceOperandInterface *RiscV32GZBEncoding::GetSource(SlotEnum, int,
+                                                      OpcodeEnum opcode,
+                                                      SourceOpEnum source_op,
+                                                      int source_no) {
+  int index = static_cast<int>(source_op);
+  auto iter = source_op_getters_.find(index);
+  if (iter == source_op_getters_.end()) {
+    LOG(ERROR) << absl::StrCat("No getter for source op enum value ", index,
+                               " for instruction ",
+                               kOpcodeNames[static_cast<int>(opcode)]);
+    return nullptr;
+  }
+  return (iter->second)();
+}
+
+}  // namespace mpact::sim::riscv::isa32gzb
diff --git a/riscv/riscv32gzb_encoding.h b/riscv/riscv32gzb_encoding.h
new file mode 100644
index 0000000..9b36852
--- /dev/null
+++ b/riscv/riscv32gzb_encoding.h
@@ -0,0 +1,95 @@
+// Copyright 2024 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef THIRD_PARTY_MPACT_RISCV_RISCV32GZB_ENCODING_H_
+#define THIRD_PARTY_MPACT_RISCV_RISCV32GZB_ENCODING_H_
+
+#include <cstdint>
+#include <string>
+
+#include "mpact/sim/generic/simple_resource.h"
+#include "mpact/sim/generic/simple_resource_operand.h"
+#include "riscv/riscv32gzb_bin_decoder.h"
+#include "riscv/riscv32gzb_decoder.h"
+#include "riscv/riscv32gzb_enums.h"
+#include "riscv/riscv_encoding_common.h"
+#include "riscv/riscv_getters.h"
+#include "riscv/riscv_state.h"
+
+namespace mpact::sim::riscv::isa32gzb {
+
+// This class provides the interface between the generated instruction decoder
+// framework (which is agnostic of the actual bit representation of
+// instructions) and the instruction representation. This class provides methods
+// to return the opcode, source operands, and destination operands for
+// instructions according to the operand fields in the encoding.
+class RiscV32GZBEncoding : public RiscV32GZBEncodingBase,
+                           public RiscVEncodingCommon {
+ public:
+  explicit RiscV32GZBEncoding(RiscVState *state);
+  ~RiscV32GZBEncoding() override;
+
+  void ParseInstruction(uint32_t inst_word);
+  OpcodeEnum GetOpcode(SlotEnum, int) { return opcode_; }
+  FormatEnum GetFormat(SlotEnum, int) { return format_; }
+
+  PredicateOperandInterface *GetPredicate(SlotEnum, int, OpcodeEnum,
+                                          PredOpEnum) override {
+    return nullptr;
+  }
+
+  ResourceOperandInterface *GetSimpleResourceOperand(
+      SlotEnum, int, OpcodeEnum, SimpleResourceVector &resource_vec,
+      int end) override;
+
+  ResourceOperandInterface *GetComplexResourceOperand(
+      SlotEnum, int, OpcodeEnum, ComplexResourceEnum resource, int begin,
+      int end);
+
+  SourceOperandInterface *GetSource(SlotEnum, int, OpcodeEnum, SourceOpEnum op,
+                                    int source_no) override;
+
+  DestinationOperandInterface *GetDestination(SlotEnum, int, OpcodeEnum,
+                                              DestOpEnum op, int dest_no,
+                                              int latency) override;
+
+  int GetLatency(SlotEnum, int, OpcodeEnum, DestOpEnum, int) override {
+    return 0;
+  }
+
+  // Methods inherited from RiscVEncodingCommon.
+  RiscVState *state() const override { return state_; }
+  generic::SimpleResourcePool *resource_pool() override {
+    return resource_pool_;
+  }
+  uint32_t inst_word() const override { return inst_word_; }
+
+ private:
+  std::string GetSimpleResourceName(SimpleResourceEnum resource_enum);
+
+  RiscVState *state_;
+  uint32_t inst_word_;
+  OpcodeEnum opcode_;
+  FormatEnum format_;
+  SourceOpGetterMap source_op_getters_;
+  DestOpGetterMap dest_op_getters_;
+  SimpleResourceGetterMap simple_resource_getters_;
+  ComplexResourceGetterMap complex_resource_getters_;
+  generic::SimpleResourceDelayLine *resource_delay_line_ = nullptr;
+  generic::SimpleResourcePool *resource_pool_ = nullptr;
+};
+
+}  // namespace mpact::sim::riscv::isa32gzb
+
+#endif  // THIRD_PARTY_MPACT_RISCV_RISCV32GZB_ENCODING_H_