Post on 19-Feb-2018
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 1/66
Universidade Federal de Santa Catarina
CTC - Centro Tecnológico
PPGEEL - Programa de Pós-Graduação em Engenharia Elétrica
EEL510231
Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
Projeto e implementação em VHDL para FPGAs de arquitetura para
execução de um conjunto reduzido de instruções do MIPS
Eduardo SchmidtMario Baldini
Romano Weirich
Florianópolis, Junho de 2015
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 2/66
Conteúdo
1 Introdução 1
2 Objetivos 1
3 Ferramentas Utilizadas 3
4 Desenvolvimento 3
4.1 Unidade Lógica e Aritmética (ULA) . . . . . . . . . . . . . . . . . . . . . . 4
4.2 Memória de programa (ROM) . . . . . . . . . . . . . . . . . . . . . . . . . 6
4.3 Extensor de sinal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
4.4 Memória de dados (RAM) . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
4.5 Bloco de controle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74.6 Bloco de controle da ULA . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
4.7 Bloco de controle do PC . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
4.8 Registrador . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
4.9 Multiplexador . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
4.10 Funções auxiliares . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
4.11 Assembler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
4.12 Simulação RTL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
4.13 Testes em hardware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
5 Anexos 15
5.1 Código-fonte do Assembler . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
5.2 Código-fonte em VHDL . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
5.2.1 mips_defns.vhd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
5.2.2 alu32.vhd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
5.2.3 alu_control.vhd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
5.2.4 control.vhd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
5.2.5 rom.vhd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
5.2.6 mux.vhd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
5.2.7 pc_control.vhd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
5.2.8 ram.vhd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
5.2.9 reg.vhd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
5.2.10 reg_bank.vhd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
5.2.11 sign_ext.vhd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
5.3 Resultados de Simulação . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 3/66
1 Introdução
Na disciplina de Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis (EEL510231),
ministrada no primeiro semestre de 2015 do Programa de Pós-Graduação em Engenha-
ria Elétrica pelo professor Eduardo Bezerra, foram estudados os conceitos de dispositivos
lógicos reconfiguráveis (ie. FPGA), como são implementados no nível de hardware e as
ferramentas (linguagens e softwares) utilizados para configurá-los.
Além das aulas expositivas, foi proposto um trabalho prático, para que os conceitos
vistos em aula fossem implementados pelos alunos em um hardware real (Altera Cyclone
II).
O objetivo do projeto final é a implementação em FPGA de um microprocessador
baseado na arquitetura MIPS multiciclo, contendo um subconjunto das instruções e fun-
cionalidades da versão apresentada no livro Computer Organization and Design: TheHardware/Software Interface, de David A. Patterson.
2 Objetivos
Este trabalho tem por objetivo o projeto, o modelamento em VHDL e a implementação
em FPGA de um conjunto reduzido de instruções do MIPS. Mais especificamente, deve-
ser projetada uma arquitetura MIPS que esteja de acordo com a arquitetura descrita no
Apêndice A de [1], considerando o conjunto reduzido de instruções a seguir:
• Addition (with overflow) – add rd, rs, rt
• Addition immediate (with overflow) – addi rt, rs, imm
• AND – and rd, rs, rt
• AND immediate – andi rt, rs, imm
•
NOR – nor rd, rs, rt
• OR – or rd, rs, rt
• OR immediate – ori rd, rs, imm
• Shift left logical – sll rd, rt, shamt
• Shift left logical variable – sllv rd, rt, rs
• Shift right arithmetic – sra rd, rt, shamt
• Shift right arithmetic variable – srav rd, rt, rs
1
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 4/66
• Shift right logical – srl rd, rt, shamt
• Shift right logical variable – srlv rd, rt, rs
• Subtract (with overflow) – sub rd, rs, rt
• Exclusive OR – xor rd, rs, rt
• Exclusive OR immediate – xori rt, rs, imm
• Set less than – slt rd, rs, rt
• Set less than immediate – slti rd, rs, imm
• Branch on equal – beq rs, rt, label
• Branch on greater than zero – bgtz rs, label
• Branch on less than zero – bltz rs, label
• Branch on not equal – bne rs, rt, label
• Jump – j target
• Load word – lw rt, address
• Store word – sw rt, address
Deve-se modelar a arquitetura em VHDL, visando a síntese em FPGAs e eemons-
trar seu funcionamento por intermédio da execução de um programa nas plataformas de
desenvolvimento disponíveis no laboratório (Altera DE2).
Observações:
Utilizar como base a arquitetura MIPS multiciclo definida no livro do David A. Pat-
terson e John L. Hennessy, Computer Organization and Design: The Hardware/Software
Interface.Informações sobre o projeto dos blocos de dados e controle, foram discutidas nas aulas
da disciplina, com base nos slides 1 a 29 do capítulo 4 do livro do Patterson.
Definir uma faixa de endereços de memória para mapear, pelo menos, uma porta de
entrada e uma porta de saída de 8 bits cada. Essas portas representam, por exemplo, 8
chaves (entrada) e 8 LEDs (saída) do kit de desenvolvimento.
Desenvolver um programa de teste, e executá-lo na arquitetura projetada. Esse pro-
grama de teste deve realizar algum processamento útil, sendo necessário consultar previ-
amente o professor da disciplina sobre a validade do algoritmo selecionado.
2
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 5/66
O programa de testes deve ser escrito em Assembly, e o código binário para as instru-
ções deverá ser gerado pela ferramenta SPIM (ver pg. A-38 do Appendix A).
A entrega/apresentação do trabalho será nos dias 15/julho (ou em data anterior a ser
combinada entre aluno e professor).Preparar uma documentação completa descrevendo a arquitetura do sistema, ferra-
mentas utilizadas, e todos os componentes do VHDL. Descrever também o procedimento
necessário para o desenvolvimento de programas para o microprocessador, incluindo deta-
lhes sobre a definição dos conteúdos das memórias de dados e endereços. A documentação
é parte fundamental da avaliação, e deverá ser preparada de forma a possibilitar futuras
alterações no projeto.
3 Ferramentas Utilizadas
As atividades foram realizadas em três fases: desenvolvimento, simulação e implemen-
tação no hardware.
Foi utilizada a linguagem VHDL (VHSIC Hardware Description Language) para des-
crever o hardware desenvolvido. Como o hardware alvo escolhido foi a FPGA Cyclone
II, do fabricante Altera, obrigatoriamente foi necessário a utilização do software Quartus
para compilação do VHDL e geração da bitstream a ser gravada na FPGA. Esta falta
de opção de escolha das ferramentas de compilação e geração de bitstream é um fator
limitante dos fluxos de trabalho com FPGAs. Como estes dispositivos empregam técnicas
proprietárias de fabricação e a bitstream gerada é altamente atrelada ao hardware, seu
processo de compilação também não é divulgado. Então um desenvolvedor tem pouca fle-
xibilidade quanto a escolha da ferramenta de compilação, estando limitado às oferecidas
pelo fabricante do componente de hardware.
Tipo Ferramenta Versão
Hardware alvo FPGA Cyclone II EP2C35F672C6N
(Dev. Kit Altera DE2)Compilador/Sintetisador Altera Quartus II 15.0.1 - build 150
Simulador Modelsim Altera Starter Edition 10.3d
Gerenciador de código fonte Git 2.1.4
4 Desenvolvimento
A partir do estudo de caso apresentado em [1] e das aulas da disciplina, foi construído
um diagrama do datapath do processador MIPS para ser utilizado como referência no
desenvolvimento deste trabalho. O diagrama pode ser visto na Figura 1, e os componentes
3
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 6/66
presentes no mesmo são descritos em detalhe nesta seção. O código em VHDL utilizado
na descrição dos mesmos pode ser consultado na seção Anexos, ao fim deste documento.
Figura 1: Datapath utilizado como referência neste trabalho
4.1 Unidade Lógica e Aritmética (ULA)
Responsável por realizar as operações lógicas e aritméticas listadas na Tabela 1 e
necessárias para a execução de cada uma das instruções do instruction set . Configurada
por um sinal de controle a ALU define os operandos, sua ordem e a operação à ser
realizada entre eles. O bloco possui duas saídas: uma referente ao resultado da operação,
um sinalizador de zero, e um sinalizador de overflow para as operações add e sub.
Figura 2: Diagrama entrada-saída ULA
4
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 7/66
Tabela 1: Lista de operações suportadas pela ALU.type/opcode alu_op instruction funct operation alu_fcn meaning of operationI/35d 0000 lw xxxxxx add 0000 $t = M($s + i)
I/43d 0000 sw xxxxxx add 0000 M($s + i) = $sI/4d 0001 beq xxxxxx subtract 0001 ($s = $t)? pc += iI/5d 0010 bne xxxxxx = 0? 0010 ($s = $t)? pc += iI/6d 0011 blez xxxxxx > 0? 0011 ($s > 0)? pc += iI/7d 0101 bgtz xxxxxx <= 0? 0100 ($s <= 0)? pc += iR/0d 0101 add 100000 add 0000 $d = $s + $tR/0d 0101 sub 100010 subtract 0001 $d = $s - $tR/0d 0101 and 100100 and 0101 $d = $s & $tR/0d 0101 or 100101 or 0110 $d = $s | $tR/0d 0101 nor 100111 nor 0111 $d = ($s | $t)R/0d 0101 slt 101010 < ? 1001 $d = ($s < $t)R/0d 0101 xor 100110 xor 1000 $d = $s $tR/0d 0101 sll 000000 sll 1010 $d = $t « shamtR/0d 0101 sllv 000100 sll 1010 $d = $t « $sR/0d 0101 sra 000011 sra 1011 $d = $t » shamtR/0d 0101 srav 000111 sra 1011 $d = $t » $sR/0d 0101 srl 000010 srl 1100 $d = $t »> shamtR/0d 0101 srlv 000110 srl 1100 $d = $t »> $sI/12d 0110 andi xxxxxx and 0101 $d = $s & SE(i)I/13d 0110 ori xxxxxx or 0110 $d = $s | SE(i)I/14d 0110 xori xxxxxx xor 1000 $d = $s SE(i)
I/8d 0110 addi xxxxxx add 0000 $d = $s + SE(i)I/10d 0110 slti xxxxxx < ? 1001 $d = ($s < SE(i))J/2d xxxx j xxxxxx x xxxx pc = SE(j)
Um desafio de projeto foi manter a generalidade do hardware gerado para a ALU
ao verificar-se ordens diferentes de operandos em operações não comutativas para al-
guns casos de instruções do tipo R. Ao realizar-se uma verificação criteriosa do problema
verificou-se os casos em esse problema ocorria: instruções de deslocamento que utilizavam
o valor do campo shamt . Verificou-se também que para as demais instruções do tipo R o
valor de shamt é 0, de forma que o próprio sinal pode ser utilizado para decidir a ordem
dos operandos.
Adicionalmente, a verificação da condição de desvio é determinada pela ALU. É pos-
sível reaproveitar o sinalizador de zero para determinar se o desvio deve ser tomado adici-
onando um conjunto de operação à ALU. Nesse contexto, as operações greater than zero,
less than zero, e equal? foram incluídas. Estas operações, ao serem realizadas quando das
instruções blez , bgtz , e bne respectivamente, fazem com que o flag Z fique ativo caso as
condições de desvio sejam satisfeitas.
Por fim, vale destacar que para permitir a execução de instruções do tipo I e do tipo
5
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 8/66
R pela mesma ALU, um multiplexador externo foi adicionado em uma de suas entradas,
de forma que a mesmoa pudesse receber o valor da saída 2 do banco de registradores ou
o valor do campo imediato da instrução, com o sinal estendido.
4.2 Memória de programa (ROM)
A memória de programa é responsável por armazenar as instruções a serem executadas
pelo processador. Optou-se por utilizar uma memória com 256 posições, cada qual com
32 bits, de forma que fosse possível armazenar programas relativamente complexos e ao
mesmo tempo simplificar a obtenção das instruções, uma vez que o tamanho de cada
posição da ROM coincide com o tamanho das instruções do programa.
Figura 3: Diagrama entrada-saída da memória ROM
4.3 Extensor de sinal
Para fazer com que todos os sinais tenham 32 bits, foram utilizados dois extensores,
conforme mostra a Figura 1. Os extensores preenchem com 0s ou 1s o sinal de entrada,
dependendo do sinal do mesmo, de forma que o sinal de saída possua 32 bits. Foram
utilizados dois extensores para os campos imediatos das instruções do tipo I e J.
Figura 4: Diagrama entrada-saída do extensor de sinal
6
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 9/66
4.4 Memória de dados (RAM)
Responsável por permitir a escrita e leitura de informações pelo processador através
das instruções lw e sw . Foi utilizada uma memória de 1024 posições, cada qual com 32
bits, totalizando 4KB. Além do acesso normal pelo processador, uma posição da memória
RAM (addr = 0 ) é também mapeada para uma saída específica do bloco ( fixed_out ),
de forma que o processador possa se comunicar com o mundo exterior através da escrita
nesse endereço (por exemplo, para acender LEDs ou controlar algum periférico).
Figura 5: Diagrama entrada-saída da memória RAM
4.5 Bloco de controle
Responsável por coordenar o funcionamento dos demais blocos funcionais do proces-
sador, sendo responsável por interpretar as instruções do programa assim que as mesmas
são carregadas da memória, e gerar os sinais adequados em todos os estágios de execução
das mesmas. Neste trabalho, a arquitetura MIPS multiciclo foi adotada para a imple-
mentação do processador. Isso quer dizer que a execução de uma instrução ocupa mais
de um ciclo do sinal de clock. O diagrama de transição de estados da FSM que gerencia
os sinais de controle do sistema é apresentada na Figura 7.
Uma análise rápida na Figura 7 mostra que instruções do tipo R, instruções do tipoI e a instrução sw demoram quatro ciclos para serem executadas; instruções de desvio
(condicional e incondicional) levam três ciclos; e a instrução lw, cinco.
As saídas de cada estado dependem do estado atual, do estado anterior e de três
campos que compõe a instrução sendo executada: op_code, shamt e funct.
4.6 Bloco de controle da ULA
Bloco responsável por informar à ALU qual deve ser a operação a ser realizada. Para
isso, são utilizados um sinal de controle derivado do opcode da instrução, o campo funct
7
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 10/66
Figura 6: Diagrama entrada-saída do bloco de controle
Figura 7: Máquina de estados da unidade de controle.
e o próprio opcode . Assim como o bloco de controle do PC, optou-se por projetar o bloco
de controle da ALU como um circuito puramente combinacional;
4.7 Bloco de controle do PC
Responsável por determinar o próximo endereço a ser carregado no registrador Program
counter , ou seja, qual será a próxima instrução a ser executada. As situações possíveis
incluem a passagem para a instrução imediatamente a seguir, o desvio incondicional para
8
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 11/66
Figura 8: Diagrama entrada-saída do bloco de controle da ULA
um endereço absoluto da memória, e um desvio para um endereço relativo, a ser somado ao
valor atual do PC. Estas últimas situações devem ser sinalizadas pelo bloco de controle
através de sinais apropriados. Optou-se por projetar o bloco de controle do PC como
sendo um circuito puramente combinacional, que a cada instante disponibiliza na saída o
valor a ser carregado no PC no próximo ciclo de clock ;
Figura 9: Diagrama entrada-saída do bloco de controle do PC
4.8 Registrador
Utilizado para implementar o PC (program counter , este componente armazena osinal de entrada a cada borda de subida do clock , e também o disponibiliza na saída do
dispositivo. Ao receber um sinal de reset , o valor armazenado é descartado.
4.9 Multiplexador
Responsável por realizar a seleção de um entre dois sinais. Como este é um dispositivo
recorrente na arquitetura, e que pode possuir entradas de dimensões variáveis, as mesmas
foram especificadas com dimensões genéricas, de forma a permitir a reutilização da mesma
entidade para a síntese de componentes diferentes.
9
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 12/66
Figura 10: Diagrama entrada-saída do registrador
Figura 11: Diagrama entrada-saída do multiplexador
4.10 Funções auxiliares
Para implementar shifts arbitrários de forma puramente combinacional, foram utili-
zadas funções auxiliares (shift_left_logical , shift_right_logical , shift_right_arithmetic ).
Cada uma destas funções utiliza 32 multiplexadores com 32 entradas às quais é conectado
o sinal original. O seletor de cada multiplexador (5 bits), é conectado ao sinal que repre-
senta o número de shifts a serem aplicados. As funções mencionadas foram implementadas
no arquivo mips_defns.vhd , disponível no Anexo deste documento.
4.11 AssemblerA bitstream gerada que foi gravada na FPGA possui um banco de memória que con-
tém as instruções do programa a ser executado. Tal programa foi inserido no arquivo
VHDL a partir de um arquivo externo que contém as instruções já em formato binário.
TYPE mem_type IS ARRAY (0 to 31) OF SIGNED(31 DOWNTO 0);
IMPURE FUNCTION init_mem(mif_file_name : IN STRING) RETURN mem_type IS
10
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 13/66
FILE mif_file : TEXT OPEN read_mode IS mif_file_name;
VARIABLE mif_line : LINE;
VARIABLE temp_bv : BIT_VECTOR(31 DOWNTO 0);
VARIABLE temp_mem : mem_type;
BEGIN
FOR i IN mem_type’RANGE LOOP
readline(mif_file, mif_line);
read(mif_line, temp_bv);
temp_mem(i) := signed(to_stdlogicvector(temp_bv));
END LOOP;
RETURN temp_mem;
END FUNCTION;
CONSTANT rom : mem_type := init_mem("mips_rom.mif");
Listing 1: Código usado para carregar ROM a partir de arquivo externo.
O código que será carregado na ROM é o código de máquina, em formato binário.
Assim sendo, é necessário realizar a compilação do programa da linguagem de programação
(assembly) para o binário de máquina. Isto pode ser realizado com ferramentas difundidas,
como o simulador SPIM, por exemplo.
Contudo, este simulador não permite exportar de maneira prática as instruções com-
piladas em código de máquina para um arquivo externo, que seria carregado na ROM.Então foi desenvolvido um assembler para realizar esta compilação. O mesmo foi
construido na linguagem Python. Suas funcionalidades principais são:
• Receber um arquivo de entrada em Assembly.
• Analisar a sintaxe do arquivo de entrada e filtrar instruções válidas (removendo
comentários e trechos não relevantes).
• Montar a instrução em formado binário, a partir da representação em assembly.
• Identificar labels ao longo do código fonte e resolver suas referências, montando as
instruções em binário com a posição de memória indicada pela label (em relação ao
arquivo de saída)
• Exportar o resultado para um arquivo compatível com o processo de carregamento
da ROM.
$ ./assembler.py conta5.asm
Listing 2: Comando para utilização do Assembler desenvolvido.
11
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 14/66
O formato do arquivo de entrada segue o padrão da linguagem Assembly tradicional,
sendo constituída por:
• Uma instrução por linha.
• Comentários precedidos de "#".
• Labels precedendo instrucoes, terminados em ":".
# prog exemplo 1
# conta ate 5, com loop
reset: addi $t1, $zero, 5
add $t2, $zero, $zero
inicio: addi $t2, $t2, 1bne $t2, $t1, inicio
fim: j fim #halt
Listing 3: Arquivo em linguagem assembly para o processador implementado.
Serão gerados três arquivos de saída equivalentes:
• Arquivo MIF Padrão de descrição de memórias adotado pelo Quartus II. Amostra:
DEPTH = 32; −− The size of memory in words
WIDTH = 32; −− The size of data in bits
ADDRESS_RADIX = HEX; −− The radix for address values
DATA_RADIX = BIN; −− The radix for data values
CONTENT −− start of (address : data pairs)
BEGIN
00 : 00000000000000000100100000100000;
01 : 00100001001010010000000000000001;
02 : 00100001001010010000000000000001;
03 : 00100001001010010000000000000001;
END
• Arquivo BIN Arquivo com instruções no formato de máquina, em binário. Este é
o arquivo que foi utilizado nos testes de carregamento da ROM. Amostra:
00000000000000000100100000100000
00100001001010010000000000000001
00100001001010010000000000000001
00100001001010010000000000000001
00100001001010010000000000000001
00100001001010010000000000000001
12
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 15/66
• Arquivo HEX Equivalente ao arquivo BIN, porém em formato hexadecimal. Serve
para facilitar a verificação do código de máquina gerado pelo assembler com outras
ferramentas de compilação (eg. SPIM). Amostra:
00004820
21290001
21290001
21290001
21290001
21290001
4.12 Simulação RTL
Inicialmente, a descrição de hardware referemte a cada bloco foi testada individual-mente através de simulações à nivel RTL. Posteriormente, esses blocos foram integrados
através do arquivo que implementa o datapath do MIPS. Realizou-se um procedimento ite-
rativo, envolvendo diversas configurações do hardware e a evecução de diversas instruções
diferentes. Cada erro no comportamento esperado no top level , gerava uma etapa verifi-
cação e correção nos arquivos de baixo nível. Os resultados individuais e do processador
completo são apresentados no Apêndice 5.3
4.13 Testes em hardware
Após a verificação do funcionamento do processador utilizando a ferramenta Model-
Sim, foram realizados testes na placa Altera DE2 disponível no laboratório. Nesses testes
foram utilizadas chaves para as entradas clk , rst e en , enquanto que endereços específicos
da memória RAM foram mapeados em LEDs e displays de 7 segmentos.
13
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 16/66
Referências
[1] Livro do Patterson.
14
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 17/66
5 Anexos
5.1 Código-fonte do Assembler
Este Assembler gera código de máquina compatível com o MIPS, contudo não suportatodo o conjunto de instruções, apenas aquelas definidas no escopo deste trabalho. O
suporte a outras instruções pode ser feito inserindo as mesmas nas entidades de *map (eg.
opcodemap, functmap, etc) e seus respectivos valores em representação binária (código
de máquina.
#!/usr/bin/python2.7
#coding=utf8
from sys import argv
def asm2bitstream_R(op, rs, rt, rd, shamt, funct):
# OPCODE REG, REG, REG
# OP RS RT RD SHAMT FUNCT
# 6 5 5 5 5 6
bs = ""
bs += opmap.get( op )
if isinstance(rs, str):
bs += regmap.get( rs )
else:
bs += "00000"
bs += regmap.get( rt )
bs += regmap.get( rd )
bs += str(’{0:05b}’.format(shamt))
bs += functmap.get( op )
return bs
def asm2bitstream_I(op, rs, rt_rd, imm, inst_pos):
# OPCODE REG, REG, IMM
# OP RS RT/RD IMM
# 6 5 5 16
bs = ""
bs += opmap.get( op )
if (op == "lw" or op == "sw"):
bs += "00000"
else:
15
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 18/66
bs += regmap.get( rs )
bs += regmap.get( rt_rd )
if isinstance(imm, int):
if (imm < 0):
# offset_comp2 = twos_comp(offset, 16)
bs += bin(imm % (1<<16))[2:]
else:
bs += str(’{0:016b}’.format( imm ))
elif isinstance(imm, str): #imm in hex
if (imm[:2] == "0x"): # imm is hex value (sw/lw)
# print "addr int value:", int(imm, 16)
# print "addr bin16 value:", str(’{0:016b}’.format( int(imm,
16) ))
bs += str(’{0:016b}’.format( int(imm, 16) ))
else: # imm is label (beq, bne)
# print "addr atual:", inst_pos, "base (pc+1):", inst_pos+1
# print "branch ppra addr:", labelmap.get(imm)
offset = labelmap.get(imm) − (inst_pos+1)
# offset_comp2 = bin(offset % (1<<16))
# offset = −3
if (offset < 0):
# offset_comp2 = twos_comp(offset, 16)
offset_comp2 = bin(offset % (1<<16))[2:]
else:
offset_comp2 = str(’{0:016b}’.format( offset ))
# print "offset:", offset, "comp2:", offset_comp2
bs += offset_comp2
return bs
def asm2bitstream_J(op, target):
# OPCODE TARG
# 6 26
bs = ""
bs += opmap.get( op )
16
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 19/66
bs += str(’{0:026b}’.format( labelmap.get( target )+1 ))
return bs
def bitstream2hex(bsin):
bsout = ""
# bsout += "0x"
bsin = bsin.strip()
for i in range(0,32,4):
bscut = bsin[i:i+4]
bscuthex = hex(int(bscut, 2))[2:]
bsout += bscuthex
return bsout
def twos_comp(val, bits):
if (val & (1 << (bits − 1))) != 0: # if sign bit is set e.g., 8bit:
128−255
val = val − (1 << bits) # compute negative value
return val # return positive value as is
print ’+−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+’
print ’| EEL510231 − 2015/01 |’
print ’| Trabalho Final |’
print ’| Assembler ASM −> Altera MIF |’
print ’| Alunos: Eduardo Fensterseifer |’
print ’| Mario Baldini |’
print ’| Romano Weirich |’
print ’| Prof.: Eduardo Bezerra |’
print ’+−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+’
# SUPPORTED SYNTAX
# (regarding EEL510231 class; not full mips inst set )
# OPCODE REG, REG, REG
# OP RS RT RD 0 FUNCT
# 6 5 5 5 5 6
# Addition (with overflow) − add rd, r s, r t
17
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 20/66
# AND − and rd, r s, r t
# NOR − nor rd, r s, r t
# OR − or rd, rs, rt
# Subtract (with overflow) − sub rd, r s, r t
# Exclusive OR − xor rd, r s, r t
# Set less than − slt rd, r s, r t
syntaxMap_R_op_rd_rs_rt = ["add", "and", "nor", "or", "sub", "xor", "slt"]
# Shift left logical variable − sllv rd, rt, rs
# Shift right arithmetic variable − srav rd, rt, rs
# Shift right logical variable − srlv rd, rt, rs
syntaxMap_R_op_rd_rt_rs = ["sllv", "srav", "srlv"]
# OPCODE, REG, REG, SHIFTAMOUNT
# OP RS RT RD SHAMT FUNCT
# 6 5 5 5 5 6
# Shift right arithmetic − sra rd, rt, shamt
# Shift left logical − sll rd, rt, shamt
# Shift right logical − srl rd, rt, shamt
syntaxMap_R_op_rd_rt_shamt = ["sra", "sll", "srl"]
# OPCODE REG, REG, IMMEDIATE
# OP RS RT/RD IMM
# 6 5 5 16
# Addition immediate (w overflow) − addi rt, rs, imm
# AND immediate − andi rt, rs, imm
# OR immediate − ori rt, r s, i mm site: o ri rd, r s,
imm
# Exclusive OR immediate − xori rt, rs, imm
# Set less than immediate − slti rd, rs, imm
syntaxMap_I_op_rtd_rs_imm = ["addi", "andi", "ori", "xori", "slti"]
# OPCODE REG, REG, LABEL
# OP Rs Rt Offset
# 6 5 5 16
18
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 21/66
# Branch on equal − beq rs, rt, label
# Branch on not equal − bne rs, rt, label site/livro errado:
bne rs, label
syntaxMap_I_op_rs_rt_label = ["beq", "bne"]
# OPCODE, REG, REG, LABEL
# OP rs rt Offset
# 6 5 5 16
# # Branch on not equal − bne rs, rt, label site/livro errado
: b ne rs, l abel
# syntaxMap_I_op_rs_rt_label = ["bne"]
# OPCODE, REG, LABEL
# OP rs 0 Offset
# 6 5 5 16
# Branch on greater than zero − bgtz rs, label
# Branch on less than zero − bltz rs, label
syntaxMap_I_op_rs_label = ["bgtz", "bltz", "bne"]
# OPCODE REG, ADDRESS
# OP rs rt Offset
# 6 5 5 16
# Load word − lw rt, address
# Store word − sw rt, address
syntaxMap_I_op_rt_address = ["lw", "sw"]
# OPCODE ADDRESS
# OP target
# 6 26
# Jump − j target
syntaxMap_J_op_target = ["j"]
19
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 22/66
opmap = { "add" : "000000", # R
"addi" : "001000", # I 0x08
"and" : "000000", # R
"andi" : "001100", # I 0x0c
"nor" : "000000", # R
"or" : "000000", # R
"ori" : "001101", # I 0x0d
"sll" : "000000", # R
"sllv" : "000000", # R
"sra" : "000000", # R
"srav" : "000000", # R
"srl" : "000000", # R
"srlv" : "000000", # R
"sub" : "000000", # R
"xor" : "000000", # R
"xori" : "001110", # I 0x0e
"slt" : "000000", # R
"slti" : "001010", # I 0x0a
"beq" : "000100", # I 0x04
"bgtz" : "000111", # I 0x07
"bltz" : "000001", # I 0x01
"bne" : "000101", # I 0x05
"j" : "000010", # J 0x02
"lw" : "100011", # I 0x23
"sw" : "101011" # I 0 x2b
}
functmap = { "add" : "100000",
"and" : "100100",
"nor" : "100111",
"or" : "100101",
"sll" : "000000",
"sllv" : "000100",
"sra" : "000011",
"srav" : "000111",
"srl" : "000010",
"srlv" : "000110",
"sub" : "100010",
20
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 23/66
"xor" : "100110",
"slt" : "101010"
}
regmap = { "$zero" : "00000",
"$at" : "00001",
"$v0" : "00010",
"$v1" : "00011",
"$a0" : "00100",
"$a1" : "00101",
"$a2" : "00110",
"$a3" : "00111",
"$t0" : "01000",
"$t1" : "01001",
"$t2" : "01010",
"$t3" : "01011",
"$t4" : "01100",
"$t5" : "01101",
"$t6" : "01110",
"$t7" : "01111",
"$s0" : "10000",
"$s1" : "10001",
"$s2" : "10010",
"$s3" : "10011",
"$s4" : "10100",
"$s5" : "10101",
"$s6" : "10110",
"$t7" : "10111",
"$t8" : "11000",
"$t9" : "11001",
"$k0" : "11010",
"$k1" : "11011",
"$gp" : "11100",
"$sp" : "11101",
"$fp" : "11110",
"$ra" : "11111"
}
if (len(argv) != 2):
21
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 24/66
print ’Usage:’
print argv[0], ’input−file.asm’
print "Ex: ./assembler.py conta5.asm"
raise SystemExit(0)
# type rom_array is array (0 to 4) of bit_vector(31 downto 0);
# function init_mem(rom_file_name : in string) return rom_array is
# file rom_file : text open read_mode is rom_file_name;
# variable rom_line : line;
# variable temp_rom : rom_array;
# begin
# for i in rom_array’range loop
# readline(rom_file, rom_line);
# read(rom_line, temp_rom(i));
# end loop;
# return temp_rom;
# end function;
# constant memoria : rom_array := init_mem("romcode.hex");
inputFilename = argv[1]
outputFilenameMIF = argv[1][:−3] + "mif"
outputFilenameBIN = argv[1][:−3] + "bin"
outputFilenameHEX = argv[1][:−3] + "hex"
print ’Compilando:’, inputFilename
print ’Arquivo de saida:’, outputFilenameMIF, "(Quartus memory) e",
outputFilenameBIN, "(bin)", outputFilenameBIN, "(hex)"
print ’−−−−−−−−−− OUTPUT −−−−−−−−−−−−−−−’
# fin = open(inputFilename, ’r’)
# Feito em 3 passagens por legibilidade. Poderia ser em 2.
# 1st pass
with open (inputFilename, "r") as inFile:
data_raw=inFile.readlines()
# print data_raw
instructions = []
labelmap = {}
22
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 25/66
for i in range(0, len(data_raw)):
line = data_raw[i].strip() #remove espacos vazios (trim) e \n do
final
if (line != "" and line[0] != "#" ):
# so processa instrucoes, ignora comentarios e linhas vazias
print "Analisando linha:", line
# Se encontrar label, salva posicao para segunda passagem
line_splited = line.split()
if (line_splited[0][−1] == ":"):
labelmap[line_splited[0][:−1]] = len(instructions)
instructions.append(line_splited[1:])
else:
instructions.append(line_splited)
print ’−−−−−−−−−−−−−−−−−−−−−−’
print ’Instrucoes validas encontradas:’, instructions
print ’Labels validas encontradas:’, labelmap
print ’−−−−−−−−−−−−−−−−−−−−−−’
print ’Gerando bitstream...’
#2nd pass
bitstring_raw = ""
bitstring_raw += "00000000000000000000000000000000\n" # fix fetcher:
program starts at address 1
bitstring_hex = ""
bitstring_hex += "00000000\n" # fix fetcher: program starts at address 1
bitstring = ""
bitstring += "DEPTH = 32; −− The size of memory in words\
n"
bitstring += "WIDTH = 32; −− The size of data in bits\n"
bitstring += "ADDRESS_RADIX = HEX; −− The radix for address values
\n"
bitstring += "DATA_RADIX = BIN; −− The radix for data values\n"
bitstring += "CONTENT −− start of (address : data
pairs)\n"
bitstring += "BEGIN\n"
bitstring += "\n"
bitstring += "00 : 00000000000000000000000000000000;\n" # fix fetcher:
program starts at address 1
23
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 26/66
for i in range(0, len(instructions)):
# opcode = instructions[i][0:3]
inst_slice = instructions[i]
# print "PARSING:", inst_slice
bitstring_inst = ""
bitstring_inst += str(i+1).zfill(2) + " : "
if inst_slice[0] in syntaxMap_R_op_rd_rs_rt:
op = inst_slice[0]
rd = inst_slice[1][:−1]
rs = inst_slice[2][:−1]
rt = inst_slice[3]
bitstring_inst += asm2bitstream_R(op, rs, rt, rd, 0, op)
elif inst_slice[0] in syntaxMap_R_op_rd_rt_rs:
op = inst_slice[0]
rd = inst_slice[1][:−1]
rt = inst_slice[2][:−1]
rs = inst_slice[3]
bitstring_inst += asm2bitstream_R(op, rs, rt, rd, 0, op)
elif inst_slice[0] in syntaxMap_R_op_rd_rt_shamt:
op = inst_slice[0]
rd = inst_slice[1][:−1]
rt = inst_slice[2][:−1]
shamt = inst_slice[3]
# print "op",op
# print "rd",rd
# print "rt",rt
# print "shamt",shamt
bitstring_inst += asm2bitstream_R(op, −1, rt, rd, int(shamt), op)
elif inst_slice[0] in syntaxMap_I_op_rtd_rs_imm:
op = inst_slice[0]
24
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 27/66
rtd = inst_slice[1][:−1]
rs = inst_slice[2][:−1]
imm = inst_slice[3]
bitstring_inst += asm2bitstream_I(op, rs, rtd, int(imm), i)
elif inst_slice[0] in syntaxMap_I_op_rs_rt_label:
op = inst_slice[0]
rs = inst_slice[1][:−1]
rt = inst_slice[2][:−1]
label = inst_slice[3]
bitstring_inst += asm2bitstream_I(op, rs, rt, label, i)
elif inst_slice[0] in syntaxMap_I_op_rs_label:
op = inst_slice[0]
rs = inst_slice[1][:−1]
label = inst_slice[3]
bitstring_inst += asm2bitstream_I(op, rs, 0, label, i)
elif inst_slice[0] in syntaxMap_I_op_rs_rt_label:
op = inst_slice[0]
rs = inst_slice[1][:−1]
rt = inst_slice[2][:−1]
label = inst_slice[3]
bitstring_inst += asm2bitstream_I(op, rs, rt, label, i)
elif inst_slice[0] in syntaxMap_I_op_rt_address:
op = inst_slice[0]
rt = inst_slice[1][:−1]
address = inst_slice[2]
# print "syntax sw"
# print "OP", op
# print "RT", rt
# print "addr", address
25
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 28/66
bitstring_inst += asm2bitstream_I(op, rt, rt, address, i)
elif inst_slice[0] in syntaxMap_J_op_target:
op = inst_slice[0]
target = inst_slice[1]
bitstring_inst += asm2bitstream_J(op, target )
else:
print "ERRO! Instrucao desconhecida!", inst_slice[0]
print inst_slice
raise SystemExit(0)
bitstring_raw += bitstring_inst[4:].strip()
# print "bitstring_raw+=", bitstring_inst[4:].strip()
bitstring_hex += bitstream2hex(bitstring_inst[4:])
# print "bitstring_hex+=", bitstream2hex(bitstring_inst[4:])
bitstring_raw += "\n"
bitstring_hex += "\n"
bitstring_inst += ";\n"
bitstring += bitstring_inst
print inst_slice, "\r\t\t\t\t\t\t=>\t", bitstring_inst,
bitstring += "\n"
bitstring += "END"
bitstring += "\n"
if (len(instructions) < 256):
padding = 256 − len(instructions)
print "Padding output binary file to 256 lines"
for i in range(0, padding):
bitstring_raw += "00000000000000000000000000000000\n"
26
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 29/66
# escreve codigo processado no arquivo de saida
fout1 = open(outputFilenameMIF, ’w’)
fout1.write( bitstring )
fout1.close()
fout2 = open(outputFilenameBIN, ’w’)
fout2.write( bitstring_raw )
fout2.close()
fout2 = open(outputFilenameHEX, ’w’)
fout2.write( bitstring_hex )
fout2.close()
5.2 Código-fonte em VHDL
5.2.1 mips_defns.vhd
LIBRARY IEEE;
USE IEEE.STD_LOGIC_1164. ALL;
USE IEEE.NUMERIC_STD. ALL;
USE IEEE.STD_LOGIC_UNSIGNED. ALL;
PACKAGE MIPS_DEFNS IS
FUNCTION shift_left_logical (input : STD_LOGIC_VECTOR(31 DOWNTO 0); shamt
: STD_LOGIC_VECTOR(4 DOWNTO 0)) return STD_LOGIC_VECTOR;
FUNCTION shift_right_logical (input : STD_LOGIC_VECTOR(31 DOWNTO 0);
shamt : STD_LOGIC_VECTOR(4 DOWNTO 0)) return STD_LOGIC_VECTOR;
FUNCTION shift_right_arith (input : STD_LOGIC_VECTOR(31 DOWNTO 0); shamt
: STD_LOGIC_VECTOR(4 DOWNTO 0)) return STD_LOGIC_VECTOR;
−−−−−−−−−−−−−−−−−−−−
−− Opcodes −−
−−−−−−−−−−−−−−−−−−−−
−− R−type instructions
CONSTANT any_R_type_opcode : STD_LOGIC_VECTOR(5 DOWNTO 0) := "000000";
−−−−−−−−−−−−−−−−−−−−
−− ALU Functions −−
−−−−−−−−−−−−−−−−−−−−
−− Arithmetic
CONSTANT add_fcn : STD_LOGIC_VECTOR(3 DOWNTO 0) := "0000"; −− add, addi
27
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 30/66
CONSTANT sub_fcn : STD_LOGIC_VECTOR(3 DOWNTO 0) := "0001"; −− sub, beq
CONSTANT eq_fcn : STD_LOGIC_VECTOR(3 DOWNTO 0) := "0010"; −− bne
CONSTANT gtz_fcn : STD_LOGIC_VECTOR(3 DOWNTO 0) := "0100"; −− bgtz
CONSTANT ltz_fcn : STD_LOGIC_VECTOR(3 DOWNTO 0) := "0011"; −− bltz
−− Logic
CONSTANT and_fcn : STD_LOGIC_VECTOR(3 DOWNTO 0) := "0101"; −− and, andi
CONSTANT or_fcn : STD_LOGIC_VECTOR(3 DOWNTO 0) := "0110"; −− or, ori
CONSTANT xor_fcn : STD_LOGIC_VECTOR(3 DOWNTO 0) := "1000"; −− xor, xori
CONSTANT nor_fcn : STD_LOGIC_VECTOR(3 DOWNTO 0) := "0111"; −− nor
CONSTANT slt_fcn : STD_LOGIC_VECTOR(3 DOWNTO 0) := "1001"; −− slt, slti
−− Bitwise shift
CONSTANT sll_fcn : STD_LOGIC_VECTOR(3 DOWNTO 0) := "1010"; −− sll, sllv
CONSTANT srl_fcn : STD_LOGIC_VECTOR(3 DOWNTO 0) := "1100"; −− srl, srlv
CONSTANT sra_fcn : STD_LOGIC_VECTOR(3 DOWNTO 0) := "1011"; −− sra, srav
−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
−− Func(R) or opcode(I,J) values −−
−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
−− Implemented instructions
CONSTANT add_code : STD_LOGIC_VECTOR(5 DOWNTO 0) := "100000"; −−
CONSTANT addi_code : STD_LOGIC_VECTOR(5 DOWNTO 0) := "001000"; −−
CONSTANT and_code : STD_LOGIC_VECTOR(5 DOWNTO 0) := "100100"; −−
CONSTANT andi_code : STD_LOGIC_VECTOR(5 DOWNTO 0) := "001100"; −−
CONSTANT nor_code : STD_LOGIC_VECTOR(5 DOWNTO 0) := "100111"; −−
CONSTANT or_code : STD_LOGIC_VECTOR(5 DOWNTO 0) := "100101"; −−
CONSTANT ori_code : STD_LOGIC_VECTOR(5 DOWNTO 0) := "001101"; −−
CONSTANT sll_code : STD_LOGIC_VECTOR(5 DOWNTO 0) := "000000"; −−
CONSTANT sllv_code : STD_LOGIC_VECTOR(5 DOWNTO 0) := "000100"; −−
CONSTANT sra_code : STD_LOGIC_VECTOR(5 DOWNTO 0) := "000011"; −−
CONSTANT srav_code : STD_LOGIC_VECTOR(5 DOWNTO 0) := "000111"; −−
CONSTANT srl_code : STD_LOGIC_VECTOR(5 DOWNTO 0) := "000010"; −−
CONSTANT srlv_code : STD_LOGIC_VECTOR(5 DOWNTO 0) := "000110"; −−
CONSTANT sub_code : STD_LOGIC_VECTOR(5 DOWNTO 0) := "100010"; −−
CONSTANT xor_code : STD_LOGIC_VECTOR(5 DOWNTO 0) := "100110"; −−
CONSTANT xori_code : STD_LOGIC_VECTOR(5 DOWNTO 0) := "001110"; −−
CONSTANT slt_code : STD_LOGIC_VECTOR(5 DOWNTO 0) := "101010"; −−
CONSTANT slti_code : STD_LOGIC_VECTOR(5 DOWNTO 0) := "001010"; −−
CONSTANT beq_code : STD_LOGIC_VECTOR(5 DOWNTO 0) := "000100"; −−
CONSTANT bgtz_code : STD_LOGIC_VECTOR(5 DOWNTO 0) := "000111"; −−
CONSTANT blez_code : STD_LOGIC_VECTOR(5 DOWNTO 0) := "000110"; −−
28
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 31/66
CONSTANT bne_code : STD_LOGIC_VECTOR(5 DOWNTO 0) := "000101"; −−
CONSTANT j_code : STD_LOGIC_VECTOR(5 DOWNTO 0) := "000010"; −−
CONSTANT lw_code : STD_LOGIC_VECTOR(5 DOWNTO 0) := "100011"; −−
CONSTANT sw_code : STD_LOGIC_VECTOR(5 DOWNTO 0) := "101011"; −−
−− Instructions not yet implemented
CONSTANT mfhi_code : STD_LOGIC_VECTOR(5 DOWNTO 0) := "010000";
CONSTANT mflo_code : STD_LOGIC_VECTOR(5 DOWNTO 0) := "010010";
CONSTANT mthi_code : STD_LOGIC_VECTOR(5 DOWNTO 0) := "010001";
CONSTANT mtlo_code : STD_LOGIC_VECTOR(5 DOWNTO 0) := "010011";
CONSTANT trap_code : STD_LOGIC_VECTOR(5 DOWNTO 0) := "011010";
CONSTANT sb_code : STD_LOGIC_VECTOR(5 DOWNTO 0) := "101000";
CONSTANT sh_code : STD_LOGIC_VECTOR(5 DOWNTO 0) := "101001";
CONSTANT jal_code : STD_LOGIC_VECTOR(5 DOWNTO 0) := "000011";
CONSTANT jalr_code : STD_LOGIC_VECTOR(5 DOWNTO 0) := "001001";
CONSTANT jr_code : STD_LOGIC_VECTOR(5 DOWNTO 0) := "001000";
CONSTANT lb_code : STD_LOGIC_VECTOR(5 DOWNTO 0) := "100000";
CONSTANT lbu_code : STD_LOGIC_VECTOR(5 DOWNTO 0) := "100100";
CONSTANT lh_code : STD_LOGIC_VECTOR(5 DOWNTO 0) := "100001";
CONSTANT lhu_code : STD_LOGIC_VECTOR(5 DOWNTO 0) := "100101";
CONSTANT sltiu_code : STD_LOGIC_VECTOR(5 DOWNTO 0) := "001001";
CONSTANT sltu_code : STD_LOGIC_VECTOR(5 DOWNTO 0) := "101001";
CONSTANT lhi_code : STD_LOGIC_VECTOR(5 DOWNTO 0) := "011001";
CONSTANT llo_code : STD_LOGIC_VECTOR(5 DOWNTO 0) := "011000";
CONSTANT subu_code : STD_LOGIC_VECTOR(5 DOWNTO 0) := "100011";
CONSTANT addiu_code : STD_LOGIC_VECTOR(5 DOWNTO 0) := "001001";
CONSTANT addu_code : STD_LOGIC_VECTOR(5 DOWNTO 0) := "100001";
CONSTANT div_code : STD_LOGIC_VECTOR(5 DOWNTO 0) := "011010";
CONSTANT divu_code : STD_LOGIC_VECTOR(5 DOWNTO 0) := "011011";
CONSTANT mult_code : STD_LOGIC_VECTOR(5 DOWNTO 0) := "011000";
CONSTANT multu_code : STD_LOGIC_VECTOR(5 DOWNTO 0) := "011001";
END MIPS_DEFNS;
PACKAGE BODY MIPS_DEFNS IS
FUNCTION shift_left_logical (input : STD_LOGIC_VECTOR(31 DOWNTO 0); shamt :
STD_LOGIC_VECTOR(4 DOWNTO 0)) return STD_LOGIC_VECTOR IS
VARIABLE shifted : STD_LOGIC_VECTOR(31 DOWNTO 0) := x"00000000";
VARIABLE i : INTEGER := 0;
BEGIN
FOR i IN 0 TO 31 LOOP
IF(i + conv_integer(shamt) <= 31) THEN
shifted(i + conv_integer(shamt)) := input(i);
29
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 32/66
END IF;
END LOOP;
RETURN shifted;
END shift_left_logical;
FUNCTION shift_right_logical (input : STD_LOGIC_VECTOR(31 DOWNTO 0); shamt
: STD_LOGIC_VECTOR(4 DOWNTO 0)) return STD_LOGIC_VECTOR IS
VARIABLE shifted : STD_LOGIC_VECTOR(31 DOWNTO 0) := x"00000000";
VARIABLE i : INTEGER := 0;
BEGIN
FOR i IN 0 TO 31 LOOP
IF(i − conv_integer(shamt) >= 0) THEN
shifted(i − conv_integer(shamt)) := input(i);
END IF;
END LOOP;
RETURN shifted;
END shift_right_logical;
FUNCTION shift_right_arith (input : STD_LOGIC_VECTOR(31 DOWNTO 0); shamt :
STD_LOGIC_VECTOR(4 DOWNTO 0)) return STD_LOGIC_VECTOR IS
VARIABLE shifted : STD_LOGIC_VECTOR(31 DOWNTO 0) := x"00000000";
VARIABLE i : INTEGER := 0;
BEGIN
IF(shifted(31) = ’1’) THEN
shifted := x"FFFFFFFF";
END IF;
FOR i IN 0 TO 31 LOOP
IF(i − conv_integer(shamt) >= 0) THEN
shifted(i − conv_integer(shamt)) := input(i);
END IF;
END LOOP;
RETURN shifted;
END shift_right_arith;
END MIPS_DEFNS;
5.2.2 alu32.vhd
LIBRARY IEEE;
USE IEEE.STD_LOGIC_UNSIGNED. ALL;
USE IEEE.NUMERIC_STD. ALL;
30
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 33/66
USE IEEE.STD_LOGIC_1164. ALL;
USE WORK.MIPS_DEFNS. ALL;
ENTITY alu32 IS
PORT (
input1, input2 : IN STD_LOGIC_VECTOR (31 DOWNTO 0);
alu_fcn : IN STD_LOGIC_VECTOR(3 DOWNTO 0);
shamt : IN STD_LOGIC_VECTOR (4 DOWNTO 0);
output : OUT STD_LOGIC_VECTOR (31 DOWNTO 0);
−− ALU Flags
zero : OUT STD_LOGIC;
overflow : OUT STD_LOGIC
);
END ENTITY alu32;
ARCHITECTURE behav OF alu32 IS
SIGNAL res33 : STD_LOGIC_VECTOR (32 DOWNTO 0);
SIGNAL res : STD_LOGIC_VECTOR (31 DOWNTO 0);
SIGNAL zero_signal : STD_LOGIC;
SIGNAL overflow_signal : STD_LOGIC;
BEGIN
PROCESS(input1, input2, shamt, alu_fcn, res, res33)
BEGIN
overflow_signal <= ’0’;
CASE alu_fcn IS
WHEN add_fcn =>
res33 <= (input1(31) & input1) + (input2(31) & input2);
res <= res33(31 DOWNTO 0);
IF res33(32) = res33(31) THEN
overflow_signal <= ’0’;
ELSE
overflow_signal <= ’1’;
END IF;
WHEN sub_fcn =>
res33 <= (input1(31) & input1) − (input2(31) & input2);
31
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 34/66
res <= res33(31 DOWNTO 0);
IF res33(32) = res33(31) THEN
overflow_signal <= ’0’;
ELSE
overflow_signal <= ’1’;
END IF;
WHEN eq_fcn =>
IF input1 = input2 THEN
res <= x"00000001";
ELSE
res <= x"00000000";
END IF;
WHEN gtz_fcn =>
IF input1 > x"00000000" THEN
res <= x"00000000";
ELSE
res <= x"00000001";
END IF;
WHEN ltz_fcn =>
IF input1 < x"00000000" THEN
res <= x"00000000";
ELSE
res <= x"00000001";
END IF;
WHEN and_fcn =>
res <= input1 AND input2;
WHEN or_fcn =>
res <= input1 OR input2;
WHEN nor_fcn =>
res <= input1 NOR input2;
WHEN xor_fcn =>
res <= input1 XOR input2;
WHEN slt_fcn =>
IF input1 < input2 THEN
res <= x"00000001";
ELSE
res <= x"00000000";
32
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 35/66
END IF;
WHEN sll_fcn =>
IF(shamt = "00000") THEN
IF unsigned(input1) > 31 THEN
res <= x"00000000";
ELSE
res <= shift_left_logical(input2,input1(4 DOWNTO 0));
END IF;
ELSE
res <= shift_left_logical(input2,shamt);
END IF;
WHEN srl_fcn =>
IF(shamt = "00000") THEN
IF unsigned(input1) > 31 THEN
res <= x"00000000";
ELSE
res <= shift_right_logical(input2,input1(4 DOWNTO 0));
END IF;
ELSE
res <= shift_right_logical(input2,shamt);
END IF;
WHEN sra_fcn =>
IF(shamt = "00000") THEN
IF unsigned(input1) > 31 AND input2(31)=’0’ THEN
res <= x"00000000";
ELSIF unsigned(input1) > 31 AND input2(31)=’1’ THEN
res <= x"FFFFFFFF";
ELSE
res <= shift_right_arith(input2, input1(4 DOWNTO 0));
END IF;
ELSE
res <= shift_right_arith(input2, shamt);
END IF;
WHEN OTHERS =>
res <= x"00000000";
END CASE;
IF res = x"00000000" THEN
zero <= ’1’;
ELSE
zero <= ’0’;
33
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 36/66
END IF;
END PROCESS;
overflow <= overflow_signal;
output <= res;
END ARCHITECTURE behav;
5.2.3 alu_control.vhd
LIBRARY IEEE;
USE IEEE.STD_LOGIC_1164. ALL;
USE IEEE.STD_LOGIC_UNSIGNED. ALL;
USE WORK.MIPS_DEFNS. ALL;
ENTITY alu_control IS
PORT (
alu_op : IN STD_LOGIC_VECTOR(3 DOWNTO 0);
funct : IN STD_LOGIC_VECTOR(5 DOWNTO 0);
opcode : IN STD_LOGIC_VECTOR(5 DOWNTO 0);
alu_fcn : OUT STD_LOGIC_VECTOR(3 DOWNTO 0)
);
END ENTITY alu_control;
ARCHITECTURE behav OF alu_control IS
BEGIN
PROCESS(alu_op,funct,opcode)
BEGIN
CASE alu_op IS
WHEN "0000" =>
alu_fcn <= add_fcn;
WHEN "0001" =>
alu_fcn <= sub_fcn;
WHEN "0010" =>
alu_fcn <= eq_fcn;
WHEN "0100" =>
alu_fcn <= gtz_fcn;
WHEN "0011" =>
alu_fcn <= ltz_fcn;
34
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 37/66
−− since the opcode is not useful to discriminate between
operations (opcode=000000)
−− alu fcn must be chosen according to the funct field,
WHEN "0101" =>
IF funct="100000" THEN
alu_fcn <= add_fcn;
ELSIF funct="100010" THEN
alu_fcn <= sub_fcn;
ELSIF funct="100100" THEN
alu_fcn <= and_fcn;
ELSIF funct="100101" THEN
alu_fcn <= or_fcn;
ELSIF funct="100111" THEN
alu_fcn <= nor_fcn;
ELSIF funct="101010" THEN
alu_fcn <= slt_fcn;
ELSIF funct="100110" THEN
alu_fcn <= xor_fcn;
ELSIF funct="000000" THEN
alu_fcn <= sll_fcn;
ELSIF funct="000100" THEN
alu_fcn <= sll_fcn;
ELSIF funct="000011" THEN
alu_fcn <= sra_fcn;
ELSIF funct="000111" THEN
alu_fcn <= sra_fcn;
ELSIF funct="000010" THEN
alu_fcn <= srl_fcn;
ELSIF funct="000110" THEN
alu_fcn <= srl_fcn;
END IF;
−− alu fcn given by the opcode field, since there is no funct
−− field (its slot is being used by the immediate field)
WHEN "0110" =>
IF opcode="001100" THEN
alu_fcn <= and_fcn;
ELSIF opcode="001101" THEN
alu_fcn <= or_fcn;
ELSIF opcode="001110" THEN
alu_fcn <= xor_fcn;
ELSIF opcode="001000" THEN
alu_fcn <= add_fcn;
ELSIF opcode="001010" THEN
35
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 38/66
alu_fcn <= slt_fcn;
END IF;
WHEN OTHERS =>
alu_fcn <= "1111";
END CASE;
END PROCESS;
END ARCHITECTURE behav;
5.2.4 control.vhd
LIBRARY IEEE;
USE IEEE.STD_LOGIC_1164. ALL;
USE IEEE.STD_LOGIC_UNSIGNED. ALL;
USE WORK.MIPS_DEFNS. ALL;
ENTITY control IS
PORT (
rst, clk : IN STD_LOGIC;
−− Opcode of the instruction loaded from memory
opcode : IN STD_LOGIC_VECTOR(5 DOWNTO 0);
−− ALU operation control
alu_op : OUT STD_LOGIC_VECTOR(3 DOWNTO 0);
−− PC increment control
branch : OUT STD_LOGIC;
jump : OUT STD_LOGIC;
pc_enable_inc : OUT STD_LOGIC;
−− Data memory control
mem_read : OUT STD_LOGIC;
mem_write : OUT STD_LOGIC;
−− Register bank control
reg_write : OUT STD_LOGIC;
−− Mux control (selects)
mem_to_reg : OUT STD_LOGIC;
alu_src : OUT STD_LOGIC;
reg_dst : OUT STD_LOGIC;
error : OUT STD_LOGIC
);
END ENTITY control;
ARCHITECTURE behav OF control IS
TYPE control_state IS (idle, fetch, read_reg, op_alu, access_mem,
writeback);
36
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 39/66
SIGNAL prev_state : control_state;
SIGNAL curr_state : control_state;
SIGNAL next_state : control_state;
BEGIN
−− State machine transitions process
PROCESS(clk,rst)
BEGIN
IF(rst =’0’) THEN
curr_state <= idle;
ELSIF(rising_edge(clk)) THEN
prev_state <= curr_state;
curr_state <= next_state;
END IF;
END PROCESS;
−− States process
PROCESS(curr_state)
BEGIN
CASE curr_state IS
−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
−− IDLE −−
−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
WHEN idle =>
reg_dst <= ’0’;
branch <= ’0’;
jump <= ’0’;
mem_to_reg <= ’0’;
alu_op <= "0000";
mem_write <= ’0’;
mem_read <= ’0’;
alu_src <= ’0’;
reg_write <= ’0’;
pc_enable_inc <= ’0’;
error <= ’0’;
next_state <= fetch;
−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
−− FETCH INSTRUCTION −−
−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
WHEN fetch =>
37
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 40/66
−− If we’re coming from a branch/jump, we dont want to let
−− PC be incremented before the instruction is executed
IF prev_state = op_alu THEN
pc_enable_inc <= ’0’;
ELSE
pc_enable_inc <= ’1’;
END IF;
reg_dst <= ’0’;
branch <= ’0’;
jump <= ’0’;
mem_to_reg <= ’0’;
alu_op <= "0000";
mem_write <= ’0’;
mem_read <= ’0’;
alu_src <= ’0’;
reg_write <= ’0’;
error <= ’0’;
next_state <= read_reg;
−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
−− READ REGISTERS −−
−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
WHEN read_reg =>
pc_enable_inc <= ’0’; −− Disable PC increments
reg_dst <= ’0’; −− reg_dst is set in the writeback state
branch <= ’0’;
jump <= ’0’;
mem_to_reg <= ’0’;
alu_op <= "0000";
mem_write <= ’0’;
mem_read <= ’0’;
alu_src <= ’0’;
reg_write <= ’0’;
error <= ’0’;
next_state <= op_alu;
−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
−− PERFORM ALU OPERATION −−
38
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 41/66
−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
WHEN op_alu =>
IF opcode = lw_code OR opcode = sw_code THEN
alu_op <= "0000";
reg_dst <= ’0’; −− will be set on writeback
branch <= ’0’;
jump <= ’0’;
mem_to_reg <= ’0’;
mem_write <= ’0’;
mem_read <= ’0’;
alu_src <= ’1’; −− so that we have $s and imm as alu
ops
reg_write <= ’0’;
pc_enable_inc <= ’0’;
error <= ’0’;
next_state <= access_mem;
ELSIF opcode = beq_code THEN
pc_enable_inc <= ’0’;
reg_dst <= ’0’;
branch <= ’1’;
jump <= ’0’;
mem_to_reg <= ’0’;
alu_op <= "0001";
mem_write <= ’0’;
mem_read <= ’0’;
alu_src <= ’0’;
reg_write <= ’0’;
error <= ’0’;
next_state <= fetch;
ELSIF opcode = bne_code THEN
pc_enable_inc <= ’0’;
reg_dst <= ’0’;
branch <= ’1’;
jump <= ’0’;
mem_to_reg <= ’0’;
alu_op <= "0010";
mem_write <= ’0’;
mem_read <= ’0’;
alu_src <= ’0’;
reg_write <= ’0’;
39
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 42/66
error <= ’0’;
next_state <= fetch;
ELSIF opcode = blez_code THEN
pc_enable_inc <= ’0’;
reg_dst <= ’0’;
branch <= ’1’;
jump <= ’0’;
mem_to_reg <= ’0’;
alu_op <= "0100";
mem_write <= ’0’;
mem_read <= ’0’;
alu_src <= ’0’;
reg_write <= ’0’;
error <= ’0’;
next_state <= fetch;
ELSIF opcode = bgtz_code THEN
pc_enable_inc <= ’0’;
reg_dst <= ’0’;
branch <= ’1’;
jump <= ’0’;
mem_to_reg <= ’0’;
alu_op <= "0011";
mem_write <= ’0’;
mem_read <= ’0’;
alu_src <= ’0’;
reg_write <= ’0’;
error <= ’0’;
next_state <= fetch;
ELSIF opcode = any_R_type_opcode THEN
pc_enable_inc <= ’0’;
reg_dst <= ’0’;
branch <= ’0’;
jump <= ’0’;
mem_to_reg <= ’0’;
alu_op <= "0101";
mem_write <= ’0’;
mem_read <= ’0’;
alu_src <= ’0’;
reg_write <= ’0’;
40
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 43/66
error <= ’0’;
next_state <= writeback;
ELSIF opcode = andi_code OR
opcode = ori_code OR
opcode = xori_code OR
opcode = addi_code OR
opcode = slti_code THEN
pc_enable_inc <= ’0’;
reg_dst <= ’0’;
branch <= ’0’;
jump <= ’0’;
mem_to_reg <= ’0’;
alu_op <= "0110";
mem_write <= ’0’;
mem_read <= ’0’;
alu_src <= ’1’;
reg_write <= ’0’;
error <= ’0’;
next_state <= writeback;
ELSIF opcode = j_code THEN
pc_enable_inc <= ’0’;
reg_dst <= ’0’;
branch <= ’0’;
jump <= ’1’;
mem_to_reg <= ’0’;
alu_op <= "0000";
mem_write <= ’0’;
mem_read <= ’0’;
alu_src <= ’0’;
reg_write <= ’0’;
error <= ’0’;
next_state <= fetch;
ELSE
pc_enable_inc <= ’0’;
reg_dst <= ’0’;
branch <= ’0’;
jump <= ’0’;
mem_to_reg <= ’0’;
alu_op <= "0000";
41
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 44/66
mem_write <= ’0’;
mem_read <= ’0’;
alu_src <= ’0’;
reg_write <= ’0’;
error <= ’1’;
next_state <= idle; −− if next_state = idle and rst = 1
something went wrong
END IF;
−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
−− ACCESS MEMORY −−
−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
WHEN access_mem =>
pc_enable_inc <= ’0’;
reg_dst <= ’0’;
branch <= ’0’;
jump <= ’0’;
mem_to_reg <= ’0’;
alu_op <= "0000";
reg_write <= ’0’;
error <= ’0’;
IF opcode = lw_code THEN
alu_src <= ’1’;
mem_read <= ’1’;
mem_write <= ’0’; −− just for safety
next_state <= writeback;
ELSIF opcode = sw_code THEN
alu_src <= ’1’;
mem_read <= ’0’; −− just for safety
mem_write <= ’1’;
next_state <= fetch;
ELSE
alu_src <= ’0’;
mem_read <= ’0’;
mem_write <= ’0’;
next_state <= idle;
42
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 45/66
END IF;
−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
−− WRITEBACK −−
−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
WHEN writeback =>
pc_enable_inc <= ’0’;
branch <= ’0’;
jump <= ’0’;
alu_op <= "0000";
IF opcode = any_R_type_opcode THEN
alu_src <= ’0’;
ELSE
alu_src <= ’1’;
END IF;
reg_write <= ’1’;
mem_read <= ’1’; −− just for safety
mem_write <= ’0’;
error <= ’0’;
IF opcode = lw_code THEN
reg_dst <= ’0’;
mem_to_reg <= ’1’;
ELSIF opcode = any_R_type_opcode THEN
reg_dst <= ’1’;
mem_to_reg <= ’0’;
ELSE
reg_dst <= ’0’;
mem_to_reg <= ’0’;
END IF;
next_state <= fetch;
WHEN OTHERS =>
reg_dst <= ’0’;
branch <= ’0’;
jump <= ’0’;
mem_to_reg <= ’0’;
alu_op <= "0000";
mem_write <= ’0’;
mem_read <= ’0’;
43
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 46/66
alu_src <= ’0’;
reg_write <= ’0’;
pc_enable_inc <= ’0’;
error <= ’1’;
next_state <= idle;
END CASE;
END PROCESS;
END ARCHITECTURE behav;
5.2.5 rom.vhd
LIBRARY IEEE;
USE IEEE.STD_LOGIC_1164. ALL;
USE IEEE.STD_LOGIC_UNSIGNED. ALL;
USE IEEE.NUMERIC_STD. ALL;
USE STD.TEXTIO. ALL;
ENTITY rom_mips IS
PORT (
clk : IN STD_LOGIC;
rst : IN STD_LOGIC;
en : IN STD_LOGIC;
rd : IN STD_LOGIC;
addr : IN STD_LOGIC_VECTOR(31 DOWNTO 0);
output : OUT STD_LOGIC_VECTOR(31 DOWNTO 0)
);
END ENTITY rom_mips;
ARCHITECTURE behav OF rom_mips IS
TYPE mem_type IS ARRAY (0 to 255) OF SIGNED(31 DOWNTO 0);
−− ROM content must be hardcoded here!
CONSTANT rom : mem_type := (
0 => "00000000000000000000000000000000",
1 => "00000000000000000100100000100000",
2 => "00000000000000000101000000100000",
3 => "00100000000010010000000000000001",
4 => "00100000000010100000000000000010",
5 => "10101100000010010000000000000000",
44
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 47/66
6 => "10101100000010100000000000000000",
7 => "00001000000000000000000000000101",
OTHERS => "00000000000000000000000000111111");
BEGIN
PROCESS(clk,rst)
BEGIN
IF rst = ’0’ THEN
output <= "ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ";
ELSIF rising_edge(clk) THEN
IF (en = ’1’) THEN
IF (rd = ’1’) THEN
output <= std_logic_vector(rom(conv_integer(addr)));
ELSE
output <= std_logic_vector(rom(conv_integer(addr)));
END IF;
END IF;
END IF;
END PROCESS;
END ARCHITECTURE behav;
5.2.6 mux.vhd
LIBRARY IEEE;
USE IEEE.STD_LOGIC_1164. ALL;
USE IEEE.STD_LOGIC_UNSIGNED. ALL;
ENTITY mux_mips IS
GENERIC (SIG_WIDTH : POSITIVE := 8);
PORT (
input1, input2 : IN STD_LOGIC_VECTOR(SIG_WIDTH−1 DOWNTO 0);
sel : IN STD_LOGIC;
output : OUT STD_LOGIC_VECTOR(SIG_WIDTH−1 DOWNTO 0)
);
END ENTITY mux_mips;
ARCHITECTURE behav OF mux_mips IS
BEGIN
PROCESS(input1, input2, sel)
BEGIN
IF sel = ’0’ THEN
output <= input1;
45
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 48/66
ELSE
output <= input2;
END IF;
END PROCESS;
END ARCHITECTURE behav;
5.2.7 pc_control.vhd
LIBRARY IEEE;
USE IEEE.STD_LOGIC_SIGNED. ALL;
USE IEEE.STD_LOGIC_1164. ALL;
ENTITY pc_control IS
PORT (
curr_pc : IN STD_LOGIC_VECTOR(31 DOWNTO 0);
branch_addr : IN STD_LOGIC_VECTOR(31 DOWNTO 0);
jump_addr : IN STD_LOGIC_VECTOR(31 DOWNTO 0);
pc_inc_en : IN STD_LOGIC;
jump : IN STD_LOGIC;
branch : IN STD_LOGIC;
zero : IN STD_LOGIC;
next_pc : OUT STD_LOGIC_VECTOR(31 DOWNTO 0)
);
END ENTITY pc_control;
ARCHITECTURE behav OF pc_control IS
BEGIN
PROCESS(curr_pc, pc_inc_en, jump, branch, zero)
BEGIN
IF jump = ’1’ THEN
next_pc <= jump_addr;
ELSIF branch = ’1’ AND zero = ’1’ THEN
next_pc <= (curr_pc + 1 + branch_addr);
ELSIF pc_inc_en = ’1’ THEN
next_pc <= curr_pc + 1;
ELSE
next_pc <= curr_pc;
END IF;
END PROCESS;
46
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 49/66
END ARCHITECTURE behav;
5.2.8 ram.vhd
LIBRARY IEEE;
USE IEEE.STD_LOGIC_1164. ALL;
USE IEEE.STD_LOGIC_UNSIGNED. ALL;
ENTITY ram IS
GENERIC (NWORDS : POSITIVE := 512; WORDLEN : POSITIVE := 32);
PORT (
clk : IN std_logic;
en : IN std_logic;
rd : IN std_logic;
wr : IN std_logic;
write_data : IN std_logic_vector(WORDLEN−1 DOWNTO 0);
addr : IN std_logic_vector(WORDLEN−1 DOWNTO 0);
fixed_out : OUT STD_LOGIC_VECTOR(WORDLEN−1 DOWNTO 0);
output : OUT std_logic_vector(WORDLEN−1 DOWNTO 0)
);
END ENTITY ram;
ARCHITECTURE behav OF ram IS
TYPE ram_t IS ARRAY (0 TO NWORDS−1) OF STD_LOGIC_VECTOR(WORDLEN−1 DOWNTO
0);
SIGNAL ram : ram_t;
BEGIN
fixed_out <= ram(0);
PROCESS(clk)
BEGIN
IF rising_edge(clk) THEN
IF wr = ’1’ THEN
ram(conv_integer(addr)) <= write_data;
ELSIF rd = ’1’ THEN
output <= ram(conv_integer(addr));
END IF;
END IF;
47
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 50/66
END PROCESS;
END ARCHITECTURE behav;
5.2.9 reg.vhd
LIBRARY IEEE;
USE IEEE.STD_LOGIC_1164. ALL;
USE IEEE.STD_LOGIC_UNSIGNED. ALL;
ENTITY reg IS
GENERIC (NBITS : POSITIVE := 8);
PORT (
clk : IN STD_LOGIC;
rst : IN STD_LOGIC;
en : IN STD_LOGIC;
input : IN STD_LOGIC_VECTOR(NBITS−1 DOWNTO 0);
output : OUT STD_LOGIC_VECTOR(NBITS−1 DOWNTO 0)
);
END ENTITY reg;
ARCHITECTURE behav OF reg IS
BEGIN
PROCESS(clk,rst)
BEGIN
IF rising_edge(clk) THEN
IF rst = ’0’ THEN
output <= (OTHERS => ’0’);
ELSIF e n = ’1’ THEN
output <= input;
END IF;
END IF;
END PROCESS;
END ARCHITECTURE behav;
5.2.10 reg_bank.vhd
48
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 51/66
LIBRARY IEEE;
USE IEEE.STD_LOGIC_1164. ALL;
USE IEEE.STD_LOGIC_UNSIGNED. ALL;
USE IEEE.NUMERIC_STD. ALL;
USE WORK.MIPS_DEFNS. ALL;
ENTITY reg_bank IS
PORT (
idx_reg1 : IN STD_LOGIC_VECTOR(4 DOWNTO 0);
idx_reg2 : IN STD_LOGIC_VECTOR(4 DOWNTO 0);
idx_write_reg : IN STD_LOGIC_VECTOR(4 DOWNTO 0);
write_data : IN STD_LOGIC_VECTOR(31 DOWNTO 0);
clk : IN STD_LOGIC;
rst : IN STD_LOGIC;
reg_write : IN STD_LOGIC;
data_reg1 : OUT STD_LOGIC_VECTOR(31 DOWNTO 0);
data_reg2 : OUT STD_LOGIC_VECTOR(31 DOWNTO 0)
);
END ENTITY reg_bank;
ARCHITECTURE behav OF reg_bank IS
TYPE reg_bank_t IS ARRAY(0 to 31) OF STD_LOGIC_VECTOR(31 downto 0);
SIGNAL registers : reg_bank_t;
BEGIN
PROCESS(clk,rst)
BEGIN
IF rising_edge(clk) THEN
IF rst = ’0’ THEN
registers <= (OTHERS => "00000000000000000000000000000000");
ELSIF reg_write = ’1’ THEN
registers(conv_integer(idx_write_reg)) <= write_data;
END IF;
data_reg1 <= registers(conv_integer(idx_reg1));
data_reg2 <= registers(conv_integer(idx_reg2));
END IF;
END PROCESS;
49
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 52/66
END ARCHITECTURE behav;
5.2.11 sign_ext.vhd
LIBRARY IEEE;
USE IEEE.STD_LOGIC_1164. ALL;
USE IEEE.STD_LOGIC_UNSIGNED. ALL;
ENTITY sign_ext IS
GENERIC (IN_WIDTH : POSITIVE := 16; OUT_WIDTH : POSITIVE:= 32);
PORT (
input : IN STD_LOGIC_VECTOR(IN_WIDTH−1 DOWNTO 0);
output : OUT STD_LOGIC_VECTOR(OUT_WIDTH−1 DOWNTO 0)
);
END ENTITY sign_ext;
ARCHITECTURE behav OF sign_ext IS
BEGIN
PROCESS(input)
BEGIN
IF input(IN_WIDTH−1) = ’1’ THEN
output <= (OUT_WIDTH−1 DOWNTO IN_WIDTH => ’1’) & input;
ELSE
output <= (OUT_WIDTH−1 DOWNTO IN_WIDTH => ’0’) & input;
END IF;
END PROCESS;
END ARCHITECTURE behav;
5.3 Resultados de Simulação
50
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 53/66
F i g u r a
1 2 : R e s u l t a d o s d e s i m u l a ç ã o
d a A L U r e a l i z a n d o o p e r a ç õ e s a r i t i m é t i c a s .
51
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 54/66
F i g u r a 1 3 : R e s u l t a d
o s d e s i m u l a ç ã o d a A L U r e a l i z a n d o o p e r a ç õ e s a r i t i m é t i c a s
c o m
o c o r r ê n c i a d e o v e r fl o w .
52
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 55/66
F i g u r a 1 4 : R e s u l t a d o s d e s i m u l a ç ã o d a A L U r e a l i z a n d o o p e r a
ç õ e s l ó g i c a s .
53
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 56/66
F i g
u r a 1 5 : R e s u l t a d o s d e s i m u l a
ç ã o d a A L U r e a l i z a n d o d e d e
s l o c a m e n t o .
54
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 57/66
F i g u r a 1 6 : R e s u l t a d o s d e s i m u l a ç ã o d a m e m ó r i a d e i n s t r u ç õ e s .
55
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 58/66
F i g u r a 1 7 : R e s u l t a d o s d e
s i m u l a ç ã o d a m e m ó r i a d e d a
d o s .
56
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 59/66
F i g u r a 1 8 : R e s u l t a d o s d e s i m u l a ç ã o d o b a n c o d e r e g i s t r a d o r e s .
57
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 60/66
F i g u r a 1 9 : R e s u l t a d o s d e s i m u l a ç ã o d o r e g i s t r a d o r P
C .
58
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 61/66
F i g u r a 2 0 : R e s u l t a d o s d e s i m u l a ç ã o d o b l o c o d e c o n t r o l e
d o P C .
59
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 62/66
F i g
u r a 2 1 : R e s u l t a d o s d e s i m u l a
ç ã o d o b l o c o d e c o n t r o l e d o p r o c e s s a d o r .
60
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 63/66
F i g u r a 2 2 : R e s u l t a d o s d e s i m
u l a ç ã o d o b l o c o d e c o n t r o l e d a A L U .
61
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 64/66
F i g u r a 2 3 : R e s u l t a d o s d
e s i m u l a ç ã o d o e x t e n s o r d e s i n a l .
62
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 65/66
F i g u r a 2 4 : R e s u l t a d
o s d e s i m u l a ç ã o d o M u x 2 x 1 .
63
7/23/2019 EEL510231 - Sistemas Digitais e Dispositivos Lógicos Reconfiguráveis
http://slidepdf.com/reader/full/eel510231-sistemas-digitais-e-dispositivos-logicos-reconfiguraveis 66/66
F i g u r a 2 5 : R e s u l t a d o s d e s i m u l a ç ã o t o p l e v e l d o p r o c e s s a d o r .