Solution (source code)

= Solution

A <MIPS R-type instruction> has the 32-<bit> <instruction encoding>
$$
\underbrace{\mathrm{op}}_{6}\ \underbrace{\mathrm{rs}}_{5}\ \underbrace{\mathrm{rt}}_{5}\ \underbrace{\mathrm{rd}}_{5}\ \underbrace{\mathrm{shamt}}_{5}\ \underbrace{\mathrm{funct}}_{6}.
$$
For `add $x,$y,$z`, the <processor register> indices are $\mathrm{rs}=y$, $\mathrm{rt}=z$ and $\mathrm{rd}=x$, while $\mathrm{shamt}=0$. The main <opcode> selects the R-type family and the function field selects addition. The <register file> reads its two operands from instruction <bits> 25:21 and 20:16. In the original <datapath>, `RegDst=1` selects <bits> 15:11 as the destination, `ALUSrc=0` selects the second <register file> output, and `ALUFunc=ADD` makes the <arithmetic logic unit> add its inputs. The result returns to `wdata`; `RegWrite=1` writes it to $x$ at the active <clock edge>. The `zero` output is irrelevant here.<Digital systems, linear algebra, introduction to formal proof examination paper by the University of Oxford (2014)>[Question 1 datapath, printed page 2: the input-0 and input-1 multiplexer labels determine these control polarities]{ref}

A <MIPS I-type instruction> instead has the <instruction encoding>
$$
\underbrace{\mathrm{op}}_{6}\ \underbrace{\mathrm{rs}}_{5}\ \underbrace{\mathrm{rt}}_{5}\ \underbrace{\mathrm{immediate}}_{16}.
$$
For `addi $x,$y,n`, $\mathrm{rs}=y$, $\mathrm{rt}=x$, and the low sixteen <bits> contain the <immediate operand>. The <register file> supplies $y$ to the first <arithmetic logic unit> input. Set `RegDst=0` to select <bits> 20:16 for the destination, and `ALUSrc=1` to select the extended <immediate operand> for the second input. The <opcode> directly requests addition, so `ALUFunc=ADD` and `RegWrite=1`. The second <register file> read is unused. The returned result is written into $x$.

The <sign extension> circuit retains the low sixteen <bits> and copies <bit> 15 into all sixteen new high positions:
$$
\boxed{\operatorname{sext}(n)_{15:0}=n,\qquad \operatorname{sext}(n)_{31:16}=\underbrace{n_{15}\cdots n_{15}}_{16\text{ copies}}.}
$$
Thus <sign extension> preserves the signed <two's complement> value: `0x7fff` becomes `0x00007fff`, whereas `0x8000` becomes `0xffff8000`. For both instructions, the architectural result above assumes no signed overflow; the full <MIPS architecture> specifies an overflow exception, which is outside this simplified <datapath>.