Separating Source Intent, Machine Encoding, and CPU Execution

Today's most important takeaway: I realized that I often confuse the intent expressed by source code, the encoding of machine instructions, and how the CPU executes them.

For example:

addi t0, zero, -1

My initial reasoning went roughly like this: 1. The negative number -1 should be represented in two's complement. 2. Its 12-bit two's-complement representation is 111111111111. 3. That bit pattern can also be written as 0xFFF. 4. So why can't I simply write addi t0, zero, 0xFFF?

More precisely, I had not yet built this mental model:

Three layers: -1 in assembly source is a value with mathematical meaning; the assembler encodes it as twelve ones in the immediate field according to ADDI's conventions; the CPU then interprets and executes it according to ADDI's rules.

I had merged the first and second layers.

In source code, 0xFFF expresses the positive integer 4095. In an already-encoded 12-bit ADDI immediate field, however, the same bits represent -1.

Afterward, I reflected: had I been expecting the assembler to do too much?

Yes. More precisely, I had not clearly distinguished the responsibilities of the assembler, the instruction-encoding rules, and the CPU.

When the assembler sees 0xFFF in source code, it treats that literal as 4095. It does not first read it as 4095, then notice ADDI and discover that 4095 is outside the immediate's allowed range, and automatically reinterpret 0xFFF as the in-range value -1.

I had expected it to do that because I personally thought that 0xFFF and -1 had the same machine-code encoding. I need to be alert to this mistaken intuition.