// MIT License
//
// Copyright (c) 2021 FPGAcademy.org
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

// CPU adapted from FPGAcademy.org, copyright 2021, MIT License. See FPGAcademy-MIT.txt.
module io_cpu(input wire CLOCK_50, input wire [3:0] KEY, input wire [9:0] SW, output logic [9:0] LEDR);
    wire [15:0] address, write_data;
    wire write_enable;
    logic [15:0] read_data;
    reg [15:0] memory [0:255];
    integer i;
    initial begin
        for (i=0;i<256;i=i+1) memory[i]=0;
        // BEGIN ASSEMBLED PROGRAM
        memory[0] = 16'h3610;
        memory[1] = 16'h3830;
        memory[2] = 16'h1A30;
        memory[3] = 16'h8004;
        memory[4] = 16'hA005;
        memory[5] = 16'h1000;
        memory[6] = 16'h8205;
        memory[7] = 16'hD21F;
        memory[8] = 16'hA203;
        memory[9] = 16'h1E03;
        // END ASSEMBLED PROGRAM
    end
    proc core(read_data, KEY[0], CLOCK_50, SW[9], write_data, address, write_enable);
    always_ff @(posedge CLOCK_50) begin
        if (!KEY[0]) LEDR <= 0;
        case (address[15:12])
            4'h0: begin
                read_data <= memory[address[7:0]];
                if (write_enable && KEY[0]) memory[address[7:0]] <= write_data;
            end
            4'h1: begin
                read_data <= 0;
                if (write_enable && KEY[0]) LEDR <= write_data[9:0];
            end
            4'h3: read_data <= {6'b0, SW};
            default: read_data <= 0;
        endcase
    end
endmodule

module flipflop (D, Resetn, Clock, Q);
    input D, Resetn, Clock;
    output Q;
    reg Q;

    always_ff @(posedge Clock)
        if (Resetn == 0)
            Q <= 1'b0;
        else
            Q <= D;
endmodule

module proc(DIN, Resetn, Clock, Run, DOUT, ADDR, W);
    input [15:0] DIN;
    input Resetn, Clock, Run;
    output wire [15:0] DOUT;
    output wire [15:0] ADDR;
    output wire W;

    wire [0:7] R_in; // r0, ..., r7 register enables
    reg rX_in, IR_in, ADDR_in, Done, DOUT_in, A_in, G_in, AddSub, ALU_and;
    reg [2:0] Tstep_Q, Tstep_D;
    reg [15:0] BusWires;
    reg [3:0] Select; // BusWires selector
    reg [15:0] Sum;
    wire [2:0] III, rX, rY; // instruction opcode and register operands
    wire [15:0] r0, r1, r2, r3, r4, r5, r6, pc, A;
    wire [15:0] G;
    wire [15:0] IR;
    reg pc_incr;    // used to increment the pc
    wire pc_in;      // used to load the pc
    reg W_D;        // used for write signal
    wire Imm;

    assign III = IR[15:13];
    assign Imm = IR[12];
    assign rX = IR[11:9];
    assign rY = IR[2:0];
    dec3to8 decX (rX_in, rX, R_in); // produce r0 - r7 register enables

    parameter T0 = 3'b000, T1 = 3'b001, T2 = 3'b010, T3 = 3'b011, T4 = 3'b100, T5 = 3'b101;

    // Control FSM state table
    always @(Tstep_Q, Run, Done)
        case (Tstep_Q)
            T0: // instruction fetch
                if (~Run) Tstep_D = T0;
                else Tstep_D = T1;
            T1: // wait cycle for synchronous memory
                Tstep_D = T2;
            T2: // this time step stores the instruction word in IR
                Tstep_D = T3;
            T3: if (Done) Tstep_D = T0;
                else Tstep_D = T4;
            T4: if (Done) Tstep_D = T0;
                else Tstep_D = T5;
            T5: // instructions end after this time step
                Tstep_D = T0;
            default: Tstep_D = 3'bxxx;
        endcase

    /* OPCODE format: III M XXX DDDDDDDDD, where
    *     III = instruction, M = Immediate, XXX = rX. If M = 0, DDDDDDDDD = 000000YYY = rY
    *     If M = 1, DDDDDDDDD = #D is the immediate operand
    *
    *  III M  Instruction   Description
    *  --- -  -----------   -----------
    *  000 0: mv   rX,rY    rX <- rY
    *  000 1: mv   rX,#D    rX <- D (sign extended)
    *  001 1: mvt  rX,#D    rX <- D << 8
    *  010 0: add  rX,rY    rX <- rX + rY
    *  010 1: add  rX,#D    rX <- rX + D
    *  011 0: sub  rX,rY    rX <- rX - rY
    *  011 1: sub  rX,#D    rX <- rX - D
    *  100 0: ld   rX,[rY]  rX <- [rY]
    *  101 0: st   rX,[rY]  [rY] <- rX
    *  110 0: and  rX,rY    rX <- rX & rY
    *  110 1: and  rX,#D    rX <- rX & D */
    parameter mv = 3'b000, mvt = 3'b001, add = 3'b010, sub = 3'b011, ld = 3'b100, st = 3'b101,
         and_ = 3'b110;
    // selectors for the BusWires multiplexer
    parameter _R0 = 4'b0000, _R1 = 4'b0001, _R2 = 4'b0010, _R3 = 4'b0011, _R4 = 4'b0100,
        _R5 = 4'b0101, _R6 = 4'b0110, _PC = 4'b0111, _G = 4'b1000,
        _IR8_IR8_0 /* signed-extended immediate data */ = 4'b1001,
        _IR7_0_0 /* immediate data << 8 */ = 4'b1010,
        _DIN /* data-in from memory */ = 4'b1011;
    // Control FSM outputs
    always_comb begin
        // default values for control signals
        rX_in = 1'b0; A_in = 1'b0; G_in = 1'b0; IR_in = 1'b0; DOUT_in = 1'b0; ADDR_in = 1'b0;
        Select = 4'bxxxx; AddSub = 1'b0; ALU_and = 1'b0; W_D = 1'b0; Done = 1'b0;
        pc_incr = 1'b0;

        case (Tstep_Q)
            T0: begin // fetch the instruction
                Select = _PC;  // put pc onto the internal bus
                ADDR_in = 1'b1;
                pc_incr = Run; // to increment pc
            end
            T1: // wait cycle for synchronous memory
                ;
            T2: // store instruction on DIN in IR
                IR_in = 1'b1;
            T3: // define signals in T3
                case (III)
                    mv: begin
                        if (!Imm) Select = rY;          // mv rX, rY
                        else Select = _IR8_IR8_0; // mv rX, #D
                        rX_in = 1'b1;                   // enable the rX register
                        Done = 1'b1;
                    end
                    mvt: begin
                        Select = _IR7_0_0; rX_in = 1'b1; Done = 1'b1;
                    end
                    add, sub, and_: begin
                        Select = {1'b0,rX}; A_in = 1'b1;
                    end
                    ld, st: begin
                        Select = {1'b0,rY}; ADDR_in = 1'b1;
                    end
                    default: ;
                endcase
            T4: // define signals T2
                case (III)
                    add: begin
                        Select = Imm ? _IR8_IR8_0 : {1'b0,rY}; G_in = 1'b1;
                    end
                    sub: begin
                        Select = Imm ? _IR8_IR8_0 : {1'b0,rY}; AddSub = 1'b1; G_in = 1'b1;
                    end
                    and_: begin
                        Select = Imm ? _IR8_IR8_0 : {1'b0,rY}; ALU_and = 1'b1; G_in = 1'b1;
                    end
                    ld: // wait cycle for synchronous memory
                        ;
                    st: begin
                        Select = {1'b0,rX}; DOUT_in = 1'b1; W_D = 1'b1;
                    end
                    default: ;
                endcase
            T5: // define T3
                case (III)
                    add, sub, and_: begin
                        Select = _G; rX_in = 1'b1; Done = 1'b1;
                    end
                    ld: begin
                        Select = _G; rX_in = 1'b1; Done = 1'b1;
                    end
                    default: ;
                endcase
            default: ;
        endcase
    end

    assign pc_in = R_in[7];

    // Control FSM flip-flops
    always_ff @(posedge Clock)
        if (!Resetn)
            Tstep_Q <= T0;
        else
            Tstep_Q <= Tstep_D;

    regn reg_0 (BusWires, Resetn, R_in[0], Clock, r0);
    regn reg_1 (BusWires, Resetn, R_in[1], Clock, r1);
    regn reg_2 (BusWires, Resetn, R_in[2], Clock, r2);
    regn reg_3 (BusWires, Resetn, R_in[3], Clock, r3);
    regn reg_4 (BusWires, Resetn, R_in[4], Clock, r4);
    regn reg_5 (BusWires, Resetn, R_in[5], Clock, r5);
    regn reg_6 (BusWires, Resetn, R_in[6], Clock, r6);

    // r7 is program counter
    // module pc_count(R, Resetn, Clock, E, L, Q);
    pc_count reg_pc (BusWires, Resetn, Clock, pc_incr, pc_in, pc);

    regn reg_A (BusWires, Resetn, A_in, Clock, A);
    regn reg_DOUT (BusWires, Resetn, DOUT_in, Clock, DOUT);
    regn reg_ADDR (BusWires, Resetn, ADDR_in, Clock, ADDR);
    regn reg_IR (DIN, Resetn, IR_in, Clock, IR);

    flipflop reg_W (W_D, Resetn, Clock, W);

    // alu
    always_comb
        if (!ALU_and)
            if (!AddSub)
                Sum = A + BusWires;
            else
                Sum = A + ~BusWires + 16'b1;
          else
            Sum = A & BusWires;
    regn reg_G (Sum, Resetn, G_in, Clock, G);

    // define the internal processor bus
    always_comb
        case (Select)
            _R0: BusWires = r0;
            _R1: BusWires = r1;
            _R2: BusWires = r2;
            _R3: BusWires = r3;
            _R4: BusWires = r4;
            _R5: BusWires = r5;
            _R6: BusWires = r6;
            _PC: BusWires = pc;
            _G: BusWires = G;
            _IR8_IR8_0: BusWires = {{7{IR[8]}}, IR[8:0]}; // sign extended
            _IR7_0_0: BusWires = {IR[7:0], 8'b0};
            _DIN: BusWires = DIN;
            default: BusWires = 16'bx;
        endcase
endmodule

module pc_count(R, Resetn, Clock, E, L, Q);
    input [15:0] R;
    input Resetn, Clock, E, L;
    output [15:0] Q;
    reg [15:0] Q;

    always_ff @(posedge Clock)
        if (!Resetn)
            Q <= 16'b0;
        else if (L)
            Q <= R;
        else if (E)
            Q <= Q + 1'b1;
endmodule

module dec3to8(E, W, Y);
    input E; // enable
    input [2:0] W;
    output [0:7] Y;
    reg [0:7] Y;

    always_comb
        if (E == 0)
            Y = 8'b00000000;
        else
            case (W)
                3'b000: Y = 8'b10000000;
                3'b001: Y = 8'b01000000;
                3'b010: Y = 8'b00100000;
                3'b011: Y = 8'b00010000;
                3'b100: Y = 8'b00001000;
                3'b101: Y = 8'b00000100;
                3'b110: Y = 8'b00000010;
                3'b111: Y = 8'b00000001;
            endcase
endmodule

module regn(R, Resetn, E, Clock, Q);
    parameter n = 16;
    input [n-1:0] R;
    input Resetn, E, Clock;
    output [n-1:0] Q;
    reg [n-1:0] Q;

    always_ff @(posedge Clock)
        if (!Resetn)
            Q <= 0;
        else if (E)
            Q <= R;
endmodule
