Sub topic 4
Expanding Opcodes and Counting Encodable Instructions
Assume you know binary notation, instruction fields, and the purpose of registers and memory. This chapter focuses on how one fixed-length instruction word can support several instruction formats.
Why expanding opcodes are needed
An instruction usually contains an opcode and operand fields. The opcode identifies the operation, while operand fields identify registers, memory addresses, or other values.
Suppose every instruction uses the same number of bits. Giving more bits to operands leaves fewer bits for the opcode. An expanding opcode solves this by using opcode patterns that are unused by one format as prefixes for other formats.
A common design gives priority to instructions with more operands:
| Format | Operand fields | Typical use |
|---|---|---|
| Two-address | 2 | `ADD X, Y` |
| One-address | 1 | `INC X` |
| Zero-address | 0 | Stack operation such as `ADD` |
When a two-address instruction is not selected, its unused address field can become part of a longer opcode.
Counting with an expanding opcode
Consider a 16-bit instruction with a 4-bit opcode and two 6-bit address fields. If 14 two-address opcode patterns are already used, then:
\[ 2^4 - 14 = 2 \]
4-bit prefixes remain. Each remaining prefix can be combined with a 6-bit field, so the one-address capacity is:
\[ 2 \times 2^6 = 128 \]
If 100 one-address instructions are required, 28 one-address encodings remain. Each of those can be combined with another 6-bit field for zero-address instructions:
\[ (128 - 100) \times 2^6 = 1792 \]
# 16-bit instructions: 4-bit opcode, two 6-bit address fields.
opcode_bits = 4
address_bits = 6
two_address_count = 14
free_prefixes = 2**opcode_bits - two_address_count
one_address_capacity = free_prefixes * 2**address_bits
one_address_used = 100
zero_address_capacity = (
one_address_capacity - one_address_used
) * 2**address_bits
print(one_address_capacity) # 128
print(zero_address_capacity) # 1792The important rule is that every encoding consumed at one level removes all of the encodings below it that share that prefix.
GATE solving method
- Write the number of patterns in the current opcode field.
- Subtract the patterns already assigned.
- Multiply each remaining prefix by the number of combinations in the newly available operand field.
- Repeat for the next format.
- Check that no prefix is assigned to two formats.
Exercise
A 3-bit opcode has 5 two-address instructions. Each address field has 4 bits. How many one-address encodings can use the remaining prefixes?
Show answer
There are 2 remaining prefixes. Each combines with 2^4 = 16 values, so the capacity is 2 × 16 = 32 one-address encodings.