// 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 branch_cpu(input wire CLOCK_50, input wire [3:0] KEY, input wire [9:0] SW, output logic [9:0] LEDR,
    output wire [6:0] HEX0, HEX1, HEX2, HEX3, HEX4, HEX5);
    wire [15:0] address, write_data;
    wire write_enable;
    logic [15:0] read_data;
    reg [15:0] memory [0:255];
    reg [6:0] segments [0:5];
    assign HEX0 = ~segments[0];
    assign HEX1 = ~segments[1];
    assign HEX2 = ~segments[2];
    assign HEX3 = ~segments[3];
    assign HEX4 = ~segments[4];
    assign HEX5 = ~segments[5];
    integer i;
    integer digit;
    initial begin
        for (i=0;i<256;i=i+1) memory[i]=0;
        // BEGIN ASSEMBLED PROGRAM
        memory[0] = 16'h1400;
        memory[1] = 16'h1C03;
        memory[2] = 16'h6000;
        memory[3] = 16'h243A;
        memory[4] = 16'h1C05;
        memory[5] = 16'h2201;
        memory[6] = 16'h1E3E;
        memory[7] = 16'h5402;
        memory[8] = 16'h1C09;
        memory[9] = 16'h2401;
        memory[10] = 16'h1E3E;
        memory[11] = 16'h1C0C;
        memory[12] = 16'h2231;
        memory[13] = 16'h5402;
        memory[14] = 16'h1C11;
        memory[15] = 16'h17FF;
        memory[16] = 16'h5601;
        memory[17] = 16'h262C;
        memory[18] = 16'h1C13;
        memory[19] = 16'h2801;
        memory[20] = 16'h1E3E;
        memory[21] = 16'h5402;
        memory[22] = 16'h1C19;
        memory[23] = 16'h1600;
        memory[24] = 16'h4603;
        memory[25] = 16'h2601;
        memory[26] = 16'h1E3E;
        memory[27] = 16'h1C1C;
        memory[28] = 16'h2821;
        memory[29] = 16'h5402;
        memory[30] = 16'h1C21;
        memory[31] = 16'h1600;
        memory[32] = 16'h57FF;
        memory[33] = 16'h2A1C;
        memory[34] = 16'h1C23;
        memory[35] = 16'h2C01;
        memory[36] = 16'h1E3E;
        memory[37] = 16'h5402;
        memory[38] = 16'h1C29;
        memory[39] = 16'h1600;
        memory[40] = 16'h4603;
        memory[41] = 16'h2A01;
        memory[42] = 16'h1E3E;
        memory[43] = 16'h1C2C;
        memory[44] = 16'h2C11;
        memory[45] = 16'h5402;
        memory[46] = 16'h1C33;
        memory[47] = 16'h186B;
        memory[48] = 16'h8804;
        memory[49] = 16'h16A5;
        memory[50] = 16'h6604;
        memory[51] = 16'h240A;
        memory[52] = 16'h5401;
        memory[53] = 16'h1C3B;
        memory[54] = 16'h16A5;
        memory[55] = 16'h186C;
        memory[56] = 16'hA604;
        memory[57] = 16'h8804;
        memory[58] = 16'h6604;
        memory[59] = 16'h2402;
        memory[60] = 16'h5401;
        memory[61] = 16'h1E42;
        memory[62] = 16'h3610;
        memory[63] = 16'hAC03;
        memory[64] = 16'h1A65;
        memory[65] = 16'h1E45;
        memory[66] = 16'h3610;
        memory[67] = 16'hA403;
        memory[68] = 16'h1A5F;
        memory[69] = 16'h3820;
        memory[70] = 16'h8605;
        memory[71] = 16'hA604;
        memory[72] = 16'h5A01;
        memory[73] = 16'h5801;
        memory[74] = 16'h8605;
        memory[75] = 16'hA604;
        memory[76] = 16'h5A01;
        memory[77] = 16'h5801;
        memory[78] = 16'h8605;
        memory[79] = 16'hA604;
        memory[80] = 16'h5A01;
        memory[81] = 16'h5801;
        memory[82] = 16'h8605;
        memory[83] = 16'hA604;
        memory[84] = 16'h5A01;
        memory[85] = 16'h5801;
        memory[86] = 16'h8605;
        memory[87] = 16'hA604;
        memory[88] = 16'h5A01;
        memory[89] = 16'h5801;
        memory[90] = 16'h8605;
        memory[91] = 16'hA604;
        memory[92] = 16'h5A01;
        memory[93] = 16'h5801;
        memory[94] = 16'h1E5E;
        memory[95] = 16'h005E;
        memory[96] = 16'h0079;
        memory[97] = 16'h006D;
        memory[98] = 16'h006D;
        memory[99] = 16'h0077;
        memory[100] = 16'h0073;
        memory[101] = 16'h005E;
        memory[102] = 16'h0079;
        memory[103] = 16'h0038;
        memory[104] = 16'h0030;
        memory[105] = 16'h0077;
        memory[106] = 16'h0071;
        memory[107] = 16'h00A5;
        memory[108] = 16'h005A;
        // 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]) begin
            LEDR <= 0;
            for (digit=0; digit<6; digit=digit+1) segments[digit] <= 0;
        end
        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'h2: begin
                read_data <= 0;
                if (write_enable && KEY[0] && address[11:0] < 6)
                    segments[address[2:0]] <= write_data[6: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
    reg load_branch_pc;
    reg z_flag, n_flag, c_flag;
    wire [16:0] wide_sum = {1'b0,A} + {1'b0,BusWires};
    wire take_branch = (rX == 0) || (rX == 1 && z_flag) ||
                       (rX == 2 && !z_flag) || (rX == 3 && c_flag) ||
                       (rX == 4 && c_flag) || (rX == 5 && !n_flag) ||
                       (rX == 6 && n_flag);
    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;
        load_branch_pc = 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
                        if (Imm) begin
                            Select = _IR7_0_0; rX_in = 1'b1; Done = 1'b1;
                        end else begin
                            Select = _PC; A_in = 1'b1; Done = !take_branch;
                        end
                    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: // compute the branch target using the already-incremented PC
                case (III)
                    mvt: begin Select = _IR8_IR8_0; G_in = 1'b1; end
                    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: // commit register or branch result
                case (III)
                    mvt: begin Select = _G; load_branch_pc = 1'b1; Done = 1'b1; end
                    add, sub, and_: begin
                        Select = _G; rX_in = 1'b1; Done = 1'b1;
                    end
                    ld: begin
                        Select = _DIN; rX_in = 1'b1; Done = 1'b1;
                    end
                    default: ;
                endcase
            default: ;
        endcase
    end

    assign pc_in = R_in[7] | load_branch_pc;
    always @(posedge Clock) begin
        if (!Resetn) begin
            z_flag <= 1'b0; n_flag <= 1'b0; c_flag <= 1'b0;
        end else if (G_in && (III == add || III == sub || III == and_)) begin
            z_flag <= (Sum == 0); n_flag <= Sum[15];
            if (III == add) c_flag <= wide_sum[16];
            if (III == sub) c_flag <= (A >= BusWires);
        end
    end

    // 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
