Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 37 ยท Projects and Practice

Project: An 8-bit ALU with Flags and a Testbench

Design an 8-bit Verilog ALU with add, subtract, logic and shift operations and zero, negative, carry and overflow flags, then verify it against a reference model.

The arithmetic logic unit (ALU) is the part of a processor that adds, subtracts and combines bits, and it makes a perfect first project: it is purely combinational, has a small clear specification, and its flags teach the difference between carry and overflow, a distinction that trips up nearly everyone. In this project you will specify the ALU, write it in Verilog, write a self-checking testbench against a reference model, and run the same model in C.

Verilog and its simulators do not run on this site, so the RTL and testbench are read-only; the C programs are labelled stand-ins that implement the reference model and check the flag logic exhaustively. Use the testbench techniques from self-checking testbenches.

Specification

An 8-bit ALU with inputs a, b (8 bits), a 3-bit op, and outputs y (8 bits) and four flags:

op Name Result
000 ADD a + b
001 SUB a - b
010 AND a & b
011 OR a | b
100 XOR a ^ b
101 SHL a << 1
110 SHR a >> 1 (logical)
111 SLT 1 if a < b signed, else 0

Flags:

  • Z (zero): y == 0.
  • N (negative): y[7], the sign bit of the result.
  • C (carry): for ADD, the carry out of bit 7; for SUB, set when no borrow occurred (a >= b unsigned). For shifts, the bit shifted out. Cleared for logic operations.
  • V (overflow): the signed result does not fit in 8 bits. Only ADD and SUB can overflow.

Carry tells you about unsigned arithmetic; overflow tells you about signed arithmetic. 100 + 100 = 200 does not carry (200 fits in 8 unsigned bits) but overflows as signed (200 is more than +127).

The overflow rule

For addition, overflow happens when the two operands have the same sign and the result has a different sign:

TEXT
V_add = (a[7] == b[7]) && (y[7] != a[7])

For subtraction a - b, we compute a + ~b + 1, so b effectively flips sign:

TEXT
V_sub = (a[7] != b[7]) && (y[7] != a[7])

The Verilog

VERILOG
module alu8 (
  input      [7:0] a, b,
  input      [2:0] op,
  output reg [7:0] y,
  output           z, n,
  output reg       c, v
);
  localparam ADD = 3'd0, SUB = 3'd1, AND_ = 3'd2, OR_ = 3'd3,
             XOR_ = 3'd4, SHL = 3'd5, SHR = 3'd6, SLT = 3'd7;

  reg [8:0] wide;                      // 9 bits: result plus carry

  always @* begin
    wide = 9'd0;
    y = 8'd0; c = 1'b0; v = 1'b0;      // defaults: no latches
    case (op)
      ADD: begin
        wide = {1'b0, a} + {1'b0, b};
        y = wide[7:0];
        c = wide[8];
        v = (a[7] == b[7]) && (y[7] != a[7]);
      end
      SUB: begin
        wide = {1'b0, a} + {1'b0, ~b} + 9'd1;
        y = wide[7:0];
        c = wide[8];                   // 1 means no borrow
        v = (a[7] != b[7]) && (y[7] != a[7]);
      end
      AND_: y = a & b;
      OR_:  y = a | b;
      XOR_: y = a ^ b;
      SHL:  begin y = {a[6:0], 1'b0}; c = a[7]; end
      SHR:  begin y = {1'b0, a[7:1]}; c = a[0]; end
      SLT:  y = {7'd0, ($signed(a) < $signed(b))};
      default: y = 8'd0;
    endcase
  end

  assign z = (y == 8'd0);
  assign n = y[7];
endmodule

Points to notice:

  • Default values at the top of the always @* prevent latches.
  • The 9-bit wide variable captures the carry; the operands are widened explicitly (see width pitfalls).
  • SLT uses $signed on both operands so the compare is signed.

A reference model in C

The same specification in C, written differently on purpose (using wide integers instead of bit tricks) so that bugs in one do not appear in the other. The first stand-in prints some operations with their flags:

C Stand-in: ALU reference model and a flag table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Look at 100 + 100: y = 200 (a negative number when read as signed), C = 0, V = 1. And 200 + 100 carries (C = 1) with y = 44. The 0x80 - 1 case is -128 - 1, the classic signed overflow (V = 1) which also shows C = 1 because there was no unsigned borrow.

The testbench

VERILOG
`timescale 1ns/1ps
module alu8_tb;
  reg  [7:0] a, b;
  reg  [2:0] op;
  wire [7:0] y;
  wire       z, n, c, v;
  integer    i, j, errors, checks;

  alu8 dut (.a(a), .b(b), .op(op), .y(y), .z(z), .n(n), .c(c), .v(v));

  // reference model, written differently from the DUT
  task check;
    reg [8:0] w;
    reg [7:0] ey;
    reg ec, ev;
    integer sa, sb, ssum;
    begin
      sa = $signed(a); sb = $signed(b);
      ec = 0; ev = 0;
      case (op)
        3'd0: begin w = a + b; ey = w[7:0]; ec = (a + b) > 255; ssum = sa + sb; ev = (ssum < -128) || (ssum > 127); end
        3'd1: begin ey = a - b; ec = (a >= b); ssum = sa - sb; ev = (ssum < -128) || (ssum > 127); end
        3'd2: ey = a & b;
        3'd3: ey = a | b;
        3'd4: ey = a ^ b;
        3'd5: begin ey = a << 1; ec = a[7]; end
        3'd6: begin ey = a >> 1; ec = a[0]; end
        default: ey = (sa < sb);
      endcase
      #1;
      checks = checks + 1;
      if ({y, z, n, c, v} !== {ey, ey == 8'd0, ey[7], ec, ev}) begin
        errors = errors + 1;
        if (errors < 10)
          $display("FAIL op=%0d a=%0d b=%0d: y=%0d zncv=%b%b%b%b expected y=%0d c=%b v=%b",
                   op, a, b, y, z, n, c, v, ey, ec, ev);
      end
    end
  endtask

  initial begin
    errors = 0; checks = 0;
    for (i = 0; i < 256; i = i + 1)
      for (j = 0; j < 256; j = j + 1)
        for (op = 0; op < 3'd7; op = op + 1) begin   // see note below
          a = i; b = j; check;
        end
    // note: op is 3 bits, so loop ends at 6; run SLT separately
    op = 3'd7;
    for (i = 0; i < 256; i = i + 1)
      for (j = 0; j < 256; j = j + 1) begin a = i; b = j; check; end

    if (errors == 0) $display("PASS: %0d checks", checks);
    else             $display("FAIL: %0d errors in %0d checks", errors, checks);
    $finish;
  end
endmodule

The note matters: a loop variable of 3 bits can never exceed 7, so op < 8 would loop forever. Use an integer loop counter and assign op = k;, or stop at 6 and handle 7 separately as shown. Bugs like this live in testbenches too.

Exhaustive checking of the flags

There are only 65,536 input pairs per operation, so the testbench can check every one. The second stand-in does exactly that for ADD and SUB, comparing a bit-trick flag computation (what the Verilog does) against the wide-integer model. If the overflow formula were wrong anywhere, the count of mismatches would not be zero.

C Stand-in: exhaustive check of carry and overflow formulas

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Zero errors over 131,072 checks proves the two overflow formulas for all 8-bit inputs. That is the power of exhaustive testing on small designs; for a 32-bit ALU you would switch to random and directed vectors, as in stimulus and system tasks.

Extensions

  1. Add a rotate-left and rotate-right operation and extend op to 4 bits.
  2. Add arithmetic shift right (>>> on a signed value) and test the sign extension.
  3. Parameterize the width (parameter W = 8) and test with 4 and 16 bits.
  4. Write the ALU in SystemVerilog with a typedef enum for op (data types).
  5. Add a registered output stage and a valid bit, then fit it into a small CPU datapath.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. 100 + 100 in an 8-bit ALU produces which flags?

    200 fits in 8 unsigned bits (no carry) but exceeds +127, so as a signed result it overflows.
  2. 2. When does signed overflow occur for addition?

    Adding two positives to get a negative, or two negatives to get a positive, means the true result did not fit.
  3. 3. Why is the ALU in the project written with wide = {1'b0, a} + {1'b0, b}?

    Widening the operands makes the addition 9 bits wide, so bit 8 holds the carry.
  4. 4. Why is exhaustive testing practical here?

    Two 8-bit inputs have 65,536 combinations, so every case can be checked.

Summary

  • An ALU is combinational: inputs a, b, op produce y and flags Z, N, C, V.
  • Carry is about unsigned results; overflow about signed results (same-sign operands, different-sign result).
  • Write the reference model differently from the DUT and check exhaustively when the input space is small.
  • Watch for bugs in the testbench itself, such as loop variables that are too narrow.

Next: Project: A UART Transmitter