Update BinFormat.g4 and InstructionSet.g4 comments and rewrite decoder guides. - Update top-level and per-rule comments in BinFormat.g4 and InstructionSet.g4 to accurately reflect current grammar features (format widths and packed structs, overlays, composite instruction groups, GENERATE, specializes, relational and field-to-field constraints, EncodingBase, child instruction tuples, list operands, %reloc, resource windows, and instruction attributes). - Rewrite decoder/doc/binary-encoding.md and decoder/doc/instruction-set.md as comprehensive beginner-friendly guides covering mental models, end-to-end MiniRisc walkthroughs, full language and generated C++ API references, production best practices (modular format and extension factoring from mpact_riscv, mpact_cheriot, and Coral NPU), and troubleshooting checklists. PiperOrigin-RevId: 1024607856 Change-Id: I9ebdee3ae7867aaca21640c2d233f93ddc4f698a
diff --git a/mpact/sim/decoder/BinFormat.g4 b/mpact/sim/decoder/BinFormat.g4 index af4437d..67c8bbd 100644 --- a/mpact/sim/decoder/BinFormat.g4 +++ b/mpact/sim/decoder/BinFormat.g4
@@ -12,19 +12,68 @@ // See the License for the specific language governing permissions and // limitations under the License. -// This grammar is used to specify the structure of the binary encoding of an -// instruction set architecture. The generator tool that reads in this grammar -// will generate code to aid in the decoding of instructions by determining -// which opcode a particular instruction word value matches. Additionally, the -// tool will generate extractor functions to extract the bitfields as described -// in the input description. +// This ANTLR4 file specifies the binary encoding of an instruction set +// architecture (.bin_fmt files) for MPACT-Sim's binary format code generator +// (bin_format_gen). +// +// A .bin_fmt description consists of four main kinds of declarations: +// +// 1. Preprocessor-style directives: +// - An optional '#once' guard at the top of a file to prevent multiple +// inclusions when modularizing descriptions across files. +// - '#include "..."' directives at top level to import other .bin_fmt files. +// +// 2. Instruction formats ('format'): +// - Define fixed-width bit layouts (from small 8/16/32/64-bit instruction +// words up to 128-bit and arbitrary multi-word VLIW bundles). +// - List 'fields' from most-significant bit (MSB) to least-significant bit +// (LSB, bit 0), where each entry is either a signed/unsigned bitfield or a +// nested (and optionally replicated) sub-format. +// - Optionally define 'overlays' (virtual bitfields up to 64 bits wide) +// assembled by concatenating fields, field/format bit slices, and binary +// literals. +// - Optionally inherit from a base format (': BaseFormat') to inherit width, +// share non-conflicting extractors, and group formats into a hierarchy. +// - Optionally specify 'layout: packed_struct;' to emit C++ packed bitfield +// structs and unions alongside functional extractors/inserters. +// +// 3. Instruction groups ('instruction group'): +// - Group instruction encodings that share a bit width (up to 64 bits) and +// whose formats match or derive from a common base format, or merge +// existing compatible instruction groups ('= { Group1, Group2 }'). +// - Each instruction encoding constrains fields or overlays using relational +// operators ('==', '!=', '>', '>=', '<', '<=') against numeric literals or +// other fields/overlays. Encodings also support duplicate-opcode markers +// ('!'), Cartesian-product template expansion ('GENERATE'), and encoding +// specializations ('specializes'). +// +// 4. Decoder specifications ('decoder'): +// - Define code-generation targets naming the C++ 'namespace', the target +// 'opcode_enum' type (generated from the corresponding .isa file), C++ +// header 'includes', and the instruction groups (or merged groups) to +// generate decode functions for. +// +// From a .bin_fmt file, bin_format_gen generates: +// - <prefix>_bin_decoder.{h,cc}: Decode<Group>() and +// Decode<Group>WithFormat() functions mapping instruction words to +// OpcodeEnum (and FormatEnum), plus inline bitfield/sub-format/overlay +// extractor functions (both in per-format namespaces and in +// Extractors::<Format> classes). +// - <prefix>_bin_encoder.{h,cc}: Bitfield/sub-format/overlay inserter +// functions (Encoder::<Format>) and fixed-bit opcode encoding tables +// (kOpcodeEncodings). +// - <prefix>_bin_types.h: FormatEnum and any requested Packed<Format> / +// Union<Format> C++ bitfield types. grammar BinFormat; +// Top-level file rule: an optional '#once' include guard followed by zero or +// more decoder, format, instruction group, or '#include' declarations. top_level : once? declaration_list EOF ; +// Prevents the current .bin_fmt file from being included more than once. once : '#' ONCE ; @@ -37,9 +86,18 @@ : format_def | instruction_group_def | include_file ; -// Defines an instruction format. It may inherit from another format, though -// "inheritance" in this context only refers to the width, and helps group -// formats in a hierarchy. +// Defines an instruction format. +// - 'width' ('[bits]') may be omitted only if 'inherits_from' (': BaseFormat') +// is specified, in which case the width is inherited from BaseFormat (if both +// are given, they must match). +// - Inheritance groups formats under a common ancestor so they can belong to +// the same 'instruction group', and promotes non-conflicting field/overlay +// extractors up to ancestor format namespaces. +// - Formats up to 64 bits pass values as uint8_t/uint16_t/uint32_t/uint64_t, +// formats of 65..128 bits use absl::uint128, and formats wider than 128 bits +// operate on byte buffers (const uint8_t* / uint8_t*). Formats up to 128 +// bits whose bit width is not a power of two generate both integer and +// byte-pointer extractors. format_def : FORMAT name=IDENT width=index? inherits_from? '{' layout_spec? format_field_defs'}' ';'? @@ -49,6 +107,12 @@ : ':' IDENT ; +// Optional C++ representation layout for the format: +// - 'default': Generates functional extractors and inserters only. +// - 'packed_struct': Also emits Packed<Format> (ABSL_ATTRIBUTE_PACKED C++ +// bitfield struct) and Union<Format> in <prefix>_bin_types.h. Supported +// when all fields/sub-formats are <= 64 bits and no sub-format uses an +// array count. layout_spec : LAYOUT ':' layout_type ';' ; @@ -58,23 +122,24 @@ | PACKED_STRUCT ; -// Each format consists of a number of entries whose widths sum up to the -// format widths. Each entry is either a field, or a sub-format (creating -// a hierarchy), with the width specified with array notation. Fields and/or -// sub-formats are ordered left to right within the bits of the format according -// to their order of declaration. Multiple consecutive instances of a sub-format -// may be expressed using array notation. The sub-format instances are ordered -// left to right in the format in order of the instance number. Within each -// field (or sub-format), bits are numbered from high to low going left to -// right, that is, the msb is the highest numbered bit. That means the lsb for -// any format/fields is bit number 0. +// Each format consists of a sequence of field/sub-format entries whose widths +// sum up to the format width, followed by an optional 'overlays:' section. +// Entries are ordered from MSB (left) to LSB (right) according to declaration +// order. Multiple consecutive instances of a sub-format may be expressed using +// array notation ('format SubFmt slot[N];'), ordered left-to-right from +// instance 0 to N-1. Within every format, field, or sub-format, bit 0 is the +// LSB and bit (width - 1) is the MSB. format_field_defs : FIELDS ':' field_def* (OVERLAYS ':' overlay_def*)? ; -// A field is either a named field with a width, or a reference to another -// format. A field may be signed or unsigned. If signed, the extractor function -// will include code to sign-extend the value. +// A field is either: +// 1. A named 'signed' or 'unsigned' bitfield of 'width' bits (up to 64 bits +// if extracted directly), optionally with a '= number' default value. +// Signed fields are sign-extended by their generated extractor. +// 2. A reference to another format ('format FormatName field_name[count]?;'), +// creating a format hierarchy (e.g., slots inside a VLIW bundle). Directly +// extracted sub-formats must be <= 128 bits wide. field_def : sign_spec field_name=IDENT width=index field_assign? ';' | FORMAT format_name=IDENT field_name=IDENT index? ';' @@ -84,9 +149,12 @@ : '=' number ; -// An overlay is defined by a name and a list of bit fields in the format. An -// overlay may be either signed or unsigned. If signed, the extractor function -// will include code to sign-extend the value. +// An overlay defines a virtual 'signed' or 'unsigned' bitfield (up to 64 bits +// wide) formed by concatenating 'bit_field_list' items from MSB (left) to LSB +// (right). The sum of the component widths must equal 'width'. Signed overlays +// are sign-extended by their generated extractor. Binary literal components +// contribute constant bits during extraction (and are skipped during bit +// insertion). overlay_def : sign_spec IDENT width=index '=' bit_field_list ';' ; @@ -103,11 +171,13 @@ : bit_field_spec (',' bit_field_spec)* ; -// A bit field is either: -// - A full named bit field. -// - A set of bit ranges from a bit field. -// - A set of bit ranges from a format. -// - A binary number litera. +// Each component of an overlay is one of: +// - A full named field declared in 'fields:' (e.g., 'imm5'). +// - One or more bit ranges/indices of a named field (e.g., 'imm7[6, 4..0]'). +// - One or more bit ranges/indices directly from the enclosing format +// (e.g., '[31, 7, 30..25]'; also used to slice into nested sub-formats). +// - A binary number literal (e.g., '0b0' or '0b0100\'1010'), whose bit width +// equals the number of binary digits following '0b' (excluding '\''). bit_field_spec : IDENT bit_range_list? | bit_range_list @@ -118,6 +188,8 @@ : BIN_NUMBER ; +// Bit ranges specify descending ('hi..lo', with hi >= lo) or single-bit +// ('bit') slices within the target field or enclosing format. bit_range_list : '[' bit_index_range (',' bit_index_range ) * ']' ; @@ -126,8 +198,11 @@ : number ( DOTDOT number)? ; -// An instruction group lists the encodings of a set of instructions that all -// derive from the same format. +// Defines either: +// 1. A single instruction group of 'number'-bit instructions (up to 64 bits) +// whose encoding formats are 'inst_format' or derive from 'inst_format'. +// 2. A composite instruction group formed by merging two or more previously +// defined instruction groups that share the same width and base format. instruction_group_def : INSTRUCTION GROUP name=IDENT '[' number ']' ':' inst_format=IDENT '{' instruction_def_list '}' ';'? @@ -138,8 +213,17 @@ : instruction_def* ; -// An instruction encoding contains a name, the format it refers to, and a list -// of binary field constraints. +// Specifies one or more instruction encodings within an instruction group: +// 1. Standard encoding: optional '!' ('duplicate'), opcode 'name' (matching +// an opcode in the .isa file, converted to PascalCase 'k<Name>' in +// OpcodeEnum), format name, and comma-separated field/overlay constraints. +// 2. 'GENERATE(...) { ... };': Expands the body across the Cartesian product +// of all 'range_assignment' variable/tuple lists, substituting '$(var)' +// references in instruction names, format names, and constraints. +// 3. Specialization ('name : specializes parent : ...;'): Defines a more +// specific encoding of 'parent' (in the same group), inheriting 'parent's +// format and constraints and adding further constraints tested when +// 'parent' matches. instruction_def : duplicate? name=IDENT ':' format_name=IDENT ':' field_constraint_list ';' | generate=GENERATE '(' range_assignment (',' range_assignment)* ')' @@ -147,10 +231,14 @@ | name=IDENT ':' SPECIALIZES parent=IDENT ':' field_constraint_list ';' ; +// Prefixing an instruction encoding with '!' suppresses the warning normally +// emitted when multiple encodings in a group share the same opcode name. duplicate : '!' ; +// Binds either a single variable ('var = [v1, v2, ...]') or a synchronized +// tuple of variables ('[v1, v2] = [{a1, b1}, {a2, b2}, ...]') for GENERATE. range_assignment : IDENT '=' '[' gen_value (',' gen_value)* ']' | '[' IDENT (',' IDENT)* ']' '=' '[' value_list (',' value_list)* ']' @@ -182,10 +270,11 @@ : field_constraint (',' field_constraint)* ; -// Each field constraint specifies the name or either a field or overlay defined -// in the format the encoding refers to, and whether that field/overlay has to -// be equal, not equal, greater/less, etc. to a number given by a numeric -// literal. +// Constrains a field or overlay ('field_name') in the encoding's format using a +// relational operator against either a numeric literal ('value') or another +// field/overlay ('rhs_field_name') in the same format (e.g., 'rs1 != rs2'). +// Signed fields and overlays support '==' and '!=' against constants/fields; +// unsigned fields and overlays support all six relational operators. field_constraint : field_name=IDENT constraint_op (value=number | rhs_field_name=IDENT) ; @@ -199,10 +288,11 @@ | '<=' ; -// A decoder definition is a named grouping of instruction groups for which a -// binary decoder can be generated. You may speficy multiple decoders. If more -// than one is specified, the name of the decoder to generate code for must be -// passed to the tool. +// A decoder definition specifies a named target for binary decoder/encoder code +// generation, including its C++ namespace, OpcodeEnum type, header includes, +// and the instruction groups (or merged groups) to generate decode functions +// for. Multiple decoders may be declared; if more than one is present, pass +// '--decoder_name=<name>' to bin_format_gen to select which one to generate. decoder_def : DECODER name=IDENT '{' decoder_attribute* '}' ';'? ; @@ -215,28 +305,34 @@ ; -// Namespaces can be specified to wrap the body of the instruction set. Inside -// the name spaces is the declaration of the instruction format layouts, as -// well as the full instruction encodings. +// Specifies the C++ namespace in which the generated decoder, extractors, +// encoders, and format types will be placed (at most one per decoder block). namespace_decl : NAMESPACE namespace_ident ( '::' namespace_ident) * ';' ; +// Specifies the C++ OpcodeEnum type name returned by generated Decode<Group>() +// functions (typically the enum generated from the corresponding .isa file). +// Required inside every decoder block. opcode_enum_decl : OPCODE_ENUM '=' STRING_LITERAL ';' ; +// C++ '#include' directives to emit into the generated decoder header (for +// example, the '*_enums.h' header defining OpcodeEnum). include_files : INCLUDE_FILES '{' include_file* '}' ';'? ; +// At top level, imports another .bin_fmt file. Inside 'includes { ... }' in a +// decoder block, emits a C++ '#include' line into the generated header. include_file : INCLUDE STRING_LITERAL ; -// A group name is either the name of an instruction group or a ident for -// a new instruction group that is the result of merging the list of groups -// specified in braces. +// References an existing instruction group to generate a decoder for, or +// defines a new merged instruction group inline from two or more compatible +// groups listed in braces. group_name : IDENT ';' | IDENT '=' '{' group_name_list '}' ';' @@ -281,7 +377,8 @@ PACKED_STRUCT : 'packed_struct'; ONCE : 'once'; -// Other tokens. +// Identifiers, '$(var)' generator references, strings, numeric literals (which +// allow single-quote '\'' digit separators), range operator, and comments. STRING_LITERAL : UNTERMINATED_STRING_LITERAL '"'; fragment UNTERMINATED_STRING_LITERAL : '"' (~["\\\r\n] | '\\' (. | EOF))*; IDENT : [_a-zA-Z][_a-zA-Z0-9]*;
diff --git a/mpact/sim/decoder/InstructionSet.g4 b/mpact/sim/decoder/InstructionSet.g4 index 48e4192..3d41e6b 100644 --- a/mpact/sim/decoder/InstructionSet.g4 +++ b/mpact/sim/decoder/InstructionSet.g4
@@ -13,64 +13,55 @@ // limitations under the License. -// This grammar is used to specify the structure of the instruction decoder and -// is used by the parser to generate the encoding independent part of the basic -// instruction decoder. This grammar does not addess the actual encoding of the -// instruction as that may be expressed in multiple different forms, such as -// traditional binary, protobuff, etc. The code generated from this grammar -// will declare virtual methods to obtain opcodes and operands from the -// encoding that need to be overridden with methods cognizant of the actual -// instruction encoding used. +// This ANTLR4 file specifies the representation-independent structure of an +// instruction set architecture (.isa files) for MPACT-Sim's decoder generator +// (decoder_gen). It does not describe how instructions are encoded in bits, +// protobuf messages, or text; instead, decoder_gen generates an abstract +// encoding interface class (<IsaName>EncodingBase) whose virtual methods +// extract opcodes, predicates, source/destination operands, latencies, and +// hardware resource operands from whatever concrete encoding representation the +// simulator uses (for example, code generated from BinFormat.g4). // -// The grammar specifies the instruction word structure of an ISA, i.e., -// the grouping and structure of instruction words. At its simplest, the ISA -// consists of a single slot, where any opcode is valid. This is the case for -// most traditional architectures, where the ISA is really sequential (though -// the implementation may do parallel issue), such as the x86 and Arm ISAs. +// The language models the issue and word structure of an ISA: +// - Scalar / sequential ISAs (such as RISC-V, Arm, or x86) typically consist +// of a single top-level 'slot' containing all valid opcodes. +// - VLIW ISAs pack multiple instructions into a wide instruction word, or +// 'bundle', issued in parallel. Each instruction position in a bundle is a +// 'slot' (or an indexed instance of a replicated 'slot[N]'). Slots within a +// bundle may share opcodes or restrict opcodes by slot type/instance. +// - Complex VLIW ISAs may further divide a top-level bundle into nested +// sub-'bundles' that are fetched together as a unit but dispatched +// separately (possibly in different cycles). // -// A VLIW based ISA supports specifying multiple instructions in a large -// instruction word, or bundle, that will be issued in parallel. Each -// instruction within the large instruction word occupies a slot. In the case -// of a binary instruction encoding, a slot refers to a specific bit range -// (or bit ranges if the slot is replicated) within the instruction word. In -// case of a protobuf based encoding, a slot refers to one or more message -// instances. The individual slots within a bundle may support the same set of -// opcodes, or the opcodes may be restricted by the slot instance. The latter -// allows for different instruction slots to have different layout and widths, -// optimizing for the specific opcodes (e.g., load/store vs alu) assigned to -// each slot. +// Key constructs in a .isa file: +// - 'isa <Name>': Top-level target specifying the C++ 'namespace' and the +// top-level 'bundles' or 'slots' of the architecture. +// - 'bundle <Name>': Groups child 'bundles' and/or 'slots' (with optional +// instance slices such as 'alu[0..1, 3]') and binds a bundle-level +// 'semfunc' responsible for dispatching them. +// - 'slot <Name>[N]?': Defines valid 'opcodes' plus slot defaults ('default +// size', 'default latency', 'default opcode', 'default attributes'), local +// 'int' constants, reusable 'resources', and C++ header 'includes'. Slots +// can be parameterized ('template <int ...> slot ...') and composed via +// tree-structured inheritance (': base1, base2<expr>'), selectively +// removing ('= delete') or customizing ('= override') inherited opcodes. +// - 'opcodes': Declare instructions, their byte size, operand triplets +// ('{ pred : sources : dests }') or multi-phase parent/child operand lists +// ('{ (parent_ops), (child_ops), ... }'), scalar or list ('[op]') operands, +// '%reloc(op)' annotations, compile-time or dynamic ('(*)') destination +// latencies, 'GENERATE' template expansions, and opcode attributes +// ('semfunc', 'disasm', 'resources', 'attributes', 'latency'). // -// A yet more complex ISA may divide a top level bundle into more than one -// "sub-bundles". The idea here is that while the top level bundle is fetched -// and "issued" as a unit, the sub-bundles are then separated and issued -// separately, possibly in different cycles. -// -// The top level of the grammar is the specification of the ISA name and the -// name of the class that provides access to the opcode that is being decoded. -// The details of that "encoding" class is not used by the generated code, -// instead a pointer to that class is passed to pure virtual methods that -// the overall decoder will have to provide overriding implementations for -// to have a working decoder. -// -// The ISA is then broken down into one or more bundles and/or slots. A bundle -// typically contains a group of slots that correspond to the set of -// instructions that are fetched and issued together as part of a long -// instruction word. However, a bundle may also contain other bundles that -// are issued as separate groups of instructions. -// -// Each slot contains one or more opcodes that represent the set of valid -// instructions for that slot. Since the same opcode may be valid in multiple -// slots, it is possible to define slots that aren't used directly in any -// bundle, but are used as "base classes" for those that are, allowing common -// opcodes to be factored out for ease of expression and maintenance. -// -// An opcode represents an instruction and contains an optional predicate -// operand name, an optional list of source operand names, and an optional -// list of destination operand names. The opcode name is used to generate an -// enumeration type used by the decoder. The operand names are used to -// declare virtual getter methods in the slot class for creating source and -// destination operands. The operand names are intended to correspond to -// specific operand fields in the instruction encoding. +// From a .isa file, decoder_gen generates: +// - <prefix>_enums.{h,cc}: SlotEnum, OpcodeEnum, PredOpEnum, SourceOpEnum, +// ListSourceOpEnum, DestOpEnum, ListDestOpEnum, SimpleResourceEnum, +// ComplexResourceEnum, ListComplexResourceEnum, string name arrays, and +// per-slot AttributeEnum types. +// - <prefix>_decoder.{h,cc}: <IsaName>EncodingBase, per-slot and per-bundle +// decoder classes, <IsaName>InstructionSetFactory, and +// <IsaName>InstructionSet. +// - <prefix>_encoder.{h,cc}: <IsaName>EncoderInterfaceBase and regex-based +// <SlotName>Matcher classes derived from 'disasm' format strings. grammar InstructionSet; @@ -86,6 +77,10 @@ : declaration* EOF ; +// Top-level declarations: '.isa' file imports ('#include'), global C++ header +// blocks ('includes'), ISA targets ('isa'), VLIW 'bundle' and 'slot' +// definitions, disassembly column widths ('disasm widths'), and global 'int' +// constants. declaration : include_file | include_file_list @@ -96,56 +91,60 @@ | constant_def ; -// The include_file_list lists files to include in the generated source. This -// may be specified at the global scope, or within each slot. Slot local Include -// files are only added to the generated code if that slot is used. This is -// to make it possible to avoid adding include files that will not be used -// in the final isa decoder. If there are multiple global include file lists, -// their content are merged. +// Lists C++ '#include' files to emit into the generated '*_decoder.cc' file +// (for example, headers declaring semantic functions). This block may appear at +// global scope, inside a 'bundle', or inside a 'slot'. Global 'includes' are +// always emitted; bundle- and slot-local 'includes' are merged and emitted only +// if that bundle or slot is reachable from the selected 'isa' (directly or via +// inheritance). include_file_list : INCLUDE_FILES '{' include_file* '}' ; +// Defines a named integer constant ('int name = expression;') at global scope +// or inside a slot. constant_def : template_parameter_type ident '=' expression ';' ; -// This rule specifies the disassembler field widths and alignments. A -// diasassembly string is specified by a number of fragments. Typically an -// opcode fragment followed by a fragment for the operands. This declaration -// specifies the field width for each fragment in order left to right, and -// whether the fragment is left justified (negative number) or right -// justified (positive number) within that field. +// Specifies disassembler column widths and alignments. Each 'disasm' attribute +// on an opcode provides one or more comma-separated format fragments (typically +// a mnemonic fragment followed by an operands fragment). This declaration sets +// the character width for each fragment from left to right, and whether each +// fragment is left-justified (negative width, e.g., -18) or right-justified +// (positive width, e.g., 18) within its column. disasm_widths : DISASM WIDTHS '=' '{' (expression (',' expression) *)? '}' ';' ; -// This rule defines the name of an ISA description as well as the -// name of the type that wraps the encoding of the instruction. The ISA instance -// contains either a list of instruction slots or a list of instruction bundles. -// There is either one ISA description, or if there are more than one, only one -// can be selected for code generation. +// Defines a top-level ISA target, its generated C++ namespace, and either its +// top-level 'bundles' or its top-level 'slots'. 'instruction_set_name' +// determines generated class prefixes such as <IsaName>EncodingBase, +// <IsaName>InstructionSet, and <IsaName>InstructionSetFactory. Multiple 'isa' +// declarations may appear; if more than one is defined, pass '--isa_name' to +// decoder_gen to select which one to generate. isa_declaration : ISA instruction_set_name=IDENT '{' namespace_decl (bundle_list | slot_list) '}' ; -// The namespace_decl rule is used to specify which namespace in which to -// generate the code for the isa. +// Specifies the C++ namespace in which code for this ISA is generated. namespace_decl : NAMESPACE namespace_ident ('::' namespace_ident) * ';' ; -// Mactches #include "<path to file>". +// Matches '#include "<path>"'. At top level, parses and imports declarations +// from another '.isa' file; inside 'includes { ... }', emits a C++ '#include' +// directive into the generated '*_decoder.cc' file. include_file : INCLUDE STRING_LITERAL ; -// A bundle_declaration has a name and specifies a semantic function, which is -// is responsible for dispatching the instructions for the bundles and/or slots -// It also specifies the bundles and/or slots the set of bundles and/or slots -// it contains. At least one slot or bundle has to be specified. +// Defines a VLIW bundle containing child 'bundles' and/or 'slots', optional +// bundle-local C++ 'includes', and a bundle-level 'semfunc' responsible for +// executing/dispatching its constituent sub-bundles and slots. At least one +// child bundle or slot must be specified in the bundle body. bundle_declaration : BUNDLE bundle_name=IDENT '{' bundle_parts* '}' ; @@ -157,7 +156,7 @@ | semfunc_spec ';' ; -// A bundle list is a non-empty list of bundle identifiers +// Lists sub-bundles contained in an 'isa' or 'bundle' block. bundle_list : BUNDLES '{' (bundle_spec ';')* ','? '}' @@ -167,39 +166,42 @@ : IDENT ; -// A slot list is a non-empty list of slot specifiers. +// Lists slots (and optional instance ranges) contained in an 'isa' or 'bundle'. slot_list : SLOTS '{' (slot_spec ';')* ','? '}' ; -// A slot specifier is a slot name with an optional range specification -// to specify which instances are being used when the slot may occur multiple -// times in a bundle or across multiple bundles. See below for slot declaration. +// References a declared slot, optionally selecting specific instance indices or +// ranges when the slot was declared with multiple instances ('slot name[N]'). slot_spec : IDENT array_spec? ; -// The list of ranges of slot instances used. +// Comma-separated list of slot instance indices or inclusive 'start..end' +// ranges (0-based). array_spec : '[' range_spec (',' range_spec)* ']' ; -// A single index, or range of indices. +// A single 0-based instance index, or an inclusive range of indices. range_spec : range_start=NUMBER (DOTDOT range_end=NUMBER)? ; -// Declares a slot with an optional size spec ([size]) indicating that it has -// multiple instances. It may optionally inherit from another slot. Note, -// it is an error for a base slot that isn't used directly in the ISA (i.e., -// only by inheritance) to have a size specification. It is also an error -// if not all slot instances are referenced in the isa (either at the top -// level, from within a bundle, or in an inheritance specification). -// A template slot may not have a size specification. +// Declares either a templated slot ('template <int ...> slot name') or a plain +// slot ('slot name[count]?'), optionally inheriting from one or more base slots +// or instantiated template slots (tree-structured inheritance only; diamond +// inheritance of the same ancestor or duplicate inherited opcodes is an error). +// Notes: +// - Only plain slots referenced directly by an 'isa' or 'bundle' may specify +// an instance count ('[count]'); unreferenced base slots and template slots +// may not have a size specification. +// - When a slot specifies '[count]', all instances 0..count-1 must be +// referenced across the ISA/bundles. slot_declaration // Template slot. @@ -218,13 +220,14 @@ : template_parameter_type IDENT ; -// Only integer valued template parameters are allowed for now. +// Only integer-valued template parameters and constants are currently +// supported. template_parameter_type : INT ; -// Can inherit from slots or templated slots. +// Comma-separated list of base slots or template slot instantiations. base_item_list : base_item (',' base_item)* @@ -238,7 +241,10 @@ : '<' expression (',' expression) * '>' ; -// Integer literals or template parameter names are allowed. +// Compile-time integer expression supporting numeric literals, global/slot +// constants, template parameters, destination operand latency references (in +// resource cycle expressions), unary '-', '+', '-', '*', '/', parentheses, and +// built-in functions (currently 'abs(expr)'). expression : negop expr=expression @@ -262,12 +268,26 @@ : '+' | '-' ; -// Number of instances. +// Number of slot instances (for 'slot name[N]') or instruction byte size (for +// 'opcode_name[bytes]'). size_spec : '[' NUMBER ']' ; +// Slot-scoped defaults, constants, named resource groups, and C++ includes: +// - 'default latency = expr;': Default destination operand latency in cycles +// when an opcode's destination omits '(...)'. +// - 'default size = N;': Default byte size for opcodes in this slot. +// - 'default opcode = ...;': Attributes (must include 'semfunc:') used for +// unmatched/invalid opcodes (OpcodeEnum::kNone) and as fallback 'semfunc' +// when an opcode omits 'semfunc:'. Required on every referenced slot. +// - 'default attributes = { ... };': Default instruction attribute values +// applied to every instruction in this slot unless overridden per-opcode. +// - 'int ident = expr;': Slot-local integer constant. +// - 'resources ident = ...;': Named resource specification reusable by +// opcodes in this slot via 'resources: ident'. +// - 'includes { ... }': Slot-local C++ '#include' headers. const_and_default_decl : DEFAULT LATENCY '=' expression ';' | DEFAULT SIZE '=' NUMBER ';' @@ -289,15 +309,19 @@ : (opcode_spec ';') * ; -// An opcode has a name, an optional predicate operand name, followed by -// optional lists of source and destination operand names. Each is separated -// by a colon. The colon between the predicate operand name and the source -// operand name list is mandatory even if there is no predicate operand name. -// The colon between the source and destination operand name lists is only -// required if there is a destination operand list. An opcode name is required -// to be unique. An opcode that would otherwise be inherited can be deleted -// from the derived slot. This means that a derived slot isn't necessarily a -// true superset of the base slot. +// Specifies an opcode entry inside a slot's 'opcodes { ... }' block: +// 1. Definition: 'name [byte_size]? { operand_spec } (, attributes)?' +// Opcode names must be unique across the ISA and generate 'k<PascalName>' +// enumerators in OpcodeEnum. +// 2. Deletion: 'name = delete' +// Excludes an opcode that would otherwise be inherited from a base slot. +// 3. Override: 'name = override, opcode_attribute_list' +// Modifies attributes ('semfunc', 'disasm', 'resources', 'attributes', or +// 'latency') of an opcode inherited from a base slot while preserving its +// operands and size. +// 4. Generator: 'GENERATE(range_assignments) { ... };' +// Expands parameterized opcode definitions across the Cartesian product of +// variable or tuple value lists using '$(var)' substitution. opcode_spec : name=IDENT @@ -310,6 +334,10 @@ '{' generator_opcode_spec_list '}' ; +// Either a single operand specification (for a single-phase instruction) or a +// comma-separated list of parenthesized operand specifications where the first +// tuple describes the parent Instruction and each subsequent tuple describes a +// chained child Instruction (e.g., load address issue followed by writeback). operand_spec : opcode_operands | opcode_operands_list @@ -319,6 +347,13 @@ : '(' opcode_operands ')' (',' '(' opcode_operands ')' )* ; +// Operand triplet: optional predicate operand, optional ':' + source operand +// list, and optional ':' + destination operand list. Examples: +// - '{}' (no operands) +// - '{ pred }' (predicate only) +// - '{ : rs1, imm12 }' (sources only) +// - '{ : rs1, rs2 : rd }' (sources and destination, no predicate) +// - '{ pred : rs1 : rd(2) }' (predicate, source, and destination) opcode_operands : pred=IDENT? (':' source=source_list? ( ':' dest_list? )? )? ; @@ -327,17 +362,30 @@ : source_operand (',' source_operand)* ; +// A scalar source operand (mapped to SourceOpEnum and GetSource()) or a +// bracketed list/array source operand '[ident]' (mapped to ListSourceOpEnum and +// GetSources(), e.g., for register-list push/stm instructions). source_operand : operand | '[' array_source=IDENT ']' ; +// Optional '%reloc(op_name)' marks an operand as carrying relocation metadata +// for encoder/assembler generation. operand : op_attribute=OP_ATTRIBUTE '(' op_name=IDENT ')' | op_name=IDENT ; -// Destination operands may include a latency. +// Destination operands may be scalar (DestOpEnum / GetDestination()) or +// bracketed list/array operands '[ident]' (ListDestOpEnum / GetDestinations()), +// and each must resolve to a writeback latency: +// - '(expression)': Compile-time cycle latency (0 = immediate writeback, +// >= 1 = buffered writeback after N cycles). +// - '(*)': Dynamic latency queried at decode time via +// <IsaName>EncodingBase::GetLatency(...). +// - Omitted: Uses the enclosing slot's 'default latency' (error if none is +// defined unless overridden via a 'latency:' attribute). dest_list : dest_operand (',' dest_operand)* @@ -348,7 +396,9 @@ ( '(' (expression | wildcard='*' ) ')' )? ; -// Special rules for generator instruction descriptions. +// Variable and tuple range bindings for 'GENERATE(...)': +// - Single variable: 'var = [val1, val2, ...]' +// - Tuple binding: '[v1, v2] = [{a1, b1}, {a2, b2}, ...]' range_assignment : IDENT '=' '[' gen_value (',' gen_value)* ']' | '[' IDENT (',' IDENT)* ']' '=' '[' value_list (',' value_list)* ']' @@ -392,13 +442,16 @@ : var_ident=(VAR_IDENT | IDENT) (',' var_ident=(VAR_IDENT | IDENT)) * ; -// An opcode attribute list is a comma separated list with at least one member. +// An opcode attribute list is a comma-separated list with at least one member. opcode_attribute_list : opcode_attribute (',' opcode_attribute)* ; -// An opcode attribute is either a disassembly specifier or a semfunc specifier. +// An opcode attribute specifies disassembly formatting ('disasm:'), semantic +// function bindings ('semfunc:'), hardware resource usage ('resources:'), +// integer metadata tags ('attributes:'), or destination operand latencies +// ('latency:'). At most one attribute of each kind may be given per opcode. opcode_attribute : disasm_spec @@ -408,16 +461,25 @@ | latency_spec ; -// The disassembly specifier lists a sequence of format strings. Each formatted -// string is printed within a field of the width and justification specified in -// the global "disasm widths" declaration. If no widths are specified, or fewer -// widths are specified than there are format strings, the "extra" formatted -// strings are concatenated with no explicit width or justification applied. +// The disassembly specifier lists one or more format strings (applied to the +// parent instruction). Each string is formatted within the corresponding column +// width and justification from the global 'disasm widths' declaration; any +// remaining strings beyond the declared widths are concatenated directly. +// Within format strings: +// - '%op' substitutes the operand's AsString() text; '%op?' omits/formats +// optional operands such as predicates. +// - '%(expr:fmt)' formats integer expressions involving '@' (the instruction +// address), '@ +/- op', parenthesized bit shifts ('(op << N)' or +// '@ +/- (op >> N)'), and radix/width specifiers ':d', ':o', ':x' (which +// automatically prepends '0x'), or ':X' (uppercase hex without '0x'), with +// an optional 1- or 2-digit width such as ':08x' or ':04d'. disasm_spec : DISASM ':' STRING_LITERAL ( ',' STRING_LITERAL )* ; -// The latency specifier lists the destination operands and their latencies. +// Specifies or overrides latencies for existing destination operands of the +// opcode (useful with '= override' in derived slots or alongside operand +// declarations). latency_spec : LATENCY ':' dest_operand_latency_list ; @@ -431,28 +493,30 @@ ('(' (expression | wildcard='*' ) ')')? ; -// The semantic function specifier lists a sequence of strings that in C++ can -// be assigned to a C++ callables with signature void(Instruction *). These -// will be used when dispatching the instruction. There will be one string -// for the instruction itself, plus one for each child instruction. -// E.g., -// Given the following function definitions: +// The semantic function specifier lists C++ expressions convertible to +// Instruction::SemanticFunction (callable as 'void(Instruction *)'), used when +// executing the instruction. Provide one string for the parent instruction plus +// one string for each child instruction in order. +// E.g., given: // -// void MyCFunction(const Instruction *); +// void MySemFunc(Instruction *); // void MyOtherFcn(int num_regs, Instruction *); // void MyThirdFcn(Instruction *, int width); // -// The strings should be: +// valid strings include: // -// "&MyCFunction" -// "absl::bind_front(&MyOtherFcn, /*num_regs*/ 8)" -// "std::bind(&MyThirdFcn, std::_1, /*width*/ 32)" +// "&MySemFunc" +// "absl::bind_front(&MyOtherFcn, /*num_regs=*/8)" +// "std::bind(&MyThirdFcn, std::placeholders::_1, /*width=*/32)" +// "[](Instruction *inst) { /* inline semantics */ }" // semfunc_spec : SEMFUNC ':' STRING_LITERAL ( ',' STRING_LITERAL )* ; -// The resource specifier lists the resource uses of the instruction. +// Specifies hardware hazard/pipeline resources used, acquired, or held by the +// instruction, either inline ('{ use : acquire : hold }') or by referencing a +// named 'resources' definition declared in the enclosing slot. resource_spec : RESOURCES ':' resource_details ; @@ -461,6 +525,14 @@ : ATTRIBUTES ':' instruction_attribute_list ; +// Resource details contain up to three colon-separated lists: +// - 'use_list': Resources that must be free at dispatch/issue time (checked +// only, not reserved). +// - 'acquire_list': Resources that must be free at dispatch time AND are +// reserved for their specified '[begin..end]' cycle window. +// - 'hold_list': Resources reserved for their '[begin..end]' cycle window +// without checking whether they are already free at dispatch time. +// Or 'ident' referencing a slot-level 'resources ident = ...;' declaration. resource_details : '{' use_list=resource_item_list? (':' acquire_list=resource_item_list? @@ -472,26 +544,35 @@ : resource_item (',' resource_item)* ; -// The resource will be acquired from begin_cycle to end_cycle. If omitted, -// end_cycle is the result latency of the instruction. If omitted, begin_cycle -// is cycle 0 (when the instruction issues). +// Scalar ('name') or list/array ('[name]') resource reference with an optional +// cycle window '[begin_cycle..end_cycle]': +// - If 'begin_cycle' is omitted, it defaults to cycle 0 (issue cycle). Any +// resource acquired with a non-zero 'begin_cycle' in the ISA is classified +// as a complex resource (ComplexResourceEnum / ListComplexResourceEnum); +// resources acquired only from cycle 0 are simple resources +// (SimpleResourceEnum). +// - If 'end_cycle' is omitted, it defaults to the latency of the matching +// destination operand (if 'name' names a destination operand or references +// one in its cycle expression), or 0 otherwise. // Examples: -// x[1..3]: x is acquired starting the cycle after issue through cycle 3. -// x[..3]: x is acquired starting at issue through cycle 3. -// x[] or x: x is acquired starting at issue through the instruction latency. -// x[2]: x is acquired starting at cycle 2 through the instruction latency. +// x[1..3]: reserved from cycle 1 (cycle after issue) through cycle 3. +// x[..3]: reserved from cycle 0 (issue) through cycle 3. +// x[] or x: reserved from cycle 0 through matching dest latency (or 0). +// x[2..]: reserved from cycle 2 through matching dest latency (or 0). resource_item : ( name=IDENT | '[' array_name=IDENT ']' ) ('[' (begin_cycle=expression)? ('..' end_cycle=expression? )? ']')? ; -// Instruction attributes are a list of attribute names that are assigned -// a value such as: { priv=0, branch=1.. } etc. Values can be omitted, in -// which case the value is 1. Attributes that are not named are implicitly -// defined to have value 0. All attribute names in an isa are listed in an -// enum class and are used as the index into the instruction attribute -// array. +// Instruction attributes assign compile-time integer metadata values to an +// instruction, e.g., '{ is_branch = 1, priv = 2 }'. If '= expression' is +// omitted (e.g., '{ attr_a }' to declare an attribute in 'default attributes'), +// its value is 0. Attributes declared in a slot but omitted on an opcode +// inherit the slot's 'default attributes' value (or 0 if unset). For each slot +// with attributes, decoder_gen emits 'namespace <slot_snake> { enum class +// AttributeEnum { k<AttrPascal> = ..., kPastMaxValue = ... }; }' in +// '*_enums.h' to index into Instruction::Attributes(). instruction_attribute_list : '{' instruction_attribute (',' instruction_attribute)* '}' @@ -548,7 +629,8 @@ OP_ATTRIBUTE : '%reloc'; -// Other tokens. +// Identifiers, '$(var)' generator references, strings, numeric literals (which +// allow single-quote '\'' digit separators), range operator, and comments. STRING_LITERAL : UNTERMINATED_STRING_LITERAL '"'; fragment UNTERMINATED_STRING_LITERAL : '"' (~["\\\r\n] | '\\' (. | EOF))*; IDENT : [_a-zA-Z][_a-zA-Z0-9]*;
diff --git a/mpact/sim/decoder/doc/binary-encoding.md b/mpact/sim/decoder/doc/binary-encoding.md index 960d3f9..08fe6cf 100644 --- a/mpact/sim/decoder/doc/binary-encoding.md +++ b/mpact/sim/decoder/doc/binary-encoding.md
@@ -1,598 +1,1128 @@ -# MPACT-Sim Binary Instruction Decoder Generator +# Writing Binary Encoding Descriptions in MPACT-Sim (`.bin_fmt`) -# Goals +This guide explains how to write **binary encoding description files** +(`.bin_fmt`) in MPACT-Sim using the `BinFormat.g4` grammar and the +`bin_format_gen` code generator. It is written for developers who are new to +MPACT-Sim and want to build an instruction decoder (or encoder) for a scalar, +RISC, CISC-like fixed-word, or VLIW architecture. -* Define a convenient format for describing binary instruction formats and - instruction encodings. -* Create an algorithm to partition the instructions into groups for faster - decode. -* Generate C++ code for an efficient decoder to decode the instructions in the - description +For the companion guide on describing instruction semantics, operands, slots, +and bundles, see [instruction-set.md](instruction-set.md). -# Overview +-------------------------------------------------------------------------------- -A binary instruction decoder is tedious and at times error prone to write by -hand. For instance, the Risc-V RV32G instruction set consists of 122 separate -instructions and over a dozen instruction formats. Other architectures have -more, such as the The TI C64+ DSP with almost 250 different instructions -(including 35 compact encodings). +## 1. Big Picture: How MPACT-Sim Decodes Binary Instructions -While the decoder source code may be repetitive, the large number of bit-field -extractions and value comparisons makes it more likely to introduce careless -bugs that are hard to track down. Moreover, responding to changes in the -encoding formats or overall encoding scheme requires a lot of rework, and makes -binary encoding a poor choice for doing what-if analysis and architectural -exploration. However, given that it is the preferred output format for most tool -chains, it is almost without exception necessary to support. +Writing a binary instruction decoder by hand in C++—shifting, masking, +sign-extending scattered immediate bits, and matching hundreds of opcodes—is +repetitive and error-prone. MPACT-Sim automates this by splitting instruction +decoding into **two declarative domain-specific languages** plus a small C++ +adapter class: -Defining a declarative format for describing instruction encodings and providing -a tool that parses generating the C++ code to perform the instruction decoding -not only improves programmer productivity, but provides a much more readable -specification of the implementation that can more easily be compared to the ISA -manual. Changes to instruction encodings are trivial to implement, and the -resulting decoder code is correct by construction. - -# Binary Instruction Description - -The binary instruction description file has two main components: a set of -instruction format definitions and a set of instruction encoding definitions. -The former defines the layout of bit fields in an instruction format, as well as -overlays, which can be considered virtual fields that can be constructed by -concatenating bit constants and/or fragments of the instruction word. Overlays -are useful if there are alternative interpretations of the bits in an -instruction, or if the bits in a field have to be reordered to be interpreted -correctly. For instance, in the RiscV ISA, the 32 bit store instructions -concatenate two separate, non adjacent bit fields to form the 12 bit signed -offset used in the address calculation. Another example, also from the RiscV -ISA, are the 32 bit branch instructions. The branch offset is constructed from -two immediates, but instead of just concatenating the two fields, they are -intertwined, concatenating the two msb’s, followed by the concatenation of the -remainder of the fields, adding a constant 0 bit at the lsb, to create a byte -address. - -Instruction encodings are described separately, grouped by instruction size, and -lists constraints (equal or not equal) on field values in the instruction -format. - -## Instruction Formats - -The instruction format definition has three components. The header defines the -format name, the bit width, and an optional base format. The base format helps -group formats together in a hierarchy. Only instruction encodings using formats -that derive from the same base can be put into the same instruction encoding -group. This allows encodings for execution mode dependent instructions to be -grouped according to mode and decoded accordingly, or merely a way of forcing -some instructions to be decoded in separate decode functions than others. An -example from RiscV RV32G is shown below. +1. **The Binary Encoding Description (`.bin_fmt`, this guide)**: Describes *how + bits are laid out in memory*: + * **Formats** (`format`): How an instruction word or VLIW bundle is + divided into bitfields, nested sub-formats, and reassembled virtual + fields (**overlays**). + * **Instruction Groups** (`instruction group`): Which bit-pattern + constraints (`opcode == 0x33`, `func3 == 0`, `rs1 != 0`, etc.) identify + each instruction opcode. + * **Decoder Target** (`decoder`): Which C++ namespace, `OpcodeEnum` type, + and instruction groups to generate C++ code for. +2. **The ISA Description (`.isa`, see + [instruction-set.md](instruction-set.md))**: Describes *what each + instruction does* independently of its bit encoding: slots, VLIW bundles, + source/destination/predicate operands, latencies, C++ semantic functions, + disassembly strings, and hardware resources. +3. **Your Encoding Adapter Class (`<IsaName>EncodingBase` subclass)**: A small + C++ class you write that bridges the two generated libraries: it passes a + fetched instruction word to the generated `Decode<Group>()` function to get + the `OpcodeEnum`, and uses the generated `Extract<Field>()` functions to + construct register and immediate operands when requested by the `.isa` + decoder. ``` -format BType[32] : Inst32 + Raw Instruction Bits (uint16_t / uint32_t / uint64_t / uint8_t[]) + | + v + +------------------------------------------------------------------+ + | Generated from .bin_fmt (bin_format_gen) | + | - Decode<Group>(inst_word) -> OpcodeEnum | + | - <fmt>::Extract<Field>(inst_word)-> integer / sub-format bits | + | - Encoder::<Fmt>::Insert<Field>() -> bit insertion for encoding | + +------------------------------------------------------------------+ + | + v + +------------------------------------------------------------------+ + | Your C++ Subclass of <IsaName>EncodingBase | + | - GetOpcode(...) returns decoded OpcodeEnum | + | - GetSource(...) uses Extract* to build SourceOperands | + | - GetDestination(...) uses Extract* to build DestOperands | + +------------------------------------------------------------------+ + | + v + +------------------------------------------------------------------+ + | Generated from .isa (decoder_gen) | + | - Builds mpact::sim::generic::Instruction* with semantic | + | functions, operands, latencies, disassembly, and attributes | + +------------------------------------------------------------------+ ``` -The body of instruction formats are divided into two sections: fields and -overlays. +-------------------------------------------------------------------------------- -### Fields +## 2. Quickstart: Your First `.bin_fmt` File -The fields section lists the fields of the format in order from msb to lsb. The -total width of the fields has to equal the declared width of the format. A field -is either a bit field definition or a reference to another format. A bit field -definition consists of an `unsigned` or `signed` specification, a name, and bit -width. A format reference consists of the keyword `format` followed by the -format name, and an optional size specification, which specifies how many times -that format is repeated. The fields section of the RiscV RV32G BType format -declaration shown previously is listed below: +Suppose we want to decode a tiny 32-bit RISC architecture (`MiniRisc`) with +three instructions: -``` - fields: - unsigned imm7[7]; - unsigned rs2[5]; - unsigned rs1[5]; - unsigned func3[3]; - unsigned imm5[5]; - unsigned opcode[7]; -``` +* `add rd, rs1, rs2` (R-type format) +* `addi rd, rs1, imm12` (I-type format, 12-bit signed immediate) +* `beq rs1, rs2, offset13` (B-type format, where a 13-bit signed PC-relative + branch offset has bits scattered across two fields and a constant `0` in + bit 0) -### Overlays +### Step 1: Write `mini_risc.bin_fmt` -An overlay is a named virtual field of the format that consists of a sequence of -field (or format) references and binary literals in order of concatenation from -left to right. Overlays are used when the value of a desired quantity from the -instruction word is not encoded directly in a field, but has to be assembled -from the fields or formats, or fragments of fields or formats, possibly with -binary literals added to the mix. Binary literals are expressed in the form -‘0b<binary digits>’, where the single quote can be used as a grouping -mechanism (e.g., `0b0100'1010`). The width of the literal is defined by the -number of binary digits following the ‘0b’ prefix. +```c +// mini_risc.bin_fmt -An overlay definition consists of an `unsigned` or `signed` specification, a -name, and bit width, (just like a field specification), but then followed by an -equal sign and a comma separated list of overlay components. Each overlay -component is one of: - -* A field or format name, which means the entire field/format is used. - * E.g., `imm5` -* A field or format name with a bit range, which selects only the specified - bits. - * E.g., `imm5[4..1]` -* A bit range on its own, which refers directly to the current format’s bits. - * E.g., `[11..8]` (which would refer to the same bits as `imm[4..1]`) -* A binary number literal which defines both the value and the width (number - of digits). - * E.g., `0b0100'1010` - -The overlay section of the RiscV RV32G BType format declaration is shown below: - -``` - overlays: - signed imm[13] = imm7[6], imm5[0], imm7[5..0], imm5[4..1], 0b0; -``` - -## Instruction Encodings - -The instruction encodings are grouped in one or more `instruction group` -definitions. Each such definition gives rise to a separate instruction decode -function in the generated code. The instructions in a single group are subject -to two constraints: they must all have the same width, and the instruction -formats used by the instructions must all derive from the same ancestor (as -specified in the group header). The user may otherwise freely select how to -group the instructions according to relevant ISA constraints, such as mode etc. - -## Header - -The header of the instruction group defines the name of the group, the width, -the opcode enum C++ type used for the opcodes and the base instruction format -all the grouped instructions’ formats must derive from. An example from RiscV 32 -is shown below: - -``` -instruction group RiscVInst32[32] : Inst32Format -``` - -This defines “RiscVInst32” as the name of an instruction group with 32 bit wide -instructions, using the base format "Inst32Format". All the instructions listed -within have to derive from "Inst32Format". - -## Instructions - -The instructions in an instruction group are listed sequentially in a semicolon -separated list. Each instruction is described by its name, the instruction -format used, and a comma separated list of value constraints on fields or -overlays in that instruction. - -As an example, consider the RiscV branch on equal “beq” instruction. This -instruction uses the BType format that was listed previously in the discussion -on instruction formats. - -``` -beq : BType : func3 == 0b000, opcode == 0b110'0011; -``` - -As can be seen, the value constraints are that the instruction field func3 has -to be equal to 0, and the opcode field has to have the value 0x63. Note, the -radix of the numeric literal in each constraint is not restricted to binary, but -can be any of binary, octal, hexadecimal or decimal. The choice is up to the -author in terms of what is most convenient. - -Another example using five instructions from the 16 bit RiscV instruction group -that all use format CR illustrates how not-equal constraints can also be used : - -``` -format CR[16] : Inst16Format { - fields: - unsigned func4[4]; - unsigned rs1[5]; - unsigned rs2[5]; - unsigned op[2]; +// 1. Define a common 32-bit base format for the instruction group. +format Inst32[32] { + fields: + unsigned upper[25]; + unsigned opcode[7]; }; -instructions Inst16[16] "isa::OpcodeEnum" : Inst16Format { - ... - cjr : CR : func4 == 0b1000, rs1 != 0, rs2 == 0, op == 0b10; - cmv : CR : func4 == 0b1000, rs1 != 0, rs2 != 0, op == 0b10; - cebreak : CR : func4 == 0b1001, rs1 == 0, rs2 == 0, op == 0b10; - cjalr : CR : func4 == 0b1001, rs1 != 0, rs2 == 0, op == 0b10; - cadd : CR : func4 == 0b1001, rs1 != 0, rs2 != 0, op == 0b10; - ... +// 2. Define concrete 32-bit formats that inherit from Inst32. +// Fields are listed from most-significant bit (bit 31) down to bit 0, +// and their widths must sum to 32. +format RType[32] : Inst32 { + fields: + unsigned funct7[7]; // bits [31..25] + unsigned rs2[5]; // bits [24..20] + unsigned rs1[5]; // bits [19..15] + unsigned funct3[3]; // bits [14..12] + unsigned rd[5]; // bits [11..7] + unsigned opcode[7]; // bits [6..0] +}; + +format IType[32] : Inst32 { + fields: + signed imm12[12]; // bits [31..20] (automatically sign-extended!) + unsigned rs1[5]; // bits [19..15] + unsigned funct3[3]; // bits [14..12] + unsigned rd[5]; // bits [11..7] + unsigned opcode[7]; // bits [6..0] +}; + +format BType[32] : Inst32 { + fields: + unsigned imm7[7]; // bits [31..25] + unsigned rs2[5]; // bits [24..20] + unsigned rs1[5]; // bits [19..15] + unsigned funct3[3]; // bits [14..12] + unsigned imm5[5]; // bits [11..7] + unsigned opcode[7]; // bits [6..0] + overlays: + // Reassemble the 13-bit signed branch offset from scattered bits + LSB 0: + signed b_imm[13] = imm7[6], imm5[0], imm7[5..0], imm5[4..1], 0b0; +}; + +// 3. Define the instruction encodings and field constraints. +instruction group MiniRisc32[32] : Inst32 { + add : RType : funct7 == 0b000'0000, funct3 == 0b000, opcode == 0b011'0011; + addi : IType : funct3 == 0b000, opcode == 0b001'0011; + beq : BType : funct3 == 0b000, opcode == 0b110'0011; +}; + +// 4. Configure the generated C++ binary decoder. +decoder MiniRiscBinDecoder { + namespace tutorial::mini_risc::encoding; + opcode_enum = "::tutorial::mini_risc::isa::OpcodeEnum"; + includes { + #include "mini_risc_enums.h" + } + MiniRisc32; }; ``` -## Decoder +### Step 2: Add the Bazel Build Rule (`BUILD`) -The decoder definition specifies properties for the generated binary instruction -decoder. Multiple decoders may be specified in a .bin\_fmt file, but only one -can be selected, by passing in a command line option to the parser tool, for -parsing and code generation. +Use `mpact_bin_fmt_decoder` (from `mpact_sim_isa.bzl`) alongside +`mpact_isa_decoder`: -The decoder definition specifies 4 pieces of information: namespace, the opcode -enumeration type to use, decoder specific include files, and the instruction -groups for which to generate decoders for. +```python +load( + "//third_party/mpact_sim/decoder:mpact_sim_isa.bzl", + "mpact_bin_fmt_decoder", + "mpact_isa_decoder", +) +# Note: In standalone Bazel / GitHub builds, load from: +# "@mpact-sim//mpact/sim/decoder:mpact_sim_isa.bzl" +mpact_isa_decoder( + name = "mini_risc_isa", + src = "mini_risc.isa", + includes = [], + isa_name = "MiniRisc", + prefix = "mini_risc", +) + +mpact_bin_fmt_decoder( + name = "mini_risc_bin_fmt", + src = "mini_risc.bin_fmt", + decoder_name = "MiniRiscBinDecoder", + includes = [], + prefix = "mini_risc", + deps = [":mini_risc_isa"], +) ``` + +### Step 3: Use the Generated Functions in C++ + +Building `:mini_risc_bin_fmt` generates `mini_risc_bin_decoder.h` (plus `.cc`, +`_bin_encoder.{h,cc}`, and `_bin_types.h`). In your C++ encoding class, you can +immediately decode words and extract bitfields without writing a single +bit-shift by hand: + +```cpp +#include "mini_risc_bin_decoder.h" +#include "mini_risc_enums.h" + +void ParseInstruction(uint32_t inst_word) { + using ::tutorial::mini_risc::isa::OpcodeEnum; + namespace enc = ::tutorial::mini_risc::encoding; + + // Decode 32-bit word into OpcodeEnum::kAdd, kAddi, kBeq, or kNone: + OpcodeEnum op = enc::DecodeMiniRisc32(inst_word); + + // Extract bitfields and overlays (signed fields/overlays are sign-extended!): + uint8_t rd = enc::r_type::ExtractRd(inst_word); + int16_t simm12 = enc::i_type::ExtractImm12(inst_word); + int16_t branch_offset = enc::b_type::ExtractBImm(inst_word); +} +``` + +-------------------------------------------------------------------------------- + +## 3. File Structure, Comments, and Modularity + +### Comments and Numeric Literals + +`.bin_fmt` files support standard C/C++ comments and four integer radixes: + +* **Comments**: Single-line `// ...` and block `/* ... */` comments. +* **Numbers**: + * Binary: `0b1100011` or `0b110'0011` + * Hexadecimal: `0x7f` or `0xdead'beef` + * Octal: `077` + * Decimal: `0`, `32`, `1'024` + * Single quotes (`'`) may appear anywhere after the first digit as visual + digit separators. + +### Splitting Descriptions Across Files (`#include` and `#once`) + +Large architectures (for example, RISC-V RV32G with I, M, A, F, D, C, and Vector +extensions) can split formats and instruction groups across multiple `.bin_fmt` +files: + +* Place `#once` at the very top of a shared `.bin_fmt` file (before any + declarations) so that including it from multiple files only processes its + contents once. +* Use `#include "path/to/other.bin_fmt"` at top level to import formats, + instruction groups, or decoders from another file. +* Remember to list all included `.bin_fmt` files in the `includes = [...]` + attribute of `mpact_bin_fmt_decoder` in your `BUILD` file so Bazel makes + them available in the build action. + +```c +// rv_base_formats.bin_fmt +#once + +format Inst32[32] { + fields: + unsigned payload[25]; + unsigned opcode[7]; +}; +``` + +```c +// rv_top.bin_fmt +#include "path/to/rv_base_formats.bin_fmt" +``` + +**Important distinction**: Top-level `#include "foo.bin_fmt"` imports another +binary format file during `bin_format_gen` parsing. By contrast, +`#include "foo.h"` *inside* a `decoder { includes { ... } }` block emits a C++ +`#include` directive into the generated `.h` file. + +-------------------------------------------------------------------------------- + +## 4. Defining Formats (`format`) + +A `format` specifies how the bits of an instruction word, slot, or VLIW bundle +are partitioned. + +### Syntax + +```c +format FormatName[width] : BaseFormat { + layout: default; // Optional: 'default' or 'packed_struct' + fields: + // Signed/unsigned bitfields and sub-formats, from MSB to LSB + overlays: // Optional section + // Virtual bitfields assembled from slices and binary literals +}; +``` + +*(The trailing `;` after `}` is optional.)* + +### Bit Numbering and Field Ordering + +Understanding bit order in `BinFormat` prevents off-by-one bugs: + +1. **Declaration order is MSB to LSB (left to right)**: The first field + declared in `fields:` occupies the highest-numbered (most-significant) bits + of the format; the last field declared occupies the lowest-numbered bits + ending at bit `0`. +2. **Bit `0` is always the LSB**: Within any `W`-bit format, field, or + sub-format, the most-significant bit is bit `W - 1` and the + least-significant bit is bit `0`. +3. **Exact width sum**: The widths of all entries in `fields:` **must sum + exactly** to the width of the format. Every bit in the format must be + accounted for—name unused bits `reserved` or `unused` rather than omitting + them. + +For example, in a 16-bit format: + +```c +format CR[16] { + fields: + unsigned func4[4]; // bits [15..12] + unsigned rs1[5]; // bits [11..7] + unsigned rs2[5]; // bits [6..2] + unsigned op[2]; // bits [1..0] +}; +// Total width = 4 + 5 + 5 + 2 = 16 bits. +``` + +### Bitfields (`signed` and `unsigned`) + +A scalar bitfield has the form: + +```c +signed field_name[width]; +unsigned field_name[width]; +``` + +*(An optional `= default_number` suffix such as `unsigned zero[3] = 0;` is also +accepted by the grammar for documentation/defaulting, though encoding +constraints are specified in `instruction group` definitions.)* + +* **`unsigned`**: The generated `Extract<Field>()` function shifts and masks + the field and returns an unsigned C++ integer (`uint8_t`, `uint16_t`, + `uint32_t`, or `uint64_t`). +* **`signed`**: The generated `Extract<Field>()` function shifts, masks, and + **sign-extends** the `width`-bit two's-complement value into a signed C++ + integer (`int8_t`, `int16_t`, `int32_t`, or `int64_t`). +* Scalar fields that require generated extractors must be at most **64 bits** + wide. (Unreferenced padding fields in wide formats may exceed 64 bits as + long as no extractor is needed, though splitting into `<= 64`-bit chunks is + good practice.) + +### Sub-Formats and Replicated Slots (Format Hierarchies) + +Instead of `signed`/`unsigned`, a field entry can embed another `format`, +optionally repeated `[count]` times: + +```c +format SubFormatName instance_name; +format SubFormatName instance_name[count]; +``` + +This is especially useful for **VLIW bundles** that pack multiple instruction +slots into a wide bundle word: + +```c +format SlotA[42] { + fields: + unsigned payload[42]; +}; + +format SlotB[26] { + fields: + unsigned payload[26]; +}; + +// A 128-bit VLIW bundle: [127..126]=mode, [125..42]=2x SlotA, [41..16]=SlotB, [15..0]=const +format VliwBundle128[128] { + fields: + unsigned mode[2]; + format SlotA slot_a[2]; // slot_a[0] is [125..84], slot_a[1] is [83..42] + format SlotB slot_b; // [41..16] + unsigned imm_pool[16]; // [15..0] +}; +``` + +For `format SlotA slot_a[2];`: + +* Instances are placed left-to-right from MSB to LSB: `index = 0` is the + highest bit range (`[125..84]`) and `index = 1` is the next range + (`[83..42]`). +* `bin_format_gen` generates an indexed extractor + `ExtractSlotA(bundle_val, int index)` and an indexed inserter + `InsertSlotA(int index, slot_val, bundle_val)`. +* Directly extracted sub-formats can be up to **128 bits** wide. + +### Format Inheritance (`: BaseFormat`) + +A format can inherit from another format: + +```c +format Base32[32] { + fields: + unsigned body[25]; + unsigned opcode[7]; +}; + +// Width '[32]' is optional when inheriting; if omitted, Base32's width (32) is used. +format DerivedR : Base32 { + fields: + unsigned funct7[7]; + unsigned rs2[5]; + unsigned rs1[5]; + unsigned funct3[3]; + unsigned rd[5]; + unsigned opcode[7]; +}; +``` + +What format inheritance does: + +1. **Width inheritance & checking**: If `[width]` is omitted on the child + format, it inherits the parent format's bit width. If `[width]` is specified + on both, `bin_format_gen` verifies that they match. +2. **Instruction group membership**: Every `instruction group` specifies a base + format (`instruction group Name[width] : BaseFormat`). Only formats equal to + `BaseFormat` or transitively derived from `BaseFormat` may be used in that + group. +3. **Extractor promotion**: Non-conflicting field and overlay extractors + defined in child formats are automatically promoted into their ancestor + format's namespace as convenience wrappers (provided no sibling/ancestor + defines a conflicting extractor with the same name at a different bit + position/type). + +**Note**: Format inheritance does *not* concatenate fields—each derived format +still declares all of its bits summing to the full format width. + +### Supported Format Widths and C++ Representation Types + +`bin_format_gen` supports formats of **any positive bit width**, mapping them to +C++ types as follows: + +| Format Bit Width | Generated C++ Input / | Notes | +: : Return Type : : +| :--------------------- | :----------------------- | :------------------- | +| `1 .. 8` | `uint8_t` (or `int8_t` | Standard integer | +: : if signed) : shifts/masks : +| `9 .. 16` | `uint16_t` (or `int16_t` | Standard integer | +: : if signed) : shifts/masks : +| `17 .. 32` | `uint32_t` (or `int32_t` | Standard integer | +: : if signed) : shifts/masks : +| `33 .. 64` | `uint64_t` (or `int64_t` | Standard integer | +: : if signed) : shifts/masks : +| `65 .. 128` | `absl::uint128` | Uses 128-bit | +: : : shifts/masks : +| `> 128` (e.g., 256-bit | `const uint8_t*` / | Byte-pointer buffer | +: VLIW) : `uint8_t*` : extractors/inserters : + +Additionally, if a format is `<= 128` bits wide and its **bit width** is **not** +a power of two (for example, a 12-bit, 24-bit, or 42-bit format), +`bin_format_gen` generates **both** integer-typed extractors (`uint16_t` / +`uint32_t` / `uint64_t` / `absl::uint128`) and `const uint8_t*` byte-buffer +overloads for convenience. + +### Packed C++ Bitfield Structs (`layout: packed_struct;`) + +By default (`layout: default;`), formats generate shift-and-mask functions. If +you also want a C++ packed bitfield struct and union for inspecting raw words, +add `layout: packed_struct;` at the top of the format: + +```c +format RType[32] : Inst32 { + layout: packed_struct; + fields: + unsigned funct7[7]; + unsigned rs2[5]; + unsigned rs1[5]; + unsigned funct3[3]; + unsigned rd[5]; + unsigned opcode[7]; +}; +``` + +In `<prefix>_bin_types.h`, `bin_format_gen` emits `PackedRType` (emitting C++ +bitfields from LSB to MSB so bit `0` matches little-endian C++ bitfield layout) +and `UnionRType` (`union { PackedRType r_type; uint8_t bytes[4]; }`). +`packed_struct` requires all fields and sub-formats to be `<= 64` bits and does +not allow replicated sub-format arrays (`format Sub s[2]`). + +-------------------------------------------------------------------------------- + +## 5. Defining Overlays (`overlays:`) + +Many ISAs scatter immediate or register bits across non-adjacent positions in +the instruction word or append implicit low-order zero bits (for example, 2-byte +or 4-byte aligned branch targets). **Overlays** let you define virtual `signed` +or `unsigned` fields (up to 64 bits wide) by concatenating pieces from MSB +(left) to LSB (right): + +```c +overlays: + signed name[width] = component_1, component_2, ...; + unsigned name[width] = component_1, component_2, ...; +``` + +### The Four Overlay Component Types + +Each comma-separated component in an overlay can be: + +1. **An entire named field**: `imm5` Uses all bits of `imm5` (where `imm5` is + declared as a `signed` or `unsigned` field in `fields:`). +2. **Bit slices of a named field**: `imm7[6]` or `imm7[5..0, 6]` Bit indices + are relative to `imm7` itself (`0` is `imm7`'s LSB). +3. **Bit slices directly from the enclosing format**: `[31, 7, 30..25, 11..8]` + Bit indices are relative to the full format (`0` is the format's LSB). Use + format-relative bit slices whenever an overlay needs bits belonging to a + nested `format` sub-format, since sub-format aliases cannot be referenced by + name in overlays. +4. **A binary literal**: `0b0` or `0b0100'1010` Appends constant bits. The bit + width of the literal is the exact number of `0`/`1` digits after `0b` + (ignoring `'` separators)—for example, `0b0` is 1 bit wide and `0b0000` is 4 + bits wide. + +The sum of the bit widths of all components **must equal** the declared +`[width]` of the overlay. Bit ranges (`hi..lo`) must be written in descending +MSB-to-LSB order (`hi >= lo`, such as `5..0`; ascending ranges like `0..5` are +rejected) or as single-bit indices, and multiple slices can be combined in a +comma-separated bracket list (`imm[7..4, 1, 0]`). + +### Overlay Examples + +```c +format JType[32] : Inst32 { + fields: + unsigned imm20[20]; // format bits [31..12] + unsigned rd[5]; // format bits [11..7] + unsigned opcode[7]; // format bits [6..0] + overlays: + // RISC-V J-type 21-bit signed jump offset: + // imm[20 | 10:1 | 11 | 19:12] << 1, referenced via format bit numbers: + signed j_imm[21] = [31, 19..12, 20, 30..21], 0b0; + + // Zero-extended 6-bit stack-pointer immediate scaled by 16 (low 4 bits 0): + unsigned scaled_uimm[9] = imm20[4..0], 0b0000; +}; +``` + +Overlays can be used **both**: + +* Through generated `Extract<OverlayName>()` / `Insert<OverlayName>()` + functions in C++, **and** +* Directly inside `instruction group` encoding constraints (e.g., + `nzimm != 0`). + +-------------------------------------------------------------------------------- + +## 6. Instruction Groups and Instruction Encodings (`instruction group`) + +While `format` blocks describe *how bits are named*, `instruction group` blocks +describe *which bit values identify each instruction*. + +### Single Instruction Group + +```c +instruction group GroupName[width] : BaseFormat { + // instruction encodings... +}; +``` + +Rules for a single instruction group: + +* **`[width]`**: Every instruction in the group has this exact bit width (**up + to 64 bits**). If your ISA has both 16-bit compressed instructions and + 32-bit standard instructions (like RISC-V C + G), place the 16-bit + instructions in a `[16]` group and the 32-bit instructions in a `[32]` + group. (For VLIW bundles wider than 64 bits, define a bundle `format` for + the full bundle width and define separate `instruction group`s for each + `<= 64`-bit instruction slot format!) +* **`: BaseFormat`**: Every instruction encoding in the group must reference + either `BaseFormat` itself or a format that inherits (directly or + indirectly) from `BaseFormat`, and `BaseFormat`'s width must equal + `[width]`. + +### Standard Instruction Encoding and Constraints + +```c +opcode_name : FormatName : constraint_1, constraint_2, ...; +``` + +* **`opcode_name`**: Must match the opcode name in your `.isa` file. + `bin_format_gen` converts `snake_case` names to `PascalCase` prefixed with + `k` when returning `OpcodeEnum` values (for example, `c_add` becomes + `OpcodeEnum::kCAdd`, and `addi` becomes `OpcodeEnum::kAddi`). +* **`FormatName`**: The specific format used to interpret field and overlay + names in the constraint list. +* **Constraints**: Comma-separated comparisons on fields or overlays of + `FormatName`. + +#### Supported Constraint Operators + +| Operator | Meaning | Allowed RHS | Notes | +| :-------------- | :--------------- | :----------------- | :---------------- | +| `==` | Equal to | Numeric literal or | Supported for | +: : : field/overlay name : `signed` and : +: : : : `unsigned`. : +: : : : Constant `==` : +: : : : constraints : +: : : : without : +: : : : literal-bit : +: : : : overlays drive : +: : : : fast lookup-table : +: : : : generation. : +| `!=` | Not equal to | Numeric literal or | Supported for | +: : : field/overlay name : `signed` and : +: : : : `unsigned` (e.g., : +: : : : `rs1 != 0`, `rs1 : +: : : : != rs2`). : +| `>`, `>=`, `<`, | Relational range | Numeric literal or | Supported for | +: `<=` : check : field/overlay name : **`unsigned`** : +: : : : fields and : +: : : : overlays (e.g., : +: : : : `rlist > 3`, : +: : : : `shamt < 32`). : + +Examples of constraints: + +```c +instruction group Inst16[16] : Inst16Base { + // Constant equality and non-zero register checks: + c_jr : CR : func4 == 0b1000, rs1 != 0, rs2 == 0, op == 0b10; + c_mv : CR : func4 == 0b1000, rs1 != 0, rs2 != 0, op == 0b10; + c_ebreak : CR : func4 == 0b1001, rs1 == 0, rs2 == 0, op == 0b10; + + // Unsigned range check: + cm_push : PType : func8 == 0b1011'1000, rlist > 3, op == 0b10; + + // Field-to-field comparison (e.g., two register fields must differ): + pair_op : CR : func4 == 0b1010, rs1 != rs2, op == 0b10; +}; +``` + +### Intentional Duplicate Opcode Encodings (`!`) + +Sometimes two distinct bit patterns or formats decode to the **exact same +logical opcode** in your `.isa` file. Normally, `bin_format_gen` warns if an +opcode name appears more than once in a group (to catch accidental copy-paste +mistakes). Prefix additional encodings with `!` to mark the duplicate opcode +name as intentional: + +```c +instruction group MyGroup[32] : Inst32 { + nop : IType : imm12 == 0, rs1 == 0, funct3 == 0, rd == 0, opcode == 0b001'0011; + !nop : RType : funct7 == 0, rs2 == 0, rs1 == 0, funct3 == 0, rd == 0, opcode == 0b011'0011; +}; +``` + +### Encoding Specializations (`specializes`) + +In many ISAs, a general instruction encoding has special-case encodings when +certain operand fields take specific values (for example, `addi x0, x0, 0` is +`nop`, or `jalr x0, rs1, 0` is `jr`). Instead of manually adding negated +constraints to the general instruction, you can declare that an instruction +**`specializes`** a parent instruction in the same group: + +```c +instruction group RiscV32I[32] : Inst32 { + addi : IType : funct3 == 0b000, opcode == 0b001'0011; + + // Inherits IType, funct3 == 0b000, and opcode == 0b001'0011 from 'addi', + // and is tested before falling back to 'addi': + nop : specializes addi : imm12 == 0, rs1 == 0, rd == 0; +}; +``` + +Rules for `specializes`: + +* `parent` must already be declared earlier in the same `instruction group`. +* The specialized instruction automatically inherits `parent`'s format and all + of `parent`'s constraints, then adds its own extra constraints. +* Every specialized variant under the same parent must still be mutually + distinguishable from its siblings. + +### Templated Instruction Generation (`GENERATE`) + +When an ISA has families of instructions with systematic names and opcode +numbers (for example, `add`, `sub`, `and`, `or`, `xor`, or width variants `_b`, +`_h`, `_w`), use `GENERATE(...)` to avoid repetitive boilerplate: + +```c +instruction group AluOps[32] : Inst32 { + // Tuple binding: 'mnem', 'f7', and 'f3' step together across the 4 tuples. + GENERATE([mnem, f7, f3] = [ + {add, 0b000'0000, 0b000}, + {sub, 0b010'0000, 0b000}, + {and, 0b000'0000, 0b111}, + {or, 0b000'0000, 0b110} + ]) { + $(mnem) : RType : funct7 == $(f7), funct3 == $(f3), opcode == 0b011'0011; + }; +}; +``` + +You can also specify **multiple comma-separated bindings** inside +`GENERATE(...)`. When multiple bindings are given, `bin_format_gen` expands +their **Cartesian product** (every combination of values): + +```c +instruction group LoadStoreOps[32] : Inst32 { + GENERATE( + [op_prefix, fmt, opc] = [{ld, IType, 0b000'0011}, {st, SType, 0b010'0011}], + [width_suffix, f3] = [{b, 0b000}, {h, 0b001}, {w, 0b010}] + ) { + // Expands to 2 x 3 = 6 encodings: ld_b, ld_h, ld_w, st_b, st_h, st_w + $(op_prefix)_$(width_suffix) : $(fmt) : funct3 == $(f3), opcode == $(opc); + }; +}; +``` + +Inside a `GENERATE` body, `$(var)` can appear in the opcode name, the format +name, the field/overlay name on the left of a constraint, or the value/field on +the right of a constraint. + +### Merging Instruction Groups + +Modular ISA descriptions often put each extension in its own `instruction group` +(for example, `RV32I`, `RV32M`, `RV32F`) and then merge them into a single +unified decode function. You can merge groups either at top level: + +```c +instruction group RV32IMF = { RV32I, RV32M, RV32F }; +``` + +or inline inside a `decoder` block (shown in the next section). All merged +groups must have the **same bit width** and the **same base format**. + +-------------------------------------------------------------------------------- + +## 7. Defining Decoders (`decoder`) + +A `decoder` block tells `bin_format_gen` what C++ code to generate: + +```c decoder RiscV32GV { namespace mpact::sim::riscv::encoding; - opcode_enum = "isa32v::OpcodeEnum"; + opcode_enum = "::mpact::sim::riscv::isa32v::OpcodeEnum"; + includes { - #include "some/include/file.h" + #include "riscv32gv_enums.h" } - // Combine instruction groups RiscV32 I, M and F. - RiscV32G = {RiscVIInst32, RiscVMInst32, RiscVFInst32}; - // Separate group for compact instructions. + + // Merge 32-bit extension groups into a single DecodeRiscV32G() function: + RiscV32G = { RiscVIInst32, RiscVMInst32, RiscVFInst32 }; + + // Emit a separate DecodeRiscVCInst16() function for 16-bit instructions: RiscVCInst16; }; ``` -### Namespace +### Decoder Attributes -The namespace property specifies the namespace in which the generated code will -be placed. +* **`namespace <ns>;`** *(required, at most one)*: The C++ namespace wrapping + all generated types, decoder functions, extractors, and encoders. +* **`opcode_enum = "<CppType>";`** *(required, at most one)*: The C++ + `OpcodeEnum` type returned by `Decode<Group>()`. When `.bin_fmt` and `.isa` + use different C++ namespaces, qualify the enum path relative to `namespace` + or from the global `::` root, and include the `*_enums.h` header in + `includes`. +* **`includes { #include "..." }`** *(optional, repeatable)*: Header files + emitted as `#include` lines at the top of `<prefix>_bin_decoder.h`. Always + include the `<prefix>_enums.h` header generated by `mpact_isa_decoder` so + `OpcodeEnum` is visible. +* **Group entries** *(at least one required)*: + * `GroupName;` — generates `Decode<GroupName>()` and + `Decode<GroupName>WithFormat()` for an existing `instruction group`. + * `CombinedName = { GroupA, GroupB, ... };` — merges multiple compatible + instruction groups into one combined decode table and generates + `Decode<CombinedName>()` and `Decode<CombinedName>WithFormat()`. -### Opcode Enumeration Type +Multiple `decoder` blocks may exist across `.bin_fmt` files (for example, +`RiscV32G` vs. `RiscV32GV`). Select which one to generate with +`decoder_name = "RiscV32GV"` in `mpact_bin_fmt_decoder` (or +`--decoder_name=RiscV32GV` on the `bin_format_gen` CLI). -The `opcode_enum` specifies the text string that references the opcode -enumeration type to use as the return value for the instruction decoder(s). +-------------------------------------------------------------------------------- -The binary instruction decoder generator is designed to work with the -representation independent decoder generator (go/mpact-sim-isa-decoder). As -such, it has to translate from the binary representation of instructions to the -opcode enumeration type defined in the generated files by that tool. In order -for this to work properly, the string literal has to specify the name of the -enumeration type as it needs to be used from within the namespaces (see the -detailed grammar rules), defined for the binary decoder generator. The name of -each instruction listed in the binary encoding description file must match the -name of an instruction in the representation independent decoder description -file for the enumeration type members to match up. +## 8. Generated Files and C++ API Reference -### Include Files +Given `prefix = "my_isa"` (or `src = "my_isa.bin_fmt"` with default prefix), +`mpact_bin_fmt_decoder` generates **five files** inside your declared +`namespace`: -Include files specific to this decoder may be specified here. They will be -copied to the generated code. +| Generated File | Contents | +| :---------------------- | :------------------------------------------------- | +| `my_isa_bin_types.h` | `enum class FormatEnum`, `kFormatNames[]`, and any | +: : `Packed<Format>` / `Union<Format>` structs for : +: : `layout\: packed_struct;` formats. : +| `my_isa_bin_decoder.h` | `Decode<Group>()` & `Decode<Group>WithFormat()` | +: : declarations, inline : +: : `<format_snake>\:\:Extract<Field>()` namespaces, : +: : and `class Extractors`. : +| `my_isa_bin_decoder.cc` | Multi-level lookup table and constraint-evaluation | +: : definitions for `Decode<Group>()`. : +| `my_isa_bin_encoder.h` | `struct Encoder` with inline `Insert<Field>()` | +: : bit-insertion helpers and `extern : +: : kOpcodeEncodings`. : +| `my_isa_bin_encoder.cc` | `kOpcodeEncodings` hash map mapping each | +: : `OpcodeEnum` to its `(fixed_bits_value, : +: : bit_width)` tuple. : -### Instruction Groups +### 1. Instruction Decode Functions (`*_bin_decoder.h`) -The remainder specifies the named instruction groups to generate decode -functions for. Multiple instruction groups can be combined into a single group -for purposes of generating only one decode function for their combined -instructions, as opposed to having separate functions for each one. Only -instruction groups that use the same format can be combined in this way. In the -example above, three instruction groups (integer, multiply/divide, and floating -point) are combined to generate a single decoder, while a separate decoder -function is generated for the compact, 16-bit instructions. - -# Generated C++ Header Code - -The binary decoder generator tool generates a set of functions in the namespace -defined in the description file (see detailed syntax). As mentioned previously, -a decode function is generated for each instruction group. The signature is - -``` -<enum type> Decode<group name>(<word type> inst_word); -``` - -Where <enum type> is the string literal in the instruction group definition, -<group name> is the name of the instruction group, and <word type> is the -smallest unsigned integer type that fits the width of the instruction. When -called, the function will return the enum member that matches the word passed in -as an argument, or the enum member kNone (always defined), if there is no match. - -The tool also generates extract functions for each field and overlay in the -formats that are defined in the description file. Each such extraction function -is defined within a nested namespace named after the format in which it is -defined. The extraction functions are defined as inline in the .h file to -improve performance without forcing every function to be included in the -executable, as many of these are not used by the decoder, but should be made -available to the user if desired. - -The return type is the smallest signed/unsigned (according to the field/overlay -definition) integer type that fits the width of the field/overlay. The argument -type is the smallest unsigned integer type that fits the format width. The -following example shows the RiscV BType format and the extraction functions +For each group (e.g., `MiniRisc32` of width 32), two top-level functions are generated: -<table> - <tr> - <td><code>format BType[32] : Inst32Format {</code> -<p> -<code> fields:</code> -<p> -<code> unsigned imm7[7];</code> -<p> -<code> unsigned rs2[5];</code> -<p> -<code> unsigned rs1[5];</code> -<p> -<code> unsigned func3[3];</code> -<p> -<code> unsigned imm5[5];</code> -<p> -<code> unsigned opcode[7];</code> -<p> -<code> overlays:</code> -<p> -<code> signed imm[13] = imm7[6], imm5[0], imm7[5..0], imm5[4..1], 0b0;</code> -<p> -<code>};</code> - </td> - </tr> - <tr> - <td><code>namespace BType {</code> -<p> -<code>inline uint8_t ExtractOpcode(uint32_t value) {</code> -<p> -<code> return value & 0x7f;</code> -<p> -<code>}</code> -<p> -<code>inline uint8_t ExtractImm7(uint32_t value) {</code> -<p> -<code> return (value >> 25) & 0x7f;</code> -<p> -<code>}</code> -<p> -<code>inline uint8_t ExtractRs1(uint32_t value) {</code> -<p> -<code> return (value >> 15) & 0x1f;</code> -<p> -<code>}</code> -<p> -<code>inline uint8_t ExtractImm5(uint32_t value) {</code> -<p> -<code> return (value >> 7) & 0x1f;</code> -<p> -<code>}</code> -<p> -<code>inline uint8_t ExtractRs2(uint32_t value) {</code> -<p> -<code> return (value >> 20) & 0x1f;</code> -<p> -<code>}</code> -<p> -<code>inline uint8_t ExtractFunc3(uint32_t value) {</code> -<p> -<code> return (value >> 12) & 0x7;</code> -<p> -<code>}</code> -<p> -<code>inline int16_t ExtractImm(uint32_t value) {</code> -<p> -<code> int16_t result;</code> -<p> -<code> result = (value & 0x80000000) >> 19;</code> -<p> -<code> result |= (value & 0x80) << 4;</code> -<p> -<code> result |= (value & 0x7e000000) >> 20;</code> -<p> -<code> result |= (value & 0xf00) >> 7;</code> -<p> -<code> result = result << 3;</code> -<p> -<code> result = result >> 3;</code> -<p> -<code> return result;</code> -<p> -<code>}</code> -<p> -<code>} // namespace BType</code> - </td> - </tr> -</table> +```cpp +// Returns the matching OpcodeEnum, or OpcodeEnum::kNone if no encoding matches: +OpcodeEnum DecodeMiniRisc32(uint32_t inst_word); -# Generating the Decoder Functions - -A decoder function is generated for each instruction group, returning the enum -member for one of the instructions, if there is a match with that instruction, -or kNone if there is not. - -## Algorithm - -A new algorithm was developed to generate the decoder for the instructions in an -instruction group. The goal of the decoder is to be correct and reasonably fast -and efficient, but does not attempt to be optimal. - -### Initialization - -In the first stage of the algorithm only the “equal to” constraints for each -encoding are considered. The algorithm computes the mask of bits that are -constrained equal for each instruction in the instruction group. This is called -the *constraint mask* of the instruction. - -### Creating Initial Encoding Groups - -In the second stage of the algorithm, an initial set of *encoding groups* are -formed. The algorithm is shown below. Initially, the set of encoding groups is -empty. For each instruction encoding, consider each encoding group in turn. If -the intersection of the constraint mask of the encoding group with the -constraint mask of the encoding is zero, that is, there is no overlap between -the constrained bits in the encoding with the constrained bits in the encoding -group, then go to the next encoding group. If the intersection is non-zero, -select that encoding group. - -If an encoding group was selected, add the current encoding to that group, and -update the encoding group’s constraint mask with a bitwise and of the -instruction encoding’s constraint mask. If no encoding group was selected, -create a new encoding group, setting the constraint mask of the encoding group -to that of the instruction encoding. At the end of this stage, each instruction -encoding has been assigned to an encoding group, and it is guaranteed that all -encoding groups have a non-zero constraint mask. The algorithm is shown in the -following figure. - +// Returns both the OpcodeEnum and the matched FormatEnum (e.g., FormatEnum::kRType), +// or {OpcodeEnum::kNone, FormatEnum::kNone} if no encoding matches: +std::pair<OpcodeEnum, FormatEnum> DecodeMiniRisc32WithFormat(uint32_t inst_word); ``` -for each instruction encoding enc { - inst_enc_group = nullptr; - for each encoding group grp { - if ((grp->constraint_mask & enc->constraint_mask) == 0) continue - inst_enc_group = grp - break + +### 2. Field, Sub-Format, and Overlay Extractors (`*_bin_decoder.h`) + +For every format (e.g., `BType`), extractors are available in **two equivalent +styles**: + +1. **Snake-case format namespace**: `b_type::ExtractImm7(inst_word)`, + `b_type::ExtractBImm(inst_word)`, plus bit-width constant + `b_type::kBTypeSize`. +2. **`Extractors` class scope**: `Extractors::BType::ExtractImm7(inst_word)`, + `Extractors::BType::ExtractBImm(inst_word)`. + +Additionally, if `BType` inherits from `Inst32`, non-conflicting extractors are +promoted to `inst32::ExtractBImm(inst_word)` / +`Extractors::Inst32::ExtractBImm(inst_word)` so you can extract common fields +without knowing which derived format was used. + +### 3. Bit Inserters and Opcode Encoding Map (`*_bin_encoder.h`) + +To support assemblers, binary encoders, and unit tests that construct machine +words programmatically, `*_bin_encoder.h` provides: + +* **`Encoder::<FormatPascal>::Insert<FieldOrOverlayOrSubFormat>(value, + inst_word)`** *(and `Insert<SubFormat>(int index, value, inst_word)` for + replicated sub-formats)*: Masks and shifts `value` into the target field, + sub-format, or overlay bits of `inst_word` and returns the updated word (or + writes into `uint8_t*` for `> 128`-bit formats). +* **`kOpcodeEncodings`**: An + `absl::NoDestructor<absl::flat_hash_map<OpcodeEnum, std::tuple<uint64_t, + int>>>` containing `(constant_equality_bits, bit_width)` for every decoded + opcode. Starting from `std::get<0>((*kOpcodeEncodings)[opcode])` and calling + `Insert<Field>()` lets you assemble complete binary instructions cleanly! + +-------------------------------------------------------------------------------- + +## 9. Under the Hood: How `bin_format_gen` Synthesizes Fast Decoders + +Knowing how `bin_format_gen` compiles an `instruction group` helps you write +efficient encodings and understand ambiguity diagnostics: + +1. **Constraint Masks**: First, `bin_format_gen` inspects `==` constant + constraints on fields and literal-free overlays to compute each + instruction's *constraint mask* (which bits have fixed constant values). +2. **Initial Encoding Groups**: Instructions whose constraint masks overlap are + clustered into initial *encoding groups*. If an instruction has *no* + constant `==` bits at all, or overlaps in incompatible ways, + `bin_format_gen` partitions accordingly. +3. **Recursive Discriminator Refinement**: Within each encoding group, + `bin_format_gen` computes: + * **Constant mask & value**: Bits constrained to the *exact same value* + across every instruction in the group (checked once on entry via + `(inst_word & mask) != value`). + * **Discriminator mask**: Bits constrained across all instructions in the + group that *differ* in value between instructions. When 2 or more + discriminator bits exist, `bin_format_gen` extracts those bits into a + compact index and dispatches through a `2^k` function-pointer table + (`parse_group_*`), marking checked bits in an *ignore mask* so child + levels never re-test them. +4. **Leaf Decode Functions**: + * **Simple leaves**: When a leaf group has no `!=` / `<` / `<=` / `>` / + `>=` constraints, no field-to-field comparisons, and no binary-literal + overlays, `bin_format_gen` emits a direct + `static OpcodeEnum opcodes[2^k]` array lookup with zero branches! + * **Constraint-checked leaves**: When relational constraints (`rs1 != 0`, + `rlist > 3`, `rs1 != rs2`) or specializations are present, the leaf + extracts the required fields once and emits targeted + `if (...) return OpcodeEnum::k...;` checks. + +-------------------------------------------------------------------------------- + +## 10. Best Practices from Production Simulators + +Production MPACT-Sim targets—such as **`mpact_riscv`** (RV32G/RV64G, Vector, +Bitmanip, Compressed `Zc*`, and the RVM23 profile), **`mpact_cheriot`** +(capability-extended RISC-V + RVV), and the **Coral NPU** simulator (RISC-V +scalar core + custom NPU vector extensions)—scale to hundreds of instructions +across many configurations by following a consistent set of modular design +patterns. + +### 1. Factor Shared Formats into Standalone `#once` Format Files + +As an architecture grows, putting `format` declarations in the same file as +instruction encodings quickly leads to either monolithic files or +duplicate-format collisions when combining extensions. + +Instead, **extract shared bit-level formats into dedicated format-only +`.bin_fmt` files guarded with `#once`**: + +* **`mpact_riscv`** places all 32-bit formats (`Inst32Format`, `RType`, + `IType`, `SType`, `BType`, `UType`, `JType`, `VMem`, `VArith`, `VConfig`, + etc.) in `riscv_format32.bin_fmt` and all 16-bit compressed formats + (`Inst16Format`, `CR`, `CI`, `CL`, `CS`, `CB`, `CJ`, `CMPP`, etc.) in + `riscv_format16.bin_fmt`, each starting with `#once`. +* **Coral NPU** similarly places all standard scalar formats and custom vector + formats (`CoralNPUSystemType`, `CoralNPUV2ArgsType`, `CoralNPUV3ArgsType`) + in `coralnpu_format.bin_fmt`. + +```c +// riscv_format32.bin_fmt +#once + +format Inst32Format[32] { + fields: + unsigned bits[25]; + unsigned opcode[7]; +}; + +format RType[32] : Inst32Format { + fields: + unsigned func7[7]; + unsigned rs2[5]; + unsigned rs1[5]; + unsigned func3[3]; + unsigned rd[5]; + unsigned opcode[7]; + overlays: + unsigned r_uimm5[5] = rs2; +}; +// ... IType, SType, BType, VMem, VArith, VConfig ... +``` + +Why this works so well: + +1. **Independent extension files**: Feature files like `riscv32g.bin_fmt`, + `riscv_vector.bin_fmt`, and `riscv_zc.bin_fmt` can each + `#include "riscv_format32.bin_fmt"` directly so they are self-contained, and + `#once` ensures the formats are parsed only once when those files are later + combined. +2. **Stable C++ extractor names**: Every simulator target built from those + formats shares identical C++ extractor namespaces (`r_type::ExtractRs1`, + `v_arith::ExtractVm`), allowing C++ operand getter libraries (`*_getters.h`) + to be reused across multiple simulator variants. + +### 2. Split Instruction Encodings by Extension or Functional Unit + +Rather than maintaining one giant `instruction group` for the entire ISA, +organize encodings into **modular per-extension or per-unit `.bin_fmt` files**, +each defining focused `instruction group` blocks: + +* **By ISA extension (`mpact_riscv` & `mpact_cheriot`)**: Separate files for + `riscv32g.bin_fmt`, `riscv32zb.bin_fmt`, `riscv_vector.bin_fmt`, + `riscv_zc.bin_fmt`, `riscv_zicond.bin_fmt`, `riscv_zicbom.bin_fmt`, or + `riscv_cheriot_f.bin_fmt` and `riscv_cheriot_vector.bin_fmt`. +* **By functional unit (Coral NPU)**: Separate files for + `coralnpu_base.bin_fmt`, `coralnpu_arith.bin_fmt`, `coralnpu_conv.bin_fmt`, + `coralnpu_memory.bin_fmt`, `coralnpu_mul.bin_fmt`, and + `coralnpu_shift.bin_fmt`. +* **Cross-width / cross-project sharing**: In `mpact_riscv`, + `riscv32zb.bin_fmt` puts bit-manipulation encodings shared between RV32 and + RV64 in `RiscVZbbInst32` and isolates 32-bit-only encodings (`rev8`, + `zext_h`) into `RiscVZbbInst32Only`. Not only do both RV32 and RV64 reuse + those groups, but the Coral NPU simulator also directly `#include`s + `mpact_riscv`'s `riscv32zb.bin_fmt` to add Zbb support without duplicating a + single line of encoding rules! + +### 3. Keep Top-Level Profile `.bin_fmt` Files as Thin Composition Wrappers + +Once formats and extensions are factored into modular files, a top-level +simulator profile `.bin_fmt` file (such as `rvm23.bin_fmt` or `riscv32v.bin_fmt` +in `mpact_riscv`, `riscv_cheriot_rvv.bin_fmt` in `mpact_cheriot`, or +`coralnpu.bin_fmt` in Coral NPU) becomes a clean, 30–60 line manifest that only: + +1. `#include`s the format and extension `.bin_fmt` files, and +2. Declares one or more `decoder` blocks that merge the desired + `instruction group`s by instruction width: + +```c +// rvm23.bin_fmt — Top-level profile composed from modular extension files +decoder RVM23 { + namespace mpact::sim::riscv::rvm23; + opcode_enum = "OpcodeEnum"; + includes { + #include "rvm23_enums.h" } - if (inst_enc_group != nullptr) { - Add enc to inst_enc_group - inst_enc_group->constraint_mask &= enc->constraint_mask - } else { - Create a new encoding group enc_group - Add enc to enc_group - enc_group->constraint_mask = enc->constraint_mask - } -} + + // Merge all 32-bit extension groups (sharing Inst32Format) into one decoder: + RVM23Inst32 = { + RiscVGInst32, + RiscVZbaInst32, RiscVZbbInst32, RiscVZbbInst32Only, + RiscVZbcInst32, RiscVZbsInst32, + RiscVZicond, RiscVZimop, RiscVZhintpause, RiscVZihintntl, + RiscVZicbop, RiscVZicbom, RiscVZicboz, + }; + + // Merge all 16-bit compressed groups (sharing Inst16Format) into a second decoder: + RVM23Inst16 = { + RiscVZcmop, RiscVCZihintntl, RiscVCZca, RiscVCZcf, + RiscVCZcb32, RiscVCZcmp, RiscVCZcmt, + }; +}; + +#include "riscv32g.bin_fmt" +#include "riscv32zb.bin_fmt" +#include "riscv_zc.bin_fmt" +#include "riscv_zhintpause.bin_fmt" +#include "riscv_zicbom.bin_fmt" +#include "riscv_zicbop.bin_fmt" +#include "riscv_zicboz.bin_fmt" +#include "riscv_zicond.bin_fmt" +#include "riscv_zihintntl.bin_fmt" +#include "riscv_zimop.bin_fmt" ``` -### Subdividing Encoding Groups +You can also place **multiple related `decoder` targets in the same wrapper +file**—for instance, `riscv_cheriot_rvv.bin_fmt` defines both +`decoder RiscVCheriotRVV` (integer RVV) and `decoder RiscVCheriotRVVFp` (adding +`RiscVFInst32` and `RiscVVFPInst32`)—and select each one in Bazel via +`decoder_name = "..."`. -Once the initial encoding groups have been formed each encoding group is -subdivided recursively into smaller encoding groups based on the “equal-to” -constraints for the instructions in the encoding group. +### 4. Decide Deliberately When to Merge Groups vs. Keep Separate Groups -Three quantities are computed for each encoding group. First, the *constant -mask*, the subset of the bits in the constraint mask that have the same -constraint value across all the instruction encodings in the encoding group. -Second, the *constant value*, which is the shared value of the bits in the -constant mask. Third, the *discriminator mask*, which is the bitset difference -between the constraint mask and the constant mask. A fourth quantity is used as -well, it is computed for subgroups when an encoding group is divided. This is -the *ignore mask*, which is the set of bits that have already been handled by an -encoding group higher in the hierarchy, and no longer need to be considered. For -instance, all 32 bit instructions in the RiscV32G ISA have 0b11 as the value of -the two lsbs. Only the top level decoder function needs to check the value of -these bits, any subsequent comparisons need consider at most the remaining 28 -bits. +Production simulators use two patterns for `instruction group`s in a `decoder`: -If the number of set bits in the discriminator is 0 an encoding group cannot be -subdivided, as there are no common bits by which to separate the instructions. -Otherwise an encoding group can be subdivided into 2^(1 << -popcount(discriminator)), where popcount(x) returns the number of set bits. For -instance, if a set of instruction encodings in a group have a constraint mask of -0x7f, a constant mask of 0x3, and thus a discriminator mask of 0x7c (the -discriminator mask has five bits sets), there can be a total of 32 (2^5) -subgroups created. In other words, the encodings in the encoding group can be -divided into 32 subgroups, and the subgroup for any instruction encoding can be -looked up by an index extracted from the bits in the instruction word that -correspond to the discriminator mask. +* **Merge compatible groups (`Combined32 = { GroupA, GroupB }`)** whenever + extensions share the same word width and encoding space (for example, all + 32-bit RISC-V extensions inheriting from `Inst32Format`). Merging generates + a **single** fast `DecodeCombined32(uint32_t)` lookup tree and automatically + verifies at build time that no two extensions accidentally collide in opcode + space. +* **Keep separate groups** when: + 1. **Instruction widths differ**: 16-bit compressed instructions + (`Inst16Format`) and 32-bit instructions (`Inst32Format`) cannot be + merged; the C++ fetch path checks the low size bits and dispatches to + `Decode...16(uint16_t)` or `Decode...32(uint32_t)`. + 2. **Major encoding spaces use distinct base formats**: For example, Coral + NPU V1 gives custom 2-operand and 3-operand vector encodings their own + root formats (`CoralNPUV2ArgsType`, `CoralNPUV3ArgsType`) separate from + `Inst32Format`, producing dedicated `DecodeCoralNPUVectorArithInst()` + functions called when custom vector opcodes are fetched. -Pseudo code for the algorithm is shown below. No subgroups are created that are -either size 0 or the size of the group itself. Moreover, no subgroups are -created if the discriminator mask has only one bit set. +### 5. Use Overlays to Avoid Format Proliferation -``` -Refine(EncodingGroup G) { - for (int i = 0; i < (1 << popcount(G->discriminator_mask()); i++) { - subgroup = new EncodingGroup - subgroup->SetIgnore(G->ignore_bits() | G->discriminator_mask() | - G->constant_mask()) - for each encoding enc in G { - if (discriminator_value(enc) != i) continue - subgroup->AddEncoding(enc) - } - if (subgroup->empty()) { - delete subgroup - continue - } - if (subgroup->size() == G.size()) { - delete subgroup - return - } - if (popcount(subgroup->discriminator()) >= 2) { - Refine(subgroup) - } - } -} +Before creating a new `format` for a minor encoding variation, check whether an +**overlay** on an existing format is cleaner: + +* **Signed vs. unsigned views of the same bits**: In `riscv_format32.bin_fmt`, + `IType` declares `signed imm12[12]` (for `addi`/`lw`) and adds + `overlays: unsigned u_imm12[12] = imm12;` (for unsigned CSR addresses in + `csrrw`) and `unsigned i_uimm5[5] = rs1;` (for CSR 5-bit immediates). +* **Multi-purpose vector formats**: `VArith` defines a single 32-bit field + layout and uses overlays (`uimm5`, `simm5`, `uimm6`, `func5`, `rd`, `rs1`) + for scalar/immediate vector variants instead of duplicating half a dozen + nearly identical vector formats. +* **Implicit register bank prefixes**: In `riscv_format16.bin_fmt`, 16-bit + compressed formats (`CL`, `CS`, `CIW`, `CA`, `CB`) map 3-bit compact + register fields (`0..7` -> `x8..x15`) directly in hardware encoding order + via `unsigned rs1[5] = 0b01, rs1p;`. + +### 6. Split Architectural Corner Cases in `.bin_fmt` Constraints + +Hardware architectures frequently attach special semantics when a register or +mode field is `0` or `1`. Rather than branching inside C++ semantic functions on +every execution, `mpact_riscv`, `mpact_cheriot`, and Coral NPU split these cases +at decode time using field constraints: + +* **Hardwired-zero register destinations (`rd == 0`)**: Separate `jal` + (`rd != 0`) from `j` (`rd == 0`), `addi` (`rd != 0`) from `nop` + (`rd == 0, rs1 == 0, imm12 == 0`), and `rd == 0` architectural hints into a + dedicated `RiscVIHints32` group. +* **CSR read/write side effects**: Split `csrrs` into `csrrs` + (`rs1 != 0, rd != 0`), `csrrs_nr` (`rd == 0`, skips CSR read side effects), + and `csrrs_nw` (`rs1 == 0`, skips CSR write attempts so reading a read-only + CSR does not trap). +* **Predicated vs. unpredicated vector ops**: Split `vle8` (`vm == 0`, masked) + and `vle8_vm1` (`vm == 1`, unmasked) so unmasked vector instructions avoid + runtime mask overhead. + +### 7. Track Transitive `.bin_fmt` Includes in `BUILD` Files + +Because Bazel executes `bin_format_gen` in a hermetic action sandbox, +`includes = [...]` on `mpact_bin_fmt_decoder` must list **every** transitively +`#include`d `.bin_fmt` file—including shared format files like +`riscv_format32.bin_fmt` and `riscv_format16.bin_fmt`: + +```python +mpact_bin_fmt_decoder( + name = "riscv32gv_bin_fmt", + src = "riscv32v.bin_fmt", + decoder_name = "RiscV32GV", + includes = [ + "riscv32g.bin_fmt", + "riscv32zb.bin_fmt", + "riscv_format16.bin_fmt", + "riscv_format32.bin_fmt", + "riscv_vector.bin_fmt", + ], + prefix = "riscv32gv", + deps = [":riscv32gv_isa"], +) ``` -There is a property of encoding groups that is worth noting. If an encoding -group has no subgroups, and there are no instruction encodings in the group that -have not-equal constraints, and there are no equal constraints that involve -overlays with bit constants, then that encoding group is considered to be -*simple*. Instructions in a simple encoding group can have their opcode -determined using a lookup table without any explicit comparisons. +-------------------------------------------------------------------------------- -### Generating Code +## 11. Common Pitfalls and Troubleshooting Checklist -The code generation process is the same for each instruction group listed in the -decoder definition. In addition to the top level decode function for the -instruction group, a separate decode function is generated for each encoding -group that will either directly return an opcode, or call the decode function -for a subgroup. The top level decoder function contains the code to call the top -level encoding groups’ decode function one after the other until one returns a -valid opcode value (not equal to `kNone`). If no valid opcode is found, `kNone` -is returned. If there is only a single top level encoding group the function is -still emitted as described. A future optimization would be to inline the next -level decode function directly instead. Below is the top level decode function -generated for RiscV32G `Inst32` instruction group: +* **"Format width mismatch" / fields don't add up**: Double-check that the sum + of all widths in `fields:` equals `[width]` in `format Name[width]`, and + that the sum of all components in each `overlay` equals `[width]` on that + overlay. Don't forget that `0b0` is 1 bit while `0b00` is 2 bits! +* **Reversed bit layout**: Remember that the **first** field in `fields:` is + the **most-significant bits** (highest bit numbers), and the **last** field + ends at **bit 0 (LSB)**—matching how instruction formats are drawn + left-to-right in ISA manuals (such as RISC-V and Arm). +* **Overlapping / ambiguous encodings error**: If two instructions in the same + group have identical `==` bits and neither `!=`/relational constraints nor + `specializes` distinguishes them, `bin_format_gen` reports an encoding + conflict. If one encoding is a special case of another (such as `nop` vs. + `addi`), use `nop : specializes addi : ...;`. If two distinct bit patterns + intentionally map to the same opcode, prefix the second with `!`. +* **Opcode enum compile error in generated `*_bin_decoder.h`**: Ensure every + instruction name in `.bin_fmt` exists in the `.isa` file (same spelling; + `snake_case` maps to `kPascalCase`), `opcode_enum` in `decoder { ... }` + points to the C++ `OpcodeEnum` namespace from `.isa`, and + `includes { #include "<prefix>_enums.h" }` is present in `decoder { ... }`. +* **VLIW bundle wider than 64 bits**: Do **not** create an `instruction group` + with `[width]` > 64. Instead, define a `format Bundle[128]` (or `[256]`) + containing sub-formats for each slot (`format AluSlot alu[2];`), and define + separate `instruction group AluGroup[42] : AluSlot { ... };` blocks for each + slot! -``` -isa::OpcodeEnum DecodeRiscVInst32(uint32_t inst_word) { - isa::OpcodeEnum opcode; - opcode = DecodeRiscVInst32_0(inst_word); - if (opcode != isa::OpcodeEnum::kNone) return opcode; - return opcode; -} -``` +-------------------------------------------------------------------------------- -The decode functions for every encoding group follow the same pattern. First if -there is a non-zero constant\_mask for the encoding group the mask is applied to -the instruction word and the value is compared to the constant\_value. If the -values are not equal, the decode function returns `kNop`. If the encoding group -has subgroups, then the index value corresponding to the discriminator\_mask is -computed and used to select and call the function pointer for the next level -decode function, returning its return value. The RiscV32G 0 level decode -function is shown below: +## 12. Grammar Reference -``` -isa::OpcodeEnum DecodeRiscVInst32_0(uint32_t inst_word) { - if ((inst_word & 0x3) != 0x3) return isa::OpcodeEnum::kNone; - uint32_t index; - index = (inst_word >> 2) & 0x1f; - return parse_group_RiscVInst32_0[index](inst_word); -} -``` - -The `parse_group_*` arrays are defined in the `.cc` file, and initialized with -the appropriate function pointers for the different encoding groups. - -For leaf encoding groups that are simple, the decode function is almost -identical to the above function, except that the index is used to select from an -opcode array, defined static constexpr local to the decode function. The -following shows such a function for RiscV32 32 bit store instructions: - -``` -isa::OpcodeEnum DecodeRiscVInst32_0_8(uint32_t inst_word) { - static isa::OpcodeEnum opcodes[4] = { - isa::OpcodeEnum::kSb, - isa::OpcodeEnum::kSh, - isa::OpcodeEnum::kSw, - isa::OpcodeEnum::kNone, - }; - if ((inst_word & 0x4000) != 0x0) return isa::OpcodeEnum::kNone; - uint32_t index; - index = (inst_word >> 12) & 0x3; - return opcodes[index]; -} -``` - -For non-simple leaf decode functions, the code starts with field extractions -required for the constraints testing, then each opcode is considered in turn, as -shown below. - -``` -isa::OpcodeEnum DecodeRiscVInst16_0_12(uint16_t inst_word) { - uint16_t index; - index = (inst_word >> 12) & 0x1; - uint16_t rs1_value = (inst_word >> 7) & 0x1f; - uint16_t rs2_value = (inst_word >> 2) & 0x1f; - if ((index == 0x0) && (rs1_value != 0x0) && (rs2_value != 0x0)) - return isa::OpcodeEnum::kCmv; - if ((index == 0x0) && (rs2_value == 0x0) && (rs1_value != 0x0)) - return isa::OpcodeEnum::kCjr; - if ((index == 0x1) && (rs1_value == 0x0) && (rs2_value == 0x0)) - return isa::OpcodeEnum::kCebreak; - if ((index == 0x1) && (rs1_value != 0x0) && (rs2_value != 0x0)) - return isa::OpcodeEnum::kCadd; - if ((index == 0x1) && (rs2_value == 0x0) && (rs1_value != 0x0)) - return isa::OpcodeEnum::kCjalr; - return isa::OpcodeEnum::kNone; -} -``` - -# Detailed Syntax of the .bin File - -The full [Antlr4](https://www.antlr.org) grammar of the .isa file is found in -the file `BinFormat.g4)`. +The complete ANTLR4 grammar for `.bin_fmt` files is located in `BinFormat.g4` in +the `decoder/` directory.
diff --git a/mpact/sim/decoder/doc/instruction-set.md b/mpact/sim/decoder/doc/instruction-set.md index c3ab675..d936fab 100644 --- a/mpact/sim/decoder/doc/instruction-set.md +++ b/mpact/sim/decoder/doc/instruction-set.md
@@ -1,467 +1,1022 @@ -# MPACT-Sim Representation Independent Decoder Generator +# Writing ISA Descriptions in MPACT-Sim (`.isa`) -Last updated 11/28/22 +This guide explains how to write **instruction set architecture (ISA) +description files** (`.isa`) in MPACT-Sim using the `InstructionSet.g4` grammar +and the `decoder_gen` code generator. It is written for developers who are new +to MPACT-Sim and want to model a scalar processor, a multi-extension RISC/CISC +architecture, or a multi-slot VLIW machine. -# Goals +For the companion guide on describing raw bitfields, overlays, and binary opcode +constraints, see [binary-encoding.md](binary-encoding.md). -* Define a separation of instruction decoding into two parts. One, fully - independent of the actual instruction encoding and formatting, that - manipulates the simulator internal instruction representation. The other - tasked with extracting information from the actual encoding format. -* Provide a convenient format for describing the structure of the target - architecture ISA in terms of instruction bundles and slots, where bundles - are groups of instruction slots that are issued together. -* Provide a convenient format for describing the set of instructions (opcodes) - that may be issued in each slot. -* Provide a convenient format for describing each instruction, its predicate, - source and destination operands, the semantic function that implements its - instruction semantics, and its optional disassembly format, without - requiring description or knowledge of the underlying instruction encoding - format. -* Generate C++ source code that implements the representation independent part - of the decoder and the interface that the encoding specific part of the - decoder must implement. +-------------------------------------------------------------------------------- -# Decoding Instructions +## 1. Big Picture: Representation-Independent Decoding in MPACT-Sim -MPACT-Sim uses instances of the Instruction class to represent individual target -architecture instructions. The Instruction class instance contains several key -items. Most importantly it stores the c++ callable for the C++ function (or -method, lambda, or other function object) that implements the semantics of an -instruction, i.e., reads operands, computes result(s), and writes to one or more -of the destination operands. It also includes pointers to source and destination -operand interfaces, through which the source and destination operand values are -read and written. These Instruction class instances are cached in a translation -cache, and reused when the same instruction is re-executed. The caching allows -the simulator to amortize the cost of decoding an instruction across many -executions. +At runtime, MPACT-Sim represents every decoded target instruction as an +`mpact::sim::generic::Instruction` object. An `Instruction` bundles together +everything the simulator needs to execute and inspect that instruction: -The decoding of a target instruction extracts information from the instruction -encoding to populate fields in the Instruction class instance. Writing this code -by hand is tedious and repetitive. Similar code with slight variations has to be -written for each of the hundred(s) of instructions in typical ISAs. The textual -representation of the C++ code is also a far cry from how the instruction -information is represented in most ISA manuals. This tends to make this code bug -prone, whether it is from mistranslating the information from ISA manuals -(extracting bit-fields for instance), or faulty copy-paste-modify on the many -repeated sequences of code. These bugs are typically tedious to debug, as their -side-effects often manifest themselves as simulated code not executing quite -right, e.g., wrong branch offset, or the wrong branch instruction executes. +* **Semantic function** (`void(Instruction*)`): The C++ callable that reads + source operands, computes results, and writes destination operands. +* **Predicate operand** *(optional)*: A boolean-like operand checked before + executing a predicated instruction. +* **Source operands**: Interfaces (`SourceOperandInterface*`) for reading + registers or immediate constants. +* **Destination operands**: Interfaces (`DestinationOperandInterface*`) for + writing registers or architectural state (such as `next_pc`) with a + specified cycle **latency**. +* **Child instructions** *(optional)*: Linked `Instruction` instances for + multi-phase operations (such as a memory load split into address issue and + register writeback). +* **Metadata**: Instruction address, byte size, formatted disassembly string, + integer attributes, and hardware pipeline resource operands. -A hand written decoder is typically inextricably coupled to the instruction -representation, such as your standard binary instruction encoding. That makes it -more costly to repurpose the simulator to read instructions in different -formats, e.g., textual assembly. +Once decoded, `Instruction` objects are stored in a decode cache so repeated +executions (such as inside loops) skip decoding entirely. -When using a simulator to perform architectural experiments it is desirable to -have a flexible encoding scheme. Often an existing encoding scheme may not have -room for all the architectural variations that need to be explored. A simple -experiment to measure the effect of doubling the number of registers becomes -difficult, as it would likely require a redesign and/or widening of the -instruction encoding. Decoupling parts of the decoder from the instruction -representation makes it easier and cheaper in terms of engineering resources to -use the simulator for architectural exploration. +### Why `.isa` Files Are Separate from `.bin_fmt` Files -## Representation Independent vs Dependent Decoding +Instead of hardcoding bit shifts inside the decoder that builds `Instruction` +objects, MPACT-Sim splits decoding into two layers: -The instruction instance needs the following information in order to simulate an -instruction: +1. **The Representation-Independent ISA Decoder (`.isa` -> `decoder_gen`)**: + Knows *every opcode in your ISA*, which slots/bundles it can issue from, + what operands and latencies it has, which C++ semantic function implements + it, and how to format its disassembly. It knows **nothing** about bit + positions, protobufs, or text assembly. Instead, `decoder_gen` generates an + abstract C++ interface class named `<IsaName>EncodingBase` with virtual + methods like `GetOpcode()`, `GetSource()`, and `GetDestination()`. +2. **The Encoding Layer (`.bin_fmt` -> `bin_format_gen`, or `.proto_fmt`, + etc.)**: Extracts opcodes and bitfields from raw machine words (see + [binary-encoding.md](binary-encoding.md)). You write a small C++ class + inheriting from `<IsaName>EncodingBase` that calls the `.bin_fmt` + decode/extract functions to return `OpcodeEnum` and operand pointers. -* Semantic function - a C callable that implements the instruction semantics. -* Predicate operand (optional), used to determine if the instruction should - execute or not. -* Source operand interfaces used by the semantic function to read instruction - sources. -* Destination operand interfaces used by the semantic function to write the - results of the instruction execution. -* Instruction size. -* Instruction address. +This separation makes it easy to experiment with new instructions, widen +register files during architectural exploration, or drive the exact same ISA +semantics from binary machine code, protobuf traces, or assembly tests. -The first four of these are all dependent on the type and identity of the -instruction, or the instruction opcode. In the traditional binary encoding -scheme, the opcode of an instruction may be determined from a single field -across the instruction set (rare), or a single field in sub-groups of the -instruction set combined with an instruction format specifier (more common). The -opcode may have additional constraints based on values of operand fields in the -instruction word as well, as is the case in the RiscV architecture. -Additionally, a predicate field may override any other decoding and designate an -instruction statically as a nop. On the other hand, in a proto based encoding -scheme, the opcode may be expressed as a single number (or enumeration type). +-------------------------------------------------------------------------------- -Regardless of the representation, the semantic function and the operands all -depend on the opcode. Therefore, the first step in creating a representation -independent decoder is to abstract out the parsing of the opcode to an interface -implemented by a representation specific decoder. +## 2. Quickstart: Your First `.isa` File -As mentioned above, the number and types of operands, such as register or -immediate, required by an instruction are determined by the opcode. On the other -hand, the exact value of a register number or an immediate, can only be -determined from the instruction representation. If factory methods for creating -instruction operands are implemented in the representation specific decoder, the -representation independent decoder can call these to obtain operand objects to -populate the Instruction instance. +Let's pair the `MiniRisc` binary encoding from +[binary-encoding.md](binary-encoding.md) with a complete `.isa` file supporting +four instructions: `add`, `addi`, `beq`, and a two-phase `lw` (load word). -The size of an instruction typically refers to its size in a particular -representation and again is a function of the opcode with no additional -information needed from the instruction representation. +### Step 1: Write `mini_risc.isa` -The instruction address is not part of the decoding except as a parameter to -identify the storage location of an instruction. +```c +// mini_risc.isa -# Representation Independent Decoder Description +// Format the first disassembly column (mnemonic) as 12 chars, left-justified: +disasm widths = {-12}; -The information necessary to generate the representation independent decoder is -contained in an MPACT-Sim ISA description file. It is processed by -`decoder_gen`, a purpose-built tool based on the [Antlr4](https://www.antlr.org) -parser generator, which reads the description and generates the appropriate -code. BUILD rules have been set up in the `mpact_sim_isa.bzl` file to make it -easy to incorporate the generated code into the simulator project for any target -architecture. +// Top-level ISA declaration: +isa MiniRisc { + namespace tutorial::mini_risc::isa; + slots { mini_risc; } +} -This section gives an overview of the contents of the description file and how -it fits in with MPACT-Sim and the code that gets generated. A detailed -description of the syntax is described in the next section. - -## Instruction Description - -Each instruction in the ISA is described separately. If the same operation, say -integer ADD, is implemented using multiple instructions, as long as they have -different encodings or different operands (for instance immediates vs registers, -unsigned immediate vs signed immediate), each such variation must have its own -description. - -Each instruction description can be divided into three components. The opcode -description, the semantic function specification, and the optional disassembly -format. - -### Opcode - -#### Name - -The opcode description specifies the name, the operands, and any child -instructions (see go/mpact-sim-overview “Modeling Instruction Issue and -Semantics”). The name of the opcode has to be unique within the ISA description. -By convention it is written in snake-case, with no capital letters, though this -is not a requirement. The name of the opcode is used to generate the name of an -entry in the enumeration class `OpcodeEnum`, by prepending “k” to the -pascal-case version of the name. That is, `add_i` becomes `kAddI`. This -enumeration class is generated in a separate .h file and is used both by the -generated code and in the representation specific decoder interface. - -#### Size - -Each opcode has a byte size associated with it, by default this is 1. The use of -the size is left to the simulator writer. For some ISAs it makes sense to have -the instruction size represent the PC increment when issuing instructions. For -some VLIW instructions, only the top-level bundle has an address, so the size of -the individual instructions don’t matter and can be left at 1. - -#### Operands - -The operands of an opcode are defined by a triplet: predicate operand, source -operand list, and destination operand list. Each individual operand is given a -name. This name is important. Just like the opcode name is used to create an -entry in an enum, each unique operand name is similarly added to an enum. There -are separate enum classes for each operand category: `PredOpEnum`, -`SourceOpEnum` and `DestOpEnum`. Just like for the OpcodeEnum class, the opcode -name gets converted to Pascal-case and prepended with a ‘k’. Thus, the operand -name “I\_imm12” gives rise to the enum class entry of `kIImm`12. Operands of the -same type (predicate/source/destination), that 1) have the same width, 2) have -the same zero/sign extension, and 3) refer to the same fields in the instruction -encoding should be given the same name. This minimizes the number of distinct -operand types and simplifies implementation of the representation specific -decoder, which will need to implement 3 methods, one for each of the predicate, -source and destination type. Each takes a value of the corresponding operand -enum class as a parameter and returns a new initialized operand object. - -The source and destination operands are specified in comma separated lists of -operand names. The predicate operand is a single operand name. Each type is -separated by a ‘:’, and may be left empty if desired. - -Each destination operand can be specified with an instruction latency, that is, -how many cycles the result should be buffered before being written to the -destination object (register or other simulated state). A value of zero causes -an immediate update without buffering. A value of one writes the value back at -the end of the current simulated cycle, i.e., so that instructions issued in the -next simulated cycle can see the update. A value of two writes the value back -and the end of the next simulated cycle, etc. The distinction between zero and -one is significant mostly for ISAs where instructions can be issued with -parallel semantics, e.g., instructions in a VLIW instruction word, where no -instruction can see updates from any other instruction in the same word. - -The following shows an example of the opcode declaration for the 32 bit add -immediate instruction with 0 latency in the RiscV32i ISA: - -``` -addi [4] { /*empty*/ : rs1, I_imm12 : rd(0) } -``` - -#### Child Instructions - -The semantics of an instruction may be divided into multiple actions that are -performed at separate times during the simulated execution of that instruction. -For instance, a load instruction is typically divided into two, the address -calculation and memory request, and the write-back of the data fetched from -memory to the register. The second (and any subsequent actions) are referred to -as child instructions of the opcode. They are allocated to separate Instruction -instances and have their own operands and semantic function. In this case, -operands can be assigned to each child instruction by using parenthesized lists -of operand triplets. For instance a RiscV32i ISA load word instruction would be -described as follows: - -``` -lw [4] { (/*empty*/ : rs1, I_imm12), (/*empty*/ : /*empty*/ : rd) } -``` - -### Semantic Function - -The instruction semantic function is a C++ callable that takes a pointer to the -instruction instance that implements the semantic operation of the instruction. -That is, it reads any source operands, performs the operation, and writes out -any results to the destination operands. An important part of the decoder is to -bind the correct semantic function to each instruction instance. - -To make it easier, the binding is expressed directly in the ISA description file -by adding a `semfunc` attribute to the opcode declaration. The semfunc attribute -takes a list of strings, one entry for each instruction/sub-instruction -specified, containing C++ code that is suitable to assign to the C++ callable, -including pointers to free functions, std::bind and absl::bind\_front bound -methods and functions, as well as lambdas and functors. - -The example below shows the semantic functions for the above load word -instruction. - -``` -lw [4] { (/*empty*/ : rs1, I_imm12), (/*empty*/ : /*empty*/ : rd) }, - semfunc: "&RV32ILw", "&RV32ILwChild"; -``` - -### Disassembly - -One of the intended use cases for MPACT-Sim is modeling prototype ISAs or -prototype ISA extensions. It is not always the case that there is a full toolset -available for such architectures, including a disassembler and/or debugger. -Therefore, the addition of a disassembly capability makes a lot of sense. -MPACT-Sim comes with a simple interactive user interface to step, run, set/clear -breakpoints, read and write memory and registers, etc. More complex interfaces -can easily be built, as well as custom simulator drivers. Being able to see the -disassembly of the instruction that is being executed is very valuable, and -helps debugging should there be any suspected issues with the instruction -semantics or decoding. - -The disassembly format is specified as the `disasm` opcode attribute, similarly -to the semantic function attribute. The argument to `disasm` is a list of text -strings that describes how the instruction should be disassembled. The list may -contain one or more strings that, when formatted, are concatenated to a single -disassembly string. The use of the `global disasm` widths declaration, allows -for each individual string to be left or right justified within a fixed width -field. The `global disasm` declaration takes a brace delimited list of integers, -one for each field to format. The sign of the integer specifies either left (-) -or right (+) justified, while the absolute value specifies the width (similar to -C style format strings). - -E.g., the following specifies that the first string will be left justified in a -field of 18 characters wide. The remaining strings will be concatenated. - -``` -global disasm = {-18}; -``` - -Any term in the string following an unescaped ‘%’ sign is interpreted to require -string substitution. Typically the string substitution is performed for operands -of the instruction. Each operand class has a `ToString()` method that returns -the preferred string representation of the operand value. For instance, register -operands return the register name, whereas immediate operands return the -immediate value. More complex formatting can be performed using a ‘%(<expr>)’ -construct, which allows a simple expression to be used as well as formatting the -value in hexadecimal, octal or binary. - -The disassembly format applies only to the main instruction, not child -instructions. - -Below is an example of the RiscV32i slli (shift left logical immediate) -instruction description including the disassembly format. - -``` -slli[4] { /*empty*/ : rs1, I_uimm5 : rd }, - disasm: "slli", "%rd, %rs1, 0x%(I_uimm5:x)", - semfunc: "&RV32ISll"; -``` - -## Slots and Bundles: Supporting VLIW Architectures - -As discussed so far the instruction description easily supports single issue -ISAs, that is, where the instructions have sequential semantics, regardless of -how an implementation may issue them. Most traditional architectures fall into -this category. However, VLIW ISAs impose some additional structure on the ISA, -and the MPACT-Sim isa description language has features to support these. - -### Slots - -A *slot* is an instruction position in a VLIW word. In its simplest form, a VLIW -word consists of exactly one slot, and that is how traditional non-VLIW ISAs are -modeled in this description. True VLIW ISAs has a number of slots. The slots may -be identical, that is, any instruction can be issued from any slot, or they can -differ, restricting which instructions can be issued from which slots. The -MPAC-Sim isa description supports both cases. - -A slot definition specifies an identifier as the slot name and an optional comma -separated list of slot names to inherit from (see below). The slot body -contains, an optional include file section, a set of `default` declarations and -an `opcodes` specification, which contains all the opcode definitions valid for -this slot. - -The default declarations allow for specifying the default size of instructions, -default latency for destination operands, and default opcode attributes -(semantic function and disassembly format), so that they don’t have to be -specified in opcode descriptions except when the value differs. An example is -shown below: - -``` -slot riscv32i { +// Single instruction slot for a sequential scalar processor: +slot mini_risc { includes { - // Any include files containing definitions used in the semfunc - // attributes. - #include "some/include/file.h" + #include "mini_risc_instructions.h" } + default size = 4; default latency = 0; + + // Fallback used when decoding an unrecognized instruction (OpcodeEnum::kNone): default opcode = - disasm: "Illegal instruction at 0x%(@:08x)", - semfunc: "&RV32IllegalInstruction"; + disasm: "illegal", "%(@:08x)", + semfunc: "&MiniRiscIllegal"; + opcodes { - ... + // R-type: rd = rs1 + rs2 + add { : rs1, rs2 : rd }, + disasm: "add", "%rd, %rs1, %rs2", + semfunc: "&MiniRiscAdd"; + + // I-type: rd = rs1 + imm12 + addi { : rs1, imm12 : rd }, + disasm: "addi", "%rd, %rs1, %imm12", + semfunc: "&MiniRiscAdd"; + + // B-type: if (rs1 == rs2) next_pc = pc + b_imm + beq { : rs1, rs2, b_imm : next_pc }, + disasm: "beq", "%rs1, %rs2, %(@+b_imm:08x)", + semfunc: "&MiniRiscBeq"; + + // Split-phase load: + // Parent: computes address (rs1 + imm12) and initiates memory read. + // Child: writes fetched data to 'rd'. + lw { (: rs1, imm12), (: : rd) }, + disasm: "lw", "%rd, %imm12(%rs1)", + semfunc: "&MiniRiscLwIssue", "&MiniRiscLwWriteback"; } } ``` -The ‘@’ sign in the disassembly format represents the instruction address. +### Step 2: Implement Semantic Functions (`mini_risc_instructions.h`) -The opcode specification is done as previously described. +Every semantic function takes a single `mpact::sim::generic::Instruction*`: -The tool generates a separate C++ decode function for each slot type that is -used in the ISA. +```cpp +#include "mpact/sim/generic/instruction.h" +// (In google3, include "third_party/mpact_sim/generic/instruction.h") -#### Slot Inheritance +namespace tutorial::mini_risc { -In some ISAs there may be a subset of instructions that can be issued from -multiple slots. Instead of requiring that the opcodes be defined anew in each -such slot, the notion of slot inheritance is introduced. A slot inheriting from -another slot inherits all of the opcodes from the base slot, except those that -are marked “deleted” in the derived slot. For instance: +void MiniRiscIllegal(::mpact::sim::generic::Instruction* inst); +void MiniRiscAdd(::mpact::sim::generic::Instruction* inst); +void MiniRiscBeq(::mpact::sim::generic::Instruction* inst); +void MiniRiscLwIssue(::mpact::sim::generic::Instruction* inst); +void MiniRiscLwWriteback(::mpact::sim::generic::Instruction* inst); +} // namespace tutorial::mini_risc ``` -slot base { - opcodes { - one [4] {}; - two [4] {}; - } -} -slot derived : base { - opcodes { - two = delete; // Only inherits opcode 'one'. - } +Inside `MiniRiscAdd(Instruction* inst)`, operands appear in the exact order +listed in `{ : rs1, rs2 : rd }`—for example, `inst->Source(0)` is `rs1`, +`inst->Source(1)` is `rs2` (or `imm12` for `addi`!), and `inst->Destination(0)` +is `rd`. Notice how `add` and `addi` can share the **exact same C++ semantic +function** (`&MiniRiscAdd`) because `SourceOperandInterface` abstracts whether +source 1 came from a register or an immediate! + +### Step 3: Connect `<IsaName>EncodingBase` and `<IsaName>InstructionSet` + +`decoder_gen` generates `mini_risc_enums.h` and `mini_risc_decoder.h` containing +`MiniRiscEncodingBase`, `MiniRiscInstructionSetFactory`, and +`MiniRiscInstructionSet`: + +1. Subclass `MiniRiscEncodingBase` and implement `GetOpcode()`, `GetSource()`, + and `GetDestination()` using your `.bin_fmt` extractors (`DecodeMiniRisc32`, + `r_type::ExtractRs1`, `i_type::ExtractImm12`, etc.). +2. Instantiate `MiniRiscInstructionSet` and call + `isa->Decode(address, &my_encoding)` inside your + `DecoderInterface::DecodeInstruction(uint64_t address)` method to obtain a + ready-to-execute `Instruction*`! + +-------------------------------------------------------------------------------- + +## 3. Global Declarations, Includes, Constants, and Expressions + +### Comments and Numeric Literals + +`.isa` files support `//` line comments, `/* ... */` block comments, and +hexadecimal (`0x1f`), binary (`0b1010`), octal (`077`), and decimal (`42`) +integer literals with optional single-quote digit separators (`0b1100'0011`, +`1'000`). + +### Importing `.isa` Files vs. Emitting C++ `#include` Headers + +There are **two distinct include constructs** in `.isa` files: + +1. **Top-level `#include "other_file.isa"`**: Parses and imports slots, + bundles, constants, or ISA definitions from another `.isa` file. Remember to + list imported `.isa` files in the `includes = [...]` attribute of + `mpact_isa_decoder` in your `BUILD` file. +2. **`includes { #include "header.h" }` blocks**: Copies C++ `#include` + directives into the generated `<prefix>_decoder.cc` file so semantic + functions and helpers (like `absl::bind_front`) are visible when compiling + the generated decoder: + * **Global `includes { ... }`**: Always emitted into + `<prefix>_decoder.cc`. + * **Slot- or bundle-local `includes { ... }`**: Merged and emitted + **only** if that slot or bundle is reachable from the selected `isa` + (directly or via slot inheritance). This keeps unused extension headers + out of builds that do not include those slots. + +### Constants and Integer Expressions + +You can define named `int` constants at **global scope** or inside a **`slot`**: + +```c +int kBaseLatency = 1; + +slot scalar_alu { + int kMulLatency = kBaseLatency + 2; + ... } ``` -Slot inheritance allows the ISA to be divided into subgroups by function if so -desired. In the RiscV32G description, each subgroup of the ISA is defined in a -separate slot, and then combined in a final slot that is used in the ISA. +Compile-time integer expressions can be used in constant definitions, +`disasm widths`, `default latency`, template arguments, destination operand +latencies, resource cycle windows, and instruction attributes. Expressions +support: -``` -slot riscv32 : riscv32i, riscv32c, riscv32m, riscv32a, riscv32f, riscv32d, zicsr, zfencei { - // default attributes for any instructions not otherwise matched. - default opcode = - disasm: "Illegal instruction at 0x%(@:08x)", - semfunc: "&RV32IllegalInstruction"; -} +* Literals, global/slot `int` constants, and `template <int ...>` parameter + names +* Arithmetic operators: unary `-`, `*`, `/`, `+`, `-`, and parentheses `(...)` +* Built-in function: `abs(expr)` + +### Disassembly Column Alignment (`disasm widths`) + +```c +disasm widths = {-18}; ``` -#### Templated Slots +When an opcode specifies multiple comma-separated strings in `disasm:` (for +example, `disasm: "addi", "%rd, %rs1, %imm12"`), `disasm widths` controls the +fixed width and alignment of each column from left to right: -A base slot can also be a templated slot. This allows, for instance, destination -operand latencies to be specified as an expression involving one or more -template parameters. Inherited opcodes are then evaluated in terms of the actual -template arguments. Currently only integer valued template arguments are -supported. The syntax is unsurprisingly familiar: +* **Negative integer (`-18`)**: Left-justified in an 18-character field. +* **Positive integer (`18`)**: Right-justified in an 18-character field. +* Any extra `disasm` strings beyond the number of entries in `disasm widths` + (or all strings if `disasm widths` is omitted) are concatenated with no + extra padding. -``` -template <int a, int b> -slot base_templated { - opcodes { - one [4] { : rs1, rs2 : rd(a + 1) }; - two [4] { : rs1, rs2 : rd(a + b + 1) }; - } -} +-------------------------------------------------------------------------------- -slot derived : base_templated<1, 3> { - … -} -``` +## 4. Top-Level `isa` Declaration -### Bundles +Every code generation target begins with an `isa` block: -A traditional VLIW instruction word is a bundle of slots with instructions that -are issued at the same time. However, some VLIW ISAs go further and divide its -slots into subgroups that can be issued at different times in the pipeline, or -even with a variable delay. MPACT-Sim allows bundles to be defined. A bundle -definition specifies the name of the bundle. The bundle body has two sections: -bundles and slots, that list the names of other bundle and slot definitions that -make up the current bundle. - -Each bundle definition used in the isa will have a DecodeFunction generated for -it. - -### ISA - -The top level of the MPACT-Sim isa specification is the “isa” definition. There -may be more than one isa definition in a .isa file. The isa for which to -generate code is specified in an option to the isa-parsing tool. The “isa” -definition specifies the name of the isa, the namespace within which the C++ -code will be generated, and the set of slots and bundles which makes up the isa, -similarly to a bundle definition. - -The simple isa definition for RiscV32G is shown below: - -``` +```c isa RiscV32G { namespace mpact::sim::riscv::isa32; slots { riscv32; } } ``` -### Constants +or, for a multi-bundle VLIW architecture: -Integer typed constants can be declared both at the global level and within -slots to give names to values. These constants can be used in expressions with -other constants and integer literals wherever integer values can be used (e.g., -instruction latencies). E.g., - -``` -int global_latency = 1; - -slot myslot { - int my_latency = global_latency + 1; - ... +```c +isa MyVliwIsa { + namespace my_sim::vliw::isa; + bundles { + main_bundle; + } } ``` -### Include Files +* **`isa <IsaName>`**: Sets the PascalCase prefix for generated classes + (`<IsaName>EncodingBase`, `<IsaName>InstructionSet`, + `<IsaName>InstructionSetFactory`, `<IsaName>EncoderInterfaceBase`). +* **`namespace <cpp::ns>;`**: The C++ namespace for all generated enums and + classes. +* **`slots { ... }` or `bundles { ... }`**: A sequential/single-word ISA lists + its `slots` directly; an ISA with sub-bundle dispatch structure lists its + top-level `bundles`. +* Multiple `isa` declarations may coexist in `.isa` files; select the active + target via `isa_name = "RiscV32G"` in `mpact_isa_decoder` (or + `--isa_name=RiscV32G` on the `decoder_gen` CLI). -In addition to the include files specified within each slot, as described -previously, a set of include files can also be specified at the global level. -While those specified within a slot are only added to the generated code if the -slot is reachable from the top level isa, the global include files are always -included in the generated code. +-------------------------------------------------------------------------------- +## 5. Describing Opcodes and Operands (`opcodes { ... }`) + +Inside a `slot`, the `opcodes { ... }` block defines the instructions valid in +that slot. + +### Basic Syntax + +```c +opcode_name [byte_size] { predicate : sources : destinations }, + attribute_1, + attribute_2, + ...; ``` -includes { - #include "include/a/global/file.h" + +* **`opcode_name`**: Must be unique across the ISA. `decoder_gen` converts + `snake_case` names to `PascalCase` prefixed with `k` in `OpcodeEnum` (for + example, `add_i` -> `OpcodeEnum::kAddI`), which must match the name used in + `.bin_fmt`. +* **`[byte_size]`** *(optional)*: Instruction byte size stored on + `Instruction::size()` (commonly used for PC increments). If omitted, the + slot's `default size` is used (which itself defaults to `1` if unset). + +### Operand Triplets (`{ pred : sources : dests }`) + +Operands are written inside braces `{ ... }` in up to three colon-separated +sections—**predicate**, **source list**, and **destination list**—all of which +are optional: + +| Syntax | Meaning | Example Instruction | +| :--------------------- | :----------------------- | :---------------------- | +| `{}` | No predicate, no | `nop {}` or `ecall {}` | +: : sources, no destinations : : +| `{ pred }` | Predicate operand only | `st_marker { pred }` | +| `{ : rs1, imm12 }` | Sources only (no | `fence { : imm12 }` | +: : predicate, no : : +: : destinations) : : +| `{ : rs1, S_imm12, rs2 | Sources only (trailing | `sw { : rs1, S_imm12, | +: \: }` : `\:` optional) : rs2 \: }` : +| `{ : rs1, rs2 : rd }` | Sources and destination | `add { : rs1, rs2 : rd | +: : (no predicate) : }` : +| `{ pred : sx, sy : dst | Predicate, sources, and | `vadd { pred : sx, sy : | +: }` : destination : dst }` : + +#### Naming Operands Wisely + +Every distinct operand name you write creates an entry in `PredOpEnum`, +`SourceOpEnum`, or `DestOpEnum` (`rs1` -> `SourceOpEnum::kRs1`, `I_imm12` -> +`SourceOpEnum::kIImm12`). In `<IsaName>EncodingBase`, you implement one factory +entry per enum value! + +**Best Practice**: Give two operands the **same name** whenever they belong to +the same category (predicate, source, or destination) and have the **exact same +bit position, bit width, and sign/zero extension** in the encoding. Conversely, +give them **different names** (such as `I_imm12` vs. `S_imm12` vs. `I_uimm5`) +when they extract different bitfields or signedness. + +### Scalar vs. List / Array Operands (`[rlist]`) + +Some instructions read or write a **variable-length list of registers** encoded +by a bitmask or count field (for example, Arm `push`/`pop` or RISC-V +`cm.push`/`cm.pop`). Enclose the operand name in square brackets `[name]`: + +```c +push { : x2, spimm6, rlist, [rlist] : x2 }; +pop { : x2, spimm6, rlist : x2, [rlist] }; +``` + +* Scalar `rlist` generates `SourceOpEnum::kRlist` and calls + `GetSource(...) -> SourceOperandInterface*`. +* Bracketed `[rlist]` generates `ListSourceOpEnum::kRlist` (or + `ListDestOpEnum::kRlist`) and calls + `GetSources(...) -> std::vector<SourceOperandInterface*>` (or + `GetDestinations(...)`), appending every returned operand to the + `Instruction`! + +### Relocation Annotation (`%reloc`) + +Prefixing a source or destination operand with `%reloc(op_name)` marks that +operand as carrying symbol relocation information when generating +assembler/encoder glue in `<prefix>_encoder.{h,cc}`: + +```c +jal { : %reloc(J_imm20) : next_pc, rd }; +``` + +### Destination Operand Latencies + +Every destination operand in MPACT-Sim has a cycle **latency** controlling when +the written value takes effect: + +* **Latency `0`**: Immediate writeback during semantic function execution + (typical for sequential single-issue simulators where no parallel slot reads + old values in the same cycle). +* **Latency `1`**: Buffered writeback at the end of the current cycle, visible + on the *next* cycle (essential for **VLIW** bundles so parallel instructions + in the same bundle read pre-bundle register values!). +* **Latency `N` (`N > 1`)**: Buffered writeback visible after `N` simulated + cycles (for modeling non-interlocked or pipelined execution). + +You can specify destination latency in three ways: + +1. **Compile-time expression**: `rd(0)`, `rd(2)`, `rd(kLoadLatency + 1)` +2. **Dynamic / runtime wildcard**: `rd(*)` — tells the generated decoder to + call `enc->GetLatency(slot, entry, opcode, DestOpEnum::kRd, dest_no)` at + decode time. +3. **Slot default**: `rd` (no parentheses) — uses `default latency = <expr>;` + from the enclosing `slot`. (If a slot has no `default latency`, omitting + `(latency)` on a destination operand is an error unless supplied via + `latency:`.) + +### Multi-Phase / Child Instructions (`(parent), (child)`) + +Instructions whose execution spans multiple stages—most commonly **memory +loads**, where stage 1 computes the effective address and issues the memory +request, and stage 2 writes the returned data buffer into `rd`—are modeled using +parenthesized operand tuples: + +```c +lw { (: rs1, I_imm12), (: : rd) }, + disasm: "lw", "%rd, %I_imm12(%rs1)", + semfunc: "&RV32ILw", "&RV32ILwChild"; +``` + +* The first tuple `(: rs1, I_imm12)` populates the parent `Instruction*` + (`&RV32ILw`). +* The second tuple `(: : rd)` allocates a child `Instruction*` + (`&RV32ILwChild`) attached via `inst->child()` (additional tuples chain via + `inst->child()->child()`, etc.). +* When `semfunc:` is specified, you must provide **one semantic function + string per tuple** (parent first, then each child in order). + +### Templated Opcode Expansion (`GENERATE`) + +Just like `.bin_fmt`, a slot's `opcodes` block supports `GENERATE(...)` over +single-variable lists or synchronized value tuples, expanding the Cartesian +product when multiple range assignments are separated by commas: + +```c +GENERATE( + [op, fn] = [{add, MyAdd}, {sub, MySub}, {and, MyAnd}], + [suffix, dsp_suf, src2] = [{r, "", rs2}, {i, ".i", imm12}] +) { + $(op)_$(suffix) { : rs1, $(src2) : rd }, + disasm: "$(op)$(dsp_suf)", "%rd, %rs1, %$(src2)", + semfunc: "&$(fn)"; +}; +``` + +Notes on `GENERATE` in `.isa` files: + +* Remember the trailing semicolon (`};`) after the `GENERATE` block (every + entry in `opcodes { ... }` is `;`-terminated). +* Attributes like `disasm:` and `semfunc:` still require string literal quotes + around the template (`semfunc: "&$(fn)"`). +* Range values may be identifiers (`add`, `MyAdd`), numbers, or quoted strings + (`""`, `".i"`). Outer double quotes on range values are stripped before + substituting `$(var)`, which makes quoted strings ideal for empty suffixes + (`""`) or fragments containing punctuation (`".i"`). + +-------------------------------------------------------------------------------- + +## 6. Opcode Attributes Reference + +An opcode can have up to **five** comma-separated attributes (at most one of +each kind): + +### 1. Semantic Functions (`semfunc:`) + +```c +semfunc: "&MySemFunc" +semfunc: "&ParentFunc", "&ChildFunc" +``` + +Each string literal must be a valid C++ expression convertible to +`Instruction::SemanticFunction` (`void(Instruction*)`). Common idioms: + +```cpp +// Given C++ declarations: +void MyAdd(Instruction* inst); +void VectorOp(int elem_bytes, Instruction* inst); +void ShiftOp(Instruction* inst, bool arithmetic); +``` + +```c +// In .isa: +semfunc: "&MyAdd" +semfunc: "absl::bind_front(&VectorOp, 4)" +semfunc: "std::bind(&ShiftOp, std::placeholders::_1, true)" +semfunc: "[](Instruction* inst) { /* inline no-op */ }" +``` + +### 2. Disassembly Formatting (`disasm:`) + +```c +disasm: "beq", "%rs1, %rs2, %(@+B_imm12:08x)" +``` + +Supported `%` substitutions inside `disasm` strings (escape a literal percent +sign as `\%`): + +* **`%op_name`**: Calls `AsString()` on the matching predicate, source, or + destination operand (for example, `"x5"` for a register or `"42"` for an + immediate). +* **`%op_name?`** *(optional operand formatting)*: Useful for predicates + (e.g., `"%pred? add"`), printing the operand only when present/active. +* **`%(expr:fmt)`** *(formatted numeric/PC expression)*: + * `@` represents `inst->address()` (the PC of the instruction). + * `@ + op_name` or `@ - op_name` adds/subtracts an operand's integer value + to/from the PC (ideal for PC-relative branches and jumps!). + * `(op_name << N)`, `(op_name >> N)`, or `@ + (op_name << N)` shifts the + operand value before formatting. Bit-shift sub-expressions **must** be + enclosed in parentheses (for example, `%((U_imm20 >> 12):d)` or + `%(@ + (imm << 2):08x)`). + * `:fmt` is an integer format specifier: `:d` (decimal), `:o` (octal), + `:x` (lowercase hex, which **automatically prepends `"0x"`**), or `:X` + (uppercase hex **without** a `"0x"` prefix). Specifiers may include a 1- + or 2-digit width (`1`–`99`), optionally zero-padded, such as `:08x` or + `:04d` (if you write a leading `0`, always include the 1- or 2-digit + width, e.g., `:08x` rather than `:0x`, and avoid writing `"0x%(...:x)"` + since `:x` already emits `"0x"`). + +### 3. Hardware Pipeline Resources (`resources:`) + +To detect structural or data hazards in cycle-accurate or scoreboarding +simulators, declare hardware/register resources in three optional +colon-separated lists: + +```c +resources: { use_list : acquire_list : hold_list } +``` + +* **`use_list`** *(1st section)*: Resources that must be **free at + dispatch/issue time** (checked only, not reserved). +* **`acquire_list`** *(2nd section)*: Resources that must be **free at + dispatch time AND reserved** for their specified `[begin..end]` cycle + window. +* **`hold_list`** *(3rd section)*: Resources **reserved** for their + `[begin..end]` cycle window *without* checking whether they are already free + at dispatch time. + +Each item can be a scalar `name` or list `[name]` with an optional cycle range: + +| Syntax | Start Cycle | End Cycle | Classification | +| :--------------- | :---------- | :--------------- | :---------------------- | +| `rd` or `rd[]` | `0` (issue) | `rd`'s dest | Simple | +: : : latency (or `0`) : (`SimpleResourceEnum`) : +| `rd[..3]` or | `0` (issue) | Cycle `3` | Simple | +: `rd[0..3]` : : : (`SimpleResourceEnum`) : +| `alu_pipe[1..3]` | Cycle `1` | Cycle `3` | Complex | +: : : : (`ComplexResourceEnum`) : +| `mul_wb[2..]` | Cycle `2` | Matching dest | Complex | +: : : latency (or `0`) : (`ComplexResourceEnum`) : + +* Resources that are only ever reserved starting at cycle `0` become **Simple + Resources** (`SimpleResourceEnum`, efficiently tracked with a single + bitvector). +* Any resource reserved starting at a non-zero cycle (`begin_cycle != 0`) in + the ISA is automatically classified as a **Complex Resource** + (`ComplexResourceEnum`, or `ListComplexResourceEnum` for `[name]`). +* Common resource patterns can be named once at the top of a `slot` and reused + across opcodes: + +```c +slot my_slot { + resources ThreeOp = { next_pc, rs1, rs2 : rd[..rd] }; + opcodes { + add { : rs1, rs2 : rd }, resources: ThreeOp, semfunc: "&MyAdd"; + } } ``` -# Detailed Syntax of .isa File +### 4. Instruction Attributes (`attributes:`) -The full [Antlr4](https://www.antlr.org) grammar of the .isa file is found in -the file `InstructionSet.g4`. +Instruction attributes attach compile-time `int` metadata flags/values (such as +branch markers, privilege levels, or memory access tags) to decoded +`Instruction`s: + +```c +slot my_slot { + default attributes = { is_branch = 0, is_mem = 0, priv_level = 0 }; + opcodes { + beq { : rs1, rs2, b_imm : next_pc }, + attributes: { is_branch = 1 }, + semfunc: "&MyBeq"; + } +} +``` + +* `decoder_gen` emits `namespace my_slot { enum class AttributeEnum { + kIsBranch = 0, kIsMem = 1, kPrivLevel = 2, kPastMaxValue = 3 }; }` in + `<prefix>_enums.h`. +* At runtime, query attributes on an `Instruction*` via + `inst->Attributes()[static_cast<int>(my_slot::AttributeEnum::kIsBranch)]`. +* Always write explicit `= value` assignments (such as `is_branch = 1`) when + setting non-zero flags: omitting `= expr` (e.g., `{ is_branch }`) registers + the attribute name in `AttributeEnum` with value `0`. Unmentioned attributes + inherit the slot's `default attributes` value (or `0` if none). + +### 5. Explicit Destination Latency Attribute (`latency:`) + +```c +latency: rd(3), [rlist](2) +``` + +Sets or overrides latencies on destination operands already declared in +`{ ... }`. This is particularly handy when customizing an inherited opcode in a +derived slot using `= override`. + +-------------------------------------------------------------------------------- + +## 7. Slots, Inheritance, Templates, and VLIW Bundles + +### Slot Defaults + +Every **referenced** slot (one listed in `isa` or a `bundle`) **must** define +`default opcode` with a `semfunc:`: + +```c +slot alu_slot { + default size = 4; + default latency = 1; + default attributes = { is_alu = 1 }; + default opcode = + disasm: "illegal", + semfunc: "&HandleIllegalInstruction"; + opcodes { ... } +} +``` + +`default opcode` is used both for `OpcodeEnum::kNone` (when binary decoding +finds no match) and as the fallback semantic function for any opcode in the slot +that omits `semfunc:`. Base slots used *only* for inheritance do not need +`default opcode`. + +### Slot Inheritance (`: base`), `= delete`, and `= override` + +You can factor modular ISA extensions or shared VLIW slot subsets into base +slots and combine them in derived slots: + +```c +slot rv32i { opcodes { add { : rs1, rs2 : rd }, semfunc: "&Add"; sub { : rs1, rs2 : rd }, semfunc: "&Sub"; } } +slot rv32m { opcodes { mul { : rs1, rs2 : rd(3) }, semfunc: "&Mul"; } } + +slot core_slot : rv32i, rv32m { + default opcode = semfunc: "&Illegal"; + opcodes { + // Exclude an opcode inherited from a base slot: + sub = delete; + + // Customize attributes (latency, semfunc, disasm, resources, attributes) + // of an inherited opcode without redeclaring its operands: + mul = override, + latency: rd(5), + semfunc: "&SlowMul"; + } +} +``` + +Slot inheritance must form a **tree** (inheriting from the same ancestor twice +via diamond inheritance, or inheriting the same opcode name from two base slots, +is reported as an error). + +### Templated Base Slots (`template <int ...>`) + +When two slots or cores share the same instructions but have different pipeline +latencies, parameterize the base slot with `template <int ...>`: + +```c +template <int alu_lat, int mul_lat> +slot base_ops { + opcodes { + add { : rs1, rs2 : rd(alu_lat) }, semfunc: "&Add"; + mul { : rs1, rs2 : rd(mul_lat) }, semfunc: "&Mul"; + } +} + +slot fast_core : base_ops<1, 2> { + default opcode = semfunc: "&Illegal"; +} + +slot deep_pipe_core : base_ops<2, 5> { + default opcode = semfunc: "&Illegal"; +} +``` + +### Replicated Slots (`slot name[N]`) and VLIW `bundle` Declarations + +In a VLIW architecture, an instruction word (bundle) issues multiple slots in +parallel, and some slots may appear multiple times (for example, 4 identical +vector ALU slots and 2 load slots): + +```c +isa ExampleVliw { + namespace sim::vliw; + bundles { + top_bundle; + } +} + +bundle top_bundle { + bundles { + scalar_subbundle; + vector_subbundle; + } + semfunc: "&DispatchTopBundle"; +} + +bundle scalar_subbundle { + slots { + scalar_slot[0, 1]; + } + semfunc: "&DispatchScalarSubbundle"; +} + +bundle vector_subbundle { + slots { + vec_alu[0..3]; + vec_mem; + } + semfunc: "&DispatchVectorSubbundle"; +} + +slot scalar_slot[2] { + default latency = 1; + default opcode = semfunc: "&Nop"; + opcodes { ... } +} + +slot vec_alu[4] { + default latency = 1; + default opcode = semfunc: "&Nop"; + opcodes { ... } +} + +slot vec_mem { + default latency = 2; + default opcode = semfunc: "&Nop"; + opcodes { ... } +} +``` + +Rules for replicated slots and bundles: + +* When a slot declares `[N]` instances (`slot vec_alu[4]`), **every instance + `0 .. N-1`** must be referenced at least once in `slots { ... }`. Use + `[0..3]` or `[0, 2]` to select specific instance indices (`entry` passed to + `GetOpcode(SlotEnum, int entry)`). +* Unreferenced base slots and `template` slots may **not** specify `[N]`. +* Every `bundle` must contain at least one child bundle or slot and specify a + bundle-level `semfunc:` responsible for executing its decoded + sub-instructions. + +-------------------------------------------------------------------------------- + +## 8. Bazel Build Rule and Generated C++ API Reference + +### `mpact_isa_decoder` Build Rule + +```python +load("//third_party/mpact_sim/decoder:mpact_sim_isa.bzl", "mpact_isa_decoder") +# (Or "@mpact-sim//mpact/sim/decoder:mpact_sim_isa.bzl" in standalone Bazel) + +mpact_isa_decoder( + name = "mini_risc_isa", + src = "mini_risc.isa", # Or srcs = [...] for multiple top-level files + includes = [], # Any #include'd .isa files + isa_name = "MiniRisc", # Selects 'isa MiniRisc' + prefix = "mini_risc", # Output file prefix (defaults to src stem) + generator = 1, # Set generator = 2 to pass Instruction* to getters + deps = [":mini_risc_semfuncs"], # Libraries declaring your semantic functions +) +``` + +### Generated Files (`prefix = "mini_risc"`, `isa MiniRisc`) + +| Generated File | Key Generated Types & Symbols | +| :---------------------------- | :------------------------------------------- | +| `mini_risc_enums.h` / `.cc` | `SlotEnum`, `OpcodeEnum`, `PredOpEnum`, | +: : `SourceOpEnum`, `ListSourceOpEnum`, : +: : `DestOpEnum`, `ListDestOpEnum`, : +: : `SimpleResourceEnum`, `ComplexResourceEnum`, : +: : `ListComplexResourceEnum`, `k*Names[]` : +: : string tables, and : +: : `<slot>\:\:AttributeEnum`. : +| `mini_risc_decoder.h` / `.cc` | `MiniRiscEncodingBase`, `<SlotPascal>Slot`, | +: : `<BundlePascal>Decoder`, : +: : `MiniRiscInstructionSetFactory`, and : +: : `MiniRiscInstructionSet`. : +| `mini_risc_encoder.h` / `.cc` | `MiniRiscEncoderInterfaceBase` and RE2-based | +: : `<SlotPascal>Matcher` classes generated from : +: : `disasm\:` patterns for assembly text : +: : encoding. : + +### Virtual Methods on `<IsaName>EncodingBase` + +Your C++ encoding class inherits from `<IsaName>EncodingBase`. Only `GetOpcode` +is pure virtual; override whichever operand/resource getters your `.isa` uses: + +```cpp +class MiniRiscEncodingBase { + public: + virtual ~MiniRiscEncodingBase() = default; + + // Pure virtual: return OpcodeEnum for the given slot and instance index: + virtual OpcodeEnum GetOpcode(SlotEnum slot, int entry) = 0; + + // Override if any opcode uses predicates: + virtual PredicateOperandInterface* GetPredicate( + SlotEnum slot, int entry, OpcodeEnum opcode, PredOpEnum pred_op); + + // Override for scalar and '[list]' source operands: + virtual SourceOperandInterface* GetSource( + SlotEnum slot, int entry, OpcodeEnum opcode, SourceOpEnum source_op, + int source_no); + virtual std::vector<SourceOperandInterface*> GetSources( + SlotEnum slot, int entry, OpcodeEnum opcode, + ListSourceOpEnum list_source_op, int source_no); + + // Override for scalar and '[list]' destination operands: + virtual DestinationOperandInterface* GetDestination( + SlotEnum slot, int entry, OpcodeEnum opcode, DestOpEnum dest_op, + int dest_no, int latency); + virtual std::vector<DestinationOperandInterface*> GetDestinations( + SlotEnum slot, int entry, OpcodeEnum opcode, + ListDestOpEnum list_dest_op, int dest_no, + const std::vector<int>& latency); + + // Override if any destination operand uses dynamic latency '(*)': + virtual int GetLatency( + SlotEnum slot, int entry, OpcodeEnum opcode, DestOpEnum dest_op, + int dest_no); + + // Override if your .isa models simple or complex pipeline resources: + virtual ResourceOperandInterface* GetSimpleResourceOperand( + SlotEnum slot, int entry, OpcodeEnum opcode, + SimpleResourceVector& resource_vec, int end); + virtual ResourceOperandInterface* GetComplexResourceOperand( + SlotEnum slot, int entry, OpcodeEnum opcode, + ComplexResourceEnum resource, int begin, int end); + virtual std::vector<ResourceOperandInterface*> GetComplexResourceOperands( + SlotEnum slot, int entry, OpcodeEnum opcode, + ListComplexResourceEnum resource, int begin, int end); +}; +``` + +*(Tip: If you set `generator = 2` in `mpact_isa_decoder`, `Instruction* inst` is +passed as the first parameter to all operand, latency, and resource getter +methods on `<IsaName>EncodingBase`.)* + +-------------------------------------------------------------------------------- + +## 9. Best Practices from Production Simulators + +Real-world MPACT-Sim simulators—including **`mpact_riscv`** (RV32G/RV64G, +Vector, Bitmanip, Compressed `Zc*`, and the RVM23 profile), **`mpact_cheriot`** +(CHERIoT capability-enabled RISC-V + RVV), and the **Coral NPU** simulator +(RISC-V scalar control core + custom NPU vector extensions)—use a consistent set +of `.isa` idioms to keep large, multi-variant instruction sets modular and +maintainable. + +### 1. Factor Complex ISAs into One Base Slot per Extension or Functional Unit + +Avoid defining hundreds of instructions in a single monolithic `slot`. Instead, +model each ISA extension or execution functional unit as its own **unreferenced +base `slot`**, splitting large extensions into separate `.isa` files: + +* **`mpact_riscv`** defines separate base slots for `riscv32i`, `riscv32m`, + `riscv32_amo_arithmetic`, `riscv32f`, `riscv32d`, `zicsr`, `zfencei`, + `privileged`, `riscv32c`, `riscv32_hints`, plus standalone extension files + such as `riscv32zb.isa`, `riscv_vector.isa`, `riscv_zc.isa`, + `riscv_zicond.isa`, and `riscv_zicbom.isa`. +* **`mpact_cheriot`** factors capability base instructions + (`riscv_cheriot.isa`), single-precision floating point + (`riscv_cheriot_f.isa`), integer RVV (`riscv_cheriot_vector.isa`), and FP + RVV (`riscv_cheriot_vector_fp.isa`) into separate files and slots. +* **Coral NPU** splits its ISA across `coralnpu_base.isa`, + `coralnpu_arith.isa`, `coralnpu_mul.isa`, `coralnpu_shift.isa`, and + `coralnpu_memory.isa`, while directly `#include`-ing `riscv32zb.isa` from + `mpact_riscv`! + +Note that these building-block slots **omit `default opcode`** because they are +only used via inheritance. + +### 2. Compose Simulator Profiles Using Thin Top-Level `.isa` Files + +With extensions factored into modular `.isa` files and base slots, defining a +complete processor variant or profile takes only a few dozen lines: `#include` +the extension `.isa` files, declare a top-level composite `slot` that inherits +from the desired subset of base slots, and define `default opcode` once at the +top level. + +For example, `rvm23.isa` in `mpact_riscv` assembles 25 extension slots into a +single profile cleanly: + +```c +// rvm23.isa +isa RVM23 { + namespace mpact::sim::riscv::rvm23; + slots { rvm23; } +} + +#include "riscv32g.isa" +#include "riscv32zb.isa" +#include "riscv_vector.isa" +#include "riscv_zc.isa" +#include "riscv_zicond.isa" +// ... other Z* extension .isa files ... + +slot rvm23 : + riscv32i, riscv32m, riscv32_amo_arithmetic, riscv32f, riscv32d, + riscv32_hints, zicsr, zfencei, privileged, riscv_vector, + riscv32_zb, riscv32_zicond /* ... */ { + default opcode = + disasm: "Illegal instruction at %(@:08x)", + semfunc: "&RiscVIllegalInstruction"; +} +``` + +Similarly, a single wrapper file can define **multiple `isa` targets** for +closely related hardware configurations. For example, `riscv_cheriot_rvv.isa` +defines both `isa RiscVCheriotRVV` +(`slot riscv_cheriot_rvv : riscv32_cheriot, riscv_cheriot_vector`) and +`isa RiscVCheriotRVVFp` (adding `riscv_cheriot_vector_fp` and +`riscv_cheriot_f`), allowing two Bazel `mpact_isa_decoder` rules to generate +integer-only and FP-enabled decoders from the same `.isa` source via +`isa_name = "..."`. + +### 3. Scope C++ `includes` to Individual Slots and Fully Qualify `semfunc` Names + +When factoring `.isa` files for reuse across multiple targets (or even across +different repositories, as Coral NPU reuses `mpact_riscv` extensions), follow +two C++ hygiene rules: + +1. **Place semantic-function `#include` headers inside the `slot` that uses + them, not at global scope**: For example, put + `#include "riscv_f_instructions.h"` inside + `slot riscv32f { includes { ... } }` and vector headers inside + `slot riscv_vector { includes { ... } }`. Because `decoder_gen` only emits + `includes` from slots reachable by the chosen `isa`, integer-only builds + never pull in floating-point or vector C++ headers. +2. **Fully qualify C++ namespaces from the global `::` root in shared + `semfunc:` strings**: Writing + `semfunc: "&::mpact::sim::riscv::RV32::RiscVIAdd"` instead of + `"&RV32::RiscVIAdd"` guarantees the generated `_decoder.cc` compiles cleanly + even when another simulator imports that slot into a completely different + `isa` C++ namespace (such as `coralnpu::sim::isa32`). + +### 4. Maximize Semantic Function Reuse via Operand Abstraction and `absl::bind_front` + +Because semantic functions read and write abstract `SourceOperandInterface` and +`DestinationOperandInterface` objects, a single C++ function can often implement +many `.isa` opcodes: + +* **Share semantics between compact (16-bit) and standard (32-bit) + encodings**: In `mpact_riscv` and `mpact_cheriot`, 16-bit compressed + instructions reuse the exact same C++ semantic functions as 32-bit + instructions by supplying hardwired register operands (`x0`, `x2`) or + dedicated immediate operand names in `.isa`: + + ```c + // 32-bit register add, 32-bit immediate add, 16-bit c.mv, and 16-bit c.li + // all bind to the exact same C++ function (&RiscVIAdd)! + add { : rs1, rs2 : rd }, semfunc: "&RiscVIAdd"; + addi { : rs1, I_imm12 : rd }, semfunc: "&RiscVIAdd"; + cmv { : crs2, x0 : rd }, semfunc: "&RiscVIAdd"; + cli { : x0, I_ci_imm6 : rd }, semfunc: "&RiscVIAdd"; + ``` + +* **Use synthetic "always-true" predicate/mask operands for unpredicated + variants**: In `riscv_vector.isa` and Coral NPU, masked vector loads + (`vle8`) pass `vmask`, while unmasked encodings (`vle8_vm1`) pass a + synthetic `vmask_true` operand + (`vle8_vm1 { (: rs1, const1, vmask_true), (: : vd) }`) whose C++ getter + returns a constant all-ones mask operand—allowing one C++ implementation to + handle both masked and unmasked execution. + +* **Bind element widths or mode flags with `absl::bind_front`**: Instead of + writing separate wrappers for 8-, 16-, 32-, and 64-bit vector loads or + `vsetvli` `rd`/`rs1 == x0` variants, bind compile-time parameters directly + in `semfunc:`: + + ```c + vle8 { (: rs1, const1, vmask), (: : vd) }, + semfunc: "absl::bind_front(&VlStrided, /*elem_width=*/1)", "&VlChild"; + vle16 { (: rs1, const2, vmask), (: : vd) }, + semfunc: "absl::bind_front(&VlStrided, /*elem_width=*/2)", "&VlChild"; + ``` + +### 5. Separate Side-Effect-Free Variants and Architectural Hints into Distinct Opcodes + +Pairing `.bin_fmt` field constraints (`rd == 0`, `rs1 == 0`) with distinct +`.isa` opcodes makes both functional simulation and hazard tracking cleaner and +more accurate: + +* **CSR read/write suppression (`zicsr`)**: `mpact_riscv` defines + `csrrs { : rs1, csr : rd, csr }` alongside `csrrs_nw { : csr : rd }` + (decoded when `rs1 == 0`) and `csrrs_nr { : rs1, csr : csr }` (decoded when + `rd == 0`). Notice that `csrrs_nw` omits `csr` from its destination operand + and resource-acquire lists, accurately modeling both the absence of CSR + write side effects and the absence of CSR write hazards. +* **Isolating hint instructions (`slot riscv32_hints`)**: Encoding `rd == 0` + hint variants (`addi_hint1`, `slli_hint1`, etc.) in a separate + `riscv32_hints` slot bound to `&RiscVINop` keeps `riscv32i` clean while + letting microarchitectural models selectively `= override` specific hints + (such as semihosting sequences or prefetch hints) in derived slots. + +### 6. Name Reusable Hazard Patterns per Slot (`resources`) + +Rather than repeating `{ next_pc, rs1, rs2 : rd[..rd] }` on dozens of ALU and +floating-point opcodes, declare named resource groups (`TwoOp`, `ThreeOp`, +`FourOp`) at the top of each `slot` (as done throughout `mpact_riscv` and Coral +NPU): + +```c +slot riscv32f { + resources TwoOp = { next_pc, frs1 : frd[0..] }; + resources ThreeOp = { next_pc, frs1, frs2 : frd[0..] }; + resources FourOp = { next_pc, frs1, frs2, frs3 : frd[0..] }; + opcodes { + fadd_s { : frs1, frs2, rm : frd }, resources: ThreeOp, ...; + fmadd_s { : frs1, frs2, frs3, rm : frd }, resources: FourOp, ...; + } +} +``` + +-------------------------------------------------------------------------------- + +## 10. Common Pitfalls and Troubleshooting Checklist + +* **Missing `default opcode` on a referenced slot**: Every slot referenced by + `isa` or `bundle` **must** declare `default opcode = semfunc: "...";`. + Without it, `decoder_gen` reports an error. +* **Missing destination operand latency**: If a slot does not set + `default latency = <expr>;`, then every destination operand in that slot + must explicitly specify either `(expr)` or `(*)`. +* **Mismatched `semfunc:` count on multi-part instructions**: If an opcode has + a parent and child tuple `{ (: rs1, imm12), (: : rd) }`, `semfunc:` must + list **two** strings (`semfunc: "&LoadIssue", "&LoadWriteback"`), not one. +* **Using `const Instruction*` in semantic functions**: MPACT-Sim's + `SemanticFunction` signature is `void(Instruction*)` (non-const), and + `std::bind` placeholders live in `std::placeholders::_1`. +* **Unreferenced slot instances**: If you declare `slot alu[4]`, referencing + only `alu[0..2]` in `slots { ... }` is an error—all 4 instances (`0..3`) + must be placed in the ISA or bundles. +* **Leading zero without width in `disasm` format**: Write `%(imm:x)` + (unpadded hex) or `%(imm:08x)` (zero-padded 8-digit hex), **not** + `%(imm:0x)`. + +-------------------------------------------------------------------------------- + +## 11. Grammar Reference + +The complete ANTLR4 grammar for `.isa` files is located in `InstructionSet.g4` +in the `decoder/` directory.