-- 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.
LIBRARY ieee;
USE ieee.std_logic_1164.all;

ENTITY flipflop IS
   PORT ( D, Resetn, Clock   : IN   STD_LOGIC;
          Q                  : OUT  STD_LOGIC);
END flipflop;

ARCHITECTURE Behavior OF flipflop IS
BEGIN
   PROCESS (Clock)
   BEGIN
      IF (Clock'EVENT AND Clock = '1') THEN
         IF (Resetn = '0') THEN
            Q <= '0';
         ELSE
            Q <= D;
         END IF;
      END IF;
   END PROCESS;
END Behavior;

library ieee;
USE ieee.std_logic_1164.all;
USE ieee.numeric_std.all;

ENTITY proc IS
    PORT (  DIN                 : IN  STD_LOGIC_VECTOR(15 DOWNTO 0);
            Resetn, Clock, Run  : IN  STD_LOGIC;
            DOUT                : OUT STD_LOGIC_VECTOR(15 DOWNTO 0);
            ADDR                : OUT STD_LOGIC_VECTOR(15 DOWNTO 0);
            W                   : OUT STD_LOGIC);
END proc;

ARCHITECTURE Behavior OF proc IS
    COMPONENT pc_count
        PORT (  R    : IN   STD_LOGIC_VECTOR(15 DOWNTO 0);
                Resetn, Clock, E, L   : IN   STD_LOGIC;
                Q    : OUT STD_LOGIC_VECTOR(15 DOWNTO 0));
    END COMPONENT;
    COMPONENT dec3to8
        PORT ( E   : IN   STD_LOGIC;
               W   : IN   STD_LOGIC_VECTOR(2 DOWNTO 0);
               Y   : OUT  STD_LOGIC_VECTOR(0 TO 7));
    END COMPONENT;
    COMPONENT regn
        GENERIC ( n : INTEGER := 16);
        PORT ( R                   : IN STD_LOGIC_VECTOR(n-1 DOWNTO 0);
               Resetn, E, Clock    : IN STD_LOGIC;
               Q                   : OUT STD_LOGIC_VECTOR(n-1 DOWNTO 0));
    END COMPONENT;
    COMPONENT flipflop
        PORT (  D, Resetn, Clock  : IN  STD_LOGIC;
                Q                 : OUT STD_LOGIC);
    END COMPONENT;

    TYPE State_type IS (T0, T1, T2, T3, T4, T5);
    SIGNAL Tstep_Q, Tstep_D: State_type;
    SIGNAL Sel : STD_LOGIC_VECTOR(3 DOWNTO 0); -- bus selector
    SIGNAL Rin : STD_LOGIC_VECTOR(0 TO 7); -- r0, ..., r7 register enables
    SIGNAL Sum : STD_LOGIC_VECTOR(15 DOWNTO 0);
    SIGNAL rXin, IRin, Done, ADDRin, DOUTin, Imm, Ain, Gin, AddSub, ALUand : STD_LOGIC;
    SIGNAL III, rX, rY : STD_LOGIC_VECTOR(2 DOWNTO 0);
    SIGNAL Xreg : STD_LOGIC_VECTOR(0 TO 7);
    SIGNAL r0, r1, r2, r3, r4, r5, r6, PC, A : STD_LOGIC_VECTOR(15 DOWNTO 0);
    SIGNAL G : STD_LOGIC_VECTOR(15 DOWNTO 0);
    SIGNAL IR, BusWires : STD_LOGIC_VECTOR(15 DOWNTO 0);
    signal take_branch, load_branch_pc, pc_write, z_flag, n_flag, c_flag : std_logic;
    signal wide_sum : unsigned(16 downto 0);
    SIGNAL pc_incr, W_D : STD_LOGIC;

    CONSTANT mv : STD_LOGIC_VECTOR(2 DOWNTO 0) := "000";
    CONSTANT mvt : STD_LOGIC_VECTOR(2 DOWNTO 0) := "001";
    CONSTANT add : STD_LOGIC_VECTOR(2 DOWNTO 0) := "010";
    CONSTANT sub : STD_LOGIC_VECTOR(2 DOWNTO 0) := "011";
    CONSTANT ld : STD_LOGIC_VECTOR(2 DOWNTO 0) := "100";
    CONSTANT st : STD_LOGIC_VECTOR(2 DOWNTO 0) := "101";
    CONSTANT and_it : STD_LOGIC_VECTOR(2 DOWNTO 0) := "110";
    -- selectors for the BusWires multiplexer
    CONSTANT SEL_R0 : STD_LOGIC_VECTOR(3 DOWNTO 0) := "0000";
    CONSTANT SEL_R1 : STD_LOGIC_VECTOR(3 DOWNTO 0) := "0001";
    CONSTANT SEL_R2 : STD_LOGIC_VECTOR(3 DOWNTO 0) := "0010";
    CONSTANT SEL_R3 : STD_LOGIC_VECTOR(3 DOWNTO 0) := "0011";
    CONSTANT SEL_R4 : STD_LOGIC_VECTOR(3 DOWNTO 0) := "0100";
    CONSTANT SEL_R5 : STD_LOGIC_VECTOR(3 DOWNTO 0) := "0101";
    CONSTANT SEL_R6 : STD_LOGIC_VECTOR(3 DOWNTO 0) := "0110";
    CONSTANT SEL_PC : STD_LOGIC_VECTOR(3 DOWNTO 0) := "0111";
    CONSTANT SEL_G : STD_LOGIC_VECTOR(3 DOWNTO 0) := "1000";
    CONSTANT SEL_IR8_IR8_0 : STD_LOGIC_VECTOR(3 DOWNTO 0) := "1001"; -- sign-extended #D
    CONSTANT SEL_IR7_0_0 : STD_LOGIC_VECTOR(3 DOWNTO 0) := "1010" ;  -- #D << 8
    CONSTANT SEL_DIN : STD_LOGIC_VECTOR(3 DOWNTO 0) := "1011" ;  -- data in
BEGIN
    III <= IR(15 DOWNTO 13);
    Imm <= IR(12);
    rX <= IR(11 DOWNTO 9);
    rY <= IR(2 DOWNTO 0);
    decX: dec3to8 PORT MAP (rXin, rX, Rin); -- produce r0 - r7 register enables

    statetable: PROCESS(Tstep_Q, Run, Done)
    BEGIN
        CASE Tstep_Q IS
            WHEN T0 =>    -- data is loaded into IR in this time step
                IF Run = '0' THEN Tstep_D <= T0;
                ELSE Tstep_D <= T1;
                END IF;
            WHEN T1 =>   -- some instructions end after this time step
                Tstep_D <= T2;
            WHEN T2 =>   -- always go to T3 after this
                Tstep_D <= T3;
            WHEN T3 =>   -- some instructions end after this time step
                IF Done = '1' THEN Tstep_D <= T0;
                ELSE Tstep_D <= T4;
                END IF;
            WHEN T4 =>   -- always go to T5 after this
                Tstep_D <= T5;
            WHEN T5 =>   -- always go to T3 after this
                Tstep_D <= T0;
        END CASE;
    END PROCESS;
    -- 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

    wide_sum <= ('0' & unsigned(A)) + ('0' & unsigned(BusWires));
    with rX select take_branch <=
        '1' when "000", z_flag when "001", not z_flag when "010",
        not c_flag when "011", c_flag when "100", not n_flag when "101",
        n_flag when "110", '0' when others;
    pc_write <= Rin(7) or load_branch_pc;
    process(Clock)
    begin
        if rising_edge(Clock) then
            if Resetn='0' then
                z_flag<='0'; n_flag<='0'; c_flag<='0';
            elsif Gin='1' and (III=add or III=sub or III=and_it) then
                if unsigned(Sum)=0 then z_flag<='1'; else z_flag<='0'; end if;
                n_flag<=Sum(15);
                if III=add then c_flag<=wide_sum(16);
                elsif III=sub then
                    if unsigned(A)>=unsigned(BusWires) then c_flag<='1'; else c_flag<='0'; end if;
                end if;
            end if;
        end if;
    end process;
    controlsignals: PROCESS (Tstep_Q, III, Imm, rX, rY, Run, take_branch)
    BEGIN
        -- default assignments
        rXin <= '0'; Ain <= '0'; Gin <= '0'; AddSub <= '0'; IRin <= '0'; Sel <= "----";
        ADDRin <= '0'; DOUTin <= '0'; W_D <= '0'; ALUand <= '0'; Done <= '0';
        load_branch_pc <= '0';
        pc_incr <= '0';
        CASE Tstep_Q IS
            WHEN T0 =>
                Sel <= SEL_PC;  -- put PC onto the internal bus
                ADDRin <= '1';
                pc_incr <= Run; -- increment PC
            WHEN T1 =>          -- wait cycle for synchronous memory
                null;
            WHEN T2 => -- store instruction on DIN into IR
                IRin <= '1';
            WHEN T3 => -- define signals in time step T1
                CASE III IS
                    WHEN mv =>
                        IF Imm = '0' THEN Sel <= '0' & rY;  -- mv rX, rY
                        ELSE Sel <= SEL_IR8_IR8_0;          -- mv rX, #D
                        END IF;
                        rXin <= '1';                        -- enable rX register
                        Done <= '1';
                    WHEN mvt =>
                        if Imm='1' then
                            Sel <= SEL_IR7_0_0; rXin <= '1'; Done <= '1';
                        else
                            Sel <= SEL_PC; Ain <= '1'; Done <= not take_branch;
                        end if;
                    WHEN add | sub | and_it =>
                        Sel <= '0' & rX; Ain <= '1';
                    WHEN ld | st =>
                        Sel <= '0' & rY; ADDRin <= '1';
                    WHEN OTHERS =>
                        null;
                END CASE;
            WHEN T4 => -- add the signed offset to the post-fetch PC
                CASE III IS
                    WHEN mvt => Sel <= SEL_IR8_IR8_0; Gin <= '1';
                    WHEN add =>
                        if Imm='1' then Sel <= SEL_IR8_IR8_0; else Sel <= '0' & rY; end if; Gin <= '1';
                    WHEN sub =>
                        if Imm='1' then Sel <= SEL_IR8_IR8_0; else Sel <= '0' & rY; end if; AddSub <= '1'; Gin <= '1';
                    WHEN and_it =>
                        if Imm='1' then Sel <= SEL_IR8_IR8_0; else Sel <= '0' & rY; end if; ALUand <= '1'; Gin <= '1';
                    WHEN ld =>
                        null;   -- wait cycle for synchronous memory
                    WHEN st =>
                        Sel <= '0' & rX; DOUTin <= '1'; W_D <= '1';
                    WHEN OTHERS =>
                        null;
                END CASE;
            WHEN T5 => -- commit the branch target
                CASE III IS
                    WHEN mvt => Sel <= SEL_G; load_branch_pc <= '1'; Done <= '1';
                    WHEN add | sub | and_it =>
                        Sel <= SEL_G; rXin <= '1'; Done <= '1';
                    WHEN ld =>
                        Sel <= SEL_DIN; rXin <= '1'; Done <= '1';
                    WHEN OTHERS =>
                        null;
                END CASE;
        END CASE;
    END PROCESS;

    fsmflipflops: PROCESS (Clock, Resetn, Tstep_D)
    BEGIN
        IF (Resetn = '0') THEN
            Tstep_Q <= T0;
        ELSIF (rising_edge(Clock)) THEN
            Tstep_Q <= Tstep_D;
        END IF;
    END PROCESS;

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

    -- pc_count(R, Resetn, Clock, E, L, Q);
    Upc: pc_count PORT MAP (BusWires, Resetn, Clock, pc_incr, pc_write, PC);

    reg_A:  regn PORT MAP (BusWires, Resetn, Ain, Clock, A);
    reg_ADDR: regn PORT MAP (BusWires, Resetn, ADDRin, Clock, ADDR);
    reg_DOUT: regn PORT MAP (BusWires, Resetn, DOUTin, Clock, DOUT);
    reg_IR: regn PORT MAP (DIN, Resetn, IRin, Clock, IR);

    reg_W: flipflop PORT MAP (W_D, Resetn, Clock, W);

    alu: PROCESS (AddSub, A, BusWires, ALUand)
    BEGIN
        IF ALUand = '0' THEN
            IF AddSub = '0' THEN
                Sum <= std_logic_vector(unsigned(A) + unsigned(BusWires));
            ELSE
                Sum <= std_logic_vector(unsigned(A) - unsigned(BusWires));
            END IF;
        ELSE
            Sum <= A AND BusWires;
        END IF;
    END PROCESS;

    reg_G: regn PORT MAP (Sum, Resetn, Gin, Clock, G);

    busmux: PROCESS (Sel, r0, r1, r2, r3, r4, r5, r6, PC, G, IR, DIN)
    BEGIN
        CASE Sel IS
            WHEN SEL_R0 => BusWires <= r0;
            WHEN SEL_R1 => BusWires <= r1;
            WHEN SEL_R2 => BusWires <= r2;
            WHEN SEL_R3 => BusWires <= r3;
            WHEN SEL_R4 => BusWires <= r4;
            WHEN SEL_R5 => BusWires <= r5;
            WHEN SEL_R6 => BusWires <= r6;
            WHEN SEL_PC => BusWires <= PC;
            WHEN SEL_G => BusWires <= G;
            WHEN SEL_IR8_IR8_0 => BusWires <= (15 DOWNTO 9 => IR(8)) & IR(8 DOWNTO 0);
            WHEN SEL_IR7_0_0 => BusWires <= IR(7 DOWNTO 0) & "00000000";
            WHEN SEL_DIN => BusWires <= DIN;
            WHEN OTHERS => BusWires <= (OTHERS => '0');
        END CASE;
    END PROCESS;
END Behavior;

LIBRARY ieee;
USE ieee.std_logic_1164.all;
USE ieee.numeric_std.all;

ENTITY pc_count IS
   PORT ( R   : IN  STD_LOGIC_VECTOR(15 DOWNTO 0);
          Resetn, Clock, E, L  : IN  STD_LOGIC;
          Q   : OUT STD_LOGIC_VECTOR(15 DOWNTO 0));
END pc_count;

ARCHITECTURE Behavior OF pc_count IS
   SIGNAL Count : STD_LOGIC_VECTOR(15 DOWNTO 0);
BEGIN
   PROCESS (Clock)
   BEGIN
      IF (Clock'EVENT AND Clock = '1') THEN
          IF (Resetn = '0') THEN
            Count <= (OTHERS => '0');
         ELSIF (L = '1') THEN
            Count <= R;
         ELSIF (E = '1') THEN
            Count <= std_logic_vector(unsigned(Count) + 1);
         END IF;
      END IF;
   END PROCESS;
   Q <= Count;
END Behavior;

LIBRARY ieee;
USE ieee.std_logic_1164.all;

ENTITY dec3to8 IS
    PORT ( E   : IN   STD_LOGIC;
           W   : IN   STD_LOGIC_VECTOR(2 DOWNTO 0);
           Y   : OUT  STD_LOGIC_VECTOR(0 TO 7));
END dec3to8;

ARCHITECTURE Behavior OF dec3to8 IS
BEGIN
    PROCESS (E, W)
    BEGIN
        IF E = '0'THEN
            Y <= "00000000";
        ELSE
            CASE W IS
                WHEN "000" => Y <= "10000000";
                WHEN "001" => Y <= "01000000";
                WHEN "010" => Y <= "00100000";
                WHEN "011" => Y <= "00010000";
                WHEN "100" => Y <= "00001000";
                WHEN "101" => Y <= "00000100";
                WHEN "110" => Y <= "00000010";
                WHEN "111" => Y <= "00000001";
                WHEN OTHERS => Y <= "00000000";
            END CASE;
        END IF;
    END PROCESS;
END Behavior;

LIBRARY ieee;
USE ieee.std_logic_1164.all;

ENTITY regn IS
    GENERIC ( n : INTEGER := 16);
    PORT ( R                   : IN  STD_LOGIC_VECTOR(n-1 DOWNTO 0);
           Resetn, E, Clock    : IN  STD_LOGIC;
           Q                   : OUT STD_LOGIC_VECTOR(n-1 DOWNTO 0));
END regn;

ARCHITECTURE Behavior OF regn IS
BEGIN
    PROCESS (Clock)
    BEGIN
        IF Clock'EVENT AND Clock = '1' THEN
            IF Resetn = '0' THEN
                Q <= (OTHERS => '0');
            ELSIF E = '1' THEN
                Q <= R;
            END IF;
        END IF;
    END PROCESS;
END Behavior;

library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

entity decimal_cpu is
    generic (ISSUE_BITS : positive := 14);
    port (CLOCK_50 : in std_logic; KEY : in std_logic_vector(3 downto 0);
          SW : in std_logic_vector(9 downto 0); LEDR : out std_logic_vector(9 downto 0);
          HEX0, HEX1, HEX2, HEX3, HEX4, HEX5 : out std_logic_vector(6 downto 0));
end entity;
architecture rtl of decimal_cpu is
    type ram_type is array(0 to 255) of std_logic_vector(15 downto 0);
    signal memory : ram_type := (
        -- BEGIN ASSEMBLED PROGRAM
        0 => x"3830",
        1 => x"8404",
        2 => x"D418",
        3 => x"220A",
        4 => x"7408",
        5 => x"2206",
        6 => x"7408",
        7 => x"2202",
        8 => x"11FE",
        9 => x"2005",
        10 => x"1063",
        11 => x"2003",
        12 => x"1009",
        13 => x"2001",
        14 => x"1000",
        15 => x"0200",
        16 => x"D2FF",
        17 => x"3A20",
        18 => x"5A04",
        19 => x"1C2F",
        20 => x"1405",
        21 => x"8806",
        22 => x"1600",
        23 => x"6204",
        24 => x"2602",
        25 => x"5601",
        26 => x"21FC",
        27 => x"4204",
        28 => x"1834",
        29 => x"4803",
        30 => x"8604",
        31 => x"A605",
        32 => x"7A01",
        33 => x"5C01",
        34 => x"7401",
        35 => x"25F1",
        36 => x"3830",
        37 => x"8404",
        38 => x"D407",
        39 => x"5401",
        40 => x"3202",
        41 => x"7201",
        42 => x"25FE",
        43 => x"7401",
        44 => x"25FB",
        45 => x"5001",
        46 => x"21E0",
        47 => x"2710",
        48 => x"03E8",
        49 => x"0064",
        50 => x"000A",
        51 => x"0001",
        52 => x"003F",
        53 => x"0006",
        54 => x"005B",
        55 => x"004F",
        56 => x"0066",
        57 => x"006D",
        58 => x"007D",
        59 => x"0007",
        60 => x"007F",
        61 => x"006F",
        -- END ASSEMBLED PROGRAM
        others => x"0000");
    signal address, write_data, read_data : std_logic_vector(15 downto 0);
    type segment_array is array(0 to 5) of std_logic_vector(6 downto 0);
    signal segments : segment_array;
    signal divider : unsigned(ISSUE_BITS-1 downto 0);
    signal run_one : std_logic;
    signal write_enable : std_logic;
begin
    HEX0 <= not segments(0);
    HEX1 <= not segments(1);
    HEX2 <= not segments(2);
    HEX3 <= not segments(3);
    HEX4 <= not segments(4);
    HEX5 <= not segments(5);
    -- Pace the start of an instruction. All registers use the board clock.
    run_one <= SW(9) when divider=(divider'range=>'1') else '0';
    process(CLOCK_50)
    begin
        if rising_edge(CLOCK_50) then
            if KEY(0)='0' then divider<=(others=>'0'); else divider<=divider+1; end if;
        end if;
    end process;
    core : entity work.proc port map(read_data, KEY(0), CLOCK_50, run_one, write_data,address,write_enable);
    process(CLOCK_50)
    begin
        if rising_edge(CLOCK_50) then
            if KEY(0)='0' then
                LEDR <= (others=>'0');
                segments <= (others=>(others=>'0'));
            end if;
            case address(15 downto 12) is
                when x"0" =>
                    read_data <= memory(to_integer(unsigned(address(7 downto 0))));
                    if write_enable='1' and KEY(0)='1' then memory(to_integer(unsigned(address(7 downto 0)))) <= write_data; end if;
                when x"1" =>
                    read_data <= (others=>'0');
                    if write_enable='1' and KEY(0)='1' then LEDR <= write_data(9 downto 0); end if;
                when x"2" =>
                    read_data <= (others=>'0');
                    if write_enable='1' and KEY(0)='1' and unsigned(address(11 downto 0)) < 6 then
                        segments(to_integer(unsigned(address(2 downto 0)))) <= write_data(6 downto 0);
                    end if;
                when x"3" => read_data <= "000000" & SW;
                when others => read_data <= (others=>'0');
            end case;
        end if;
    end process;
end architecture;
