-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparse.py
2217 lines (1870 loc) · 80.8 KB
/
parse.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'''
Authors: Justin Mendes and Shazil Razzaq
Date: Monday October 17, 2022
Last Modified: Friday Dec 2, 2022
Version: v1.4
Tests functionality of RISC-V processor up to PD4
USAGE: python3 parse.py [-h/--help] [-s/--skip] [-i/--instructions] [-in/--instructions-no-num]
[-r/--regfile] [-m <MEM_DEPTH> / --mem <MEM_DEPTH>]
<PATH to .trace file> <PATH to .x file>
EX: python3 parse.py rv32ui-p-sltiu.trace /rv32-benchmarks/individual-instructions/rv32ui-p-sltiu.x
UPDATES:
@Shazil-R && @justincmendes:
- up to PD5 instead of up to PD4
- refactored code: more pythonic, more OOP
FUTURE:
v1.x:
- Add support for flags (-pd1 -pd2 -pd3 -pd4 -pd5)
To separate the parsers verification for each of the different projects
(upto and including the project)
'''
#// TODO: ADD REGISTER FILE + DMEMORY + WRITEBACK LOGIC!!!
#// TODO: ADD ERROR MESSAGES! to all _check() functions
#// TODO: Update memory_check to verify with Internal implementation for the address and other stuff...
#// TODO: verify PC is the same at each step, sequentially! - implemented generally for single cycle
#// TODO: Reorganize code function orders
#// TODO: Support flag args
'''
EXAMPLE:
[F] 01000000 00000093
[D] 01000000 13 01 00 00 0 00 00000000 00
[R] 00 00 00000000 00000000
[E] 01000000 00000000 0
[M] 01000000 00000000 0 0 00000000
[W] 01000000 1 01 00000000
[F] <pc> <instruction>
[D] <pc> <opcode> <rd> <rs1> <rs2> <funct3> <funct7> <imm> <shamt>
[R] <addr_rs1> <addr_rs2> <data_rs1> <data_rs2>
[E] <pc> <alu_result> <branch_taken>
[M] <pc> <memory_addr> <read_write> <access_size> <memory_data>
[W] <pc> <write_enable> <write_rd> <data_rd>
'''
import sys
import argparse
import os
import glob
from collections import namedtuple
SP_BASE = "01000000" # in hex
Res = namedtuple('Result', ['err', 'res'])
'''Args Parser'''
parser = argparse.ArgumentParser()
def trace_file(path):
if not os.path.isfile(path):
raise argparse.ArgumentTypeError(f'{path} is not a file or it does not exist')
if (len(path) <= 6) or (path[-6:] != ".trace"):
raise argparse.ArgumentTypeError(f'{path} is not a valid trace file (i.e.: *.trace)')
return path
def hex_file(path):
if not os.path.isfile(path):
raise argparse.ArgumentTypeError(f'{path} is not a file or it does not exist')
if (len(path) <= 2) or (path[-2:] != ".x"):
raise argparse.ArgumentTypeError(f'{path} is not a valid hex file (i.e.: *.x)')
return path
'''Classes'''
#// TODO: Instruction Class: define this with all of the properties and control signals associated with any instruction at any time in the pipeline
class Instruction():
#// TODO: __init__ as NOP/KILL, no params
def __init__(self, id=-1):
self.id = id
self.name = "NOP"
self.pc = "0" * 32
self.binary = "0" * 32
self.opcode = "0" * 7
self.rd = "0" * 5
self.rs1 = "0" * 5
self.rs2 = "0" * 5
self.funct3 = "0" * 3
self.funct7 = "0" * 7
self.imm = "0" * 32
self.shamt = "0" * 5
self.pc_sel = "0"
self.br_eq = "0"
self.br_lt = "0"
self.br_un = "0"
self.mem_rw = "0"
self.reg_w_en = "0"
self.wb_sel = "0" * 2
self.rs1_data = "0" * 32
self.rs2_data = "0" * 32
self.alu_result = "0" * 32
self.memory_access_size = "0" * 2
self.memory_data = "0" * 32
self.write_data = "0" * 32
def print(self):
print(f'id: {self.id}')
print(f'name: {self.name}')
print(f'pc: {dec_to_hex(bin_to_dec(self.pc), 8)} ({self.pc})')
print(f'binary: {self.binary}')
print(f'opcode: {self.opcode}')
print(f'rd: {self.rd}')
print(f'rs1: {self.rs1}')
print(f'rs2: {self.rs2}')
print(f'funct3: {self.funct3}')
print(f'funct7: {self.funct7}')
print(f'imm: {self.imm}')
print(f'shamt: {self.shamt}')
print(f'pc_sel: {self.pc_sel}')
print(f'br_eq: {self.br_eq}')
print(f'br_lt: {self.br_lt}')
print(f'br_un: {self.br_un}')
print(f'mem_rw: {self.mem_rw}')
print(f'reg_w_en: {self.reg_w_en}')
print(f'wb_sel: {self.wb_sel}')
print(f'rs1_data: {self.rs1_data}')
print(f'rs2_data: {self.rs2_data}')
print(f'alu_result: {self.alu_result}')
print(f'memory_access_size: {self.memory_access_size}')
print(f'memory_data: {self.memory_data}')
print(f'write_data: {self.write_data}')
#// TODO: Pipeline Class
class Pipeline():
def __init__(self):
self.size = 5
self.queue = [-1] * self.size # 5-element array (for 5-stages)
for i in range(self.size):
self.queue[i] = Instruction()
# self.queue = [Instruction()] * self.size # 5-element array (for 5-stages)
# blank_fetch = Instruction("Fetch")
# blank_decode = Instruction("Decode")
# blank_execute = Instruction("Execute")
# blank_memory = Instruction("Memory")
# blank_write = Instruction("Write")
# self.queue = [-1] * self.size # 5-element array (for 5-stages)
# self.queue = [blank_fetch, blank_decode, blank_execute, blank_memory, blank_write]
# self.queue.append(blank_fetch)
# self.queue.append(blank_decode)
# self.queue.append(blank_execute)
# self.queue.append(blank_memory)
# self.queue.append(blank_write)
# self.queue = [Instruction()] * self.size # 5-element array (for 5-stages)
# self.queue = [Instruction() for i in range(5)]
# self.queue = [-1] * 5 # 5-element array (for 5-stages)
# for i in range(5):
# blank_instruction = Instruction()
# self.queue[i] = blank_instruction
# self.queue = []
# for i in range(5):
# self.queue.append(Instruction())
# print(blank_fetch, blank_decode, blank_execute, blank_memory, blank_write)
# print("===== INIT =====")
# self.print()
def print(self):
for i in range(5):
stage = ""
if(i == 0): stage = "Fetch:"
elif(i == 1): stage = "Decode:"
elif(i == 2): stage = "Execute:"
elif(i == 3): stage = "Memory:"
elif(i == 4): stage = "Write:"
# print (f'{stage} 0x{dec_to_hex(bin_to_dec(self.queue[i].pc), 8)} {self.queue[i].name} {self.queue[i].binary} rd:{self.queue[i].rd} rs1:{self.queue[i].rs1} rs2:{self.queue[i].rs2} imm:{self.queue[i].imm} (ID: {self.queue[i].id})')
print (f'{stage} 0x{dec_to_hex(bin_to_dec(self.queue[i].pc), 8)} {get_print_instruction(self.queue[i])} (ID: {self.queue[i].id})')
def add(self, instruction=Instruction()):
'''Right-shift then (enqueue) push to front of FIFO queue'''
# Right shift from beginning (Fetch onwards)
self.queue = [instruction] + self.queue[:-1]
def stall(self):
'''Injects NOP into EXECUTE stage'''
nop = Instruction()
# Right shift from Execute onwards
self.queue = self.queue[0:2] + [nop] + self.queue[2:-1]
def flush_jump(self):
'''Kill Decode instruction once a J-Type is resolved'''
nop = Instruction(self.queue[1].id)
self.queue[1] = nop
def flush_branch(self):
'''
Kill Decode and Execute instructions if branch should be taken
Default: Branch NOT taken (static)
'''
for i in range(1, 3):
nop = Instruction(self.queue[i].id)
self.queue[i] = nop
class Memory:
def __init__(self, size, data_width):
self.arr = ["0" * data_width] * size
self.size = size
self.data_width = data_width
def set(self, str, index):
self.arr[index] = str
return True
def get(self, index):
return self.arr[index]
def print(self):
for i in range(self.size):
print(f'{i}: {self.arr[i]}')
class DMemory(Memory):
def __init__(self, size, data_width, mem_path = None):
super().__init__(size, data_width)
# Initialize dmemory with contents in mem_path
if(mem_path):
# Get the .x file and load its content in binary to dmemory
with open(mem_path) as f:
i = 0
for line in f.readlines():
line_bin = dec_to_bin(hex_to_dec(line), 32)
if(not self.set_word(line_bin, i)): break
i += 4
def set_byte(self, str, index):
self.arr[index] = str[-8:]
return True
def set_half(self, str, index):
if(index < self.size): self.arr[index] = str[-8:]
else: return False
if(index + 1 < self.size): self.arr[index + 1] = str[-16:-8]
else: return False
return True
def set_word(self, str, index):
if(index < self.size): self.arr[index] = str[-8:]
else: return False
if(index + 1 < self.size): self.arr[index + 1] = str[-16:-8]
else: return False
if(index + 2 < self.size): self.arr[index + 2] = str[-24:-16]
else: return False
if(index + 3 < self.size): self.arr[index + 3] = str[-32:-24]
else: return False
# print(f'str: {str}\n{index}: {self.arr[index]}\n{index + 1}: {self.arr[index + 1]}\n{index + 2}: {self.arr[index + 2]}\n{index + 3}: {self.arr[index + 3]}')
return True
def get_byte(self, index):
return self.arr[index]
def get_half(self, index):
return (
(self.arr[index + 1] if index + 1 < self.size else "")
+ self.arr[index]
)
def get_word(self, index):
return (
(self.arr[index + 3] if index + 3 < self.size else "")
+ (self.arr[index + 2] if index + 2 < self.size else "")
+ (self.arr[index + 1] if index + 1 < self.size else "")
+ self.arr[index]
)
class RegFile(Memory):
def __init__(self, size, data_width):
super().__init__(size, data_width)
def set(self, str, index):
if(index == 0):
return False
self.arr[index] = str[-self.size:]
return True
# !comment this out after debugging
# def print(self):
# print(f'x0: {self.arr[0]}')
# print(f'x1: {self.arr[1]}')
# print(f'x2: {self.arr[2]}\n')
'''Flags: Instruction Checks'''
def is_reg_writeback_type(instruction_name):
return (
not is_store_type(instruction_name) and not is_branch_type(instruction_name)
and instruction_name != "ECALL"
and instruction_name != "NOP"
)
def is_load_type(instruction_name):
return (
instruction_name == "LB"
or instruction_name == "LH"
or instruction_name == "LW"
or instruction_name == "LBU"
or instruction_name == "LHU"
)
def is_store_type(instruction_name):
return (
instruction_name == "SB"
or instruction_name == "SH"
or instruction_name == "SW"
)
def is_mem_type(instruction_name):
return (
is_load_type(instruction_name)
or is_store_type(instruction_name)
)
def is_branch_type(instruction_name):
return (
instruction_name == "BEQ"
or instruction_name == "BNE"
or instruction_name == "BLT"
or instruction_name == "BGE"
or instruction_name == "BLTU"
or instruction_name == "BGEU"
)
def is_jump_type(instruction_name):
return (
instruction_name == "JAL"
or instruction_name == "JALR"
)
def is_upper_type(instruction_name):
return (
instruction_name == "LUI"
or instruction_name == "AUIPC"
)
def is_immediate_type(instruction_name):
return (
instruction_name == "JALR"
or instruction_name == "ADDI"
or instruction_name == "SLTI"
or instruction_name == "SLTIU"
or instruction_name == "XORI"
or instruction_name == "ORI"
or instruction_name == "ANDI"
)
def is_immediate_shift_type(instruction_name):
return (
instruction_name == "SLLI"
or instruction_name == "SRLI"
or instruction_name == "SRAI"
)
def is_register_type(instruction_name):
return (
instruction_name == "ADD"
or instruction_name == "SUB"
or instruction_name == "SLL"
or instruction_name == "SLT"
or instruction_name == "SLTU"
or instruction_name == "XOR"
or instruction_name == "SRL"
or instruction_name == "SRA"
or instruction_name == "OR"
or instruction_name == "AND"
)
def uses_rs1(instruction_name):
return (
not is_upper_type(instruction_name)
and instruction_name != "JAL"
and instruction_name != "ECALL"
and instruction_name != "NOP"
)
def uses_rs2(instruction_name):
return (
is_branch_type(instruction_name)
or is_store_type(instruction_name)
or is_register_type(instruction_name)
)
def get_print_instruction(instruction, instr_num = None):
index_out = f'{instr_num}. ' if instr_num else ""
print_out = None
if(instruction.name == "N/A"): return None
elif(instruction.name == "ECALL"):
return f'{index_out}ECALL'
rd = bin_to_dec(instruction.rd)
rs1 = bin_to_dec(instruction.rs1)
rs2 = bin_to_dec(instruction.rs2)
imm = dec_to_hex(bin_to_dec(instruction.imm), 8)
shamt = dec_to_hex(bin_to_dec(instruction.rd), 2)
if(is_upper_type(instruction.name) or instruction.name == "JAL"):
print_out = f'{index_out}{instruction.name} x{rd}, 0x{imm}'
elif(is_branch_type(instruction.name)):
print_out = f'{index_out}{instruction.name} x{rs1}, x{rs2}, 0x{imm}'
elif(is_load_type(instruction.name)):
print_out = f'{index_out}{instruction.name} x{rd}, 0x{imm}(x{rs1})'
elif(is_store_type(instruction.name)):
print_out = f'{index_out}{instruction.name} x{rs2}, 0x{imm}(x{rs1})'
elif(is_immediate_shift_type(instruction.name)):
print_out = f'{index_out}{instruction.name} x{rd}, x{rs1}, 0x{shamt}'
elif(is_immediate_type(instruction.name)):
print_out = f'{index_out}{instruction.name} x{rd}, x{rs1}, 0x{imm}'
elif(is_register_type(instruction.name)):
print_out = f'{index_out}{instruction.name} x{rd}, x{rs1}, x{rs2}'
elif(instruction.name == "NOP"):
print_out = f'{index_out}{instruction.name}'
return print_out
def print_instruction(instruction, instr_num = None):
print_out = f'{get_print_instruction(instruction, instr_num)} (PC: {dec_to_hex(bin_to_dec(instruction.pc), 8)})'
if(not print_out): return
else:
print(print_out)
return
'''Getters: Instruction Binary Extraction Functions'''
def get_trace_args(line):
return line[4:].split()
def get_opcode(instruction_bin):
return instruction_bin[-7:]
def get_rd(instruction_bin):
return instruction_bin[-12:-7]
def get_rs1(instruction_bin):
return instruction_bin[-20:-15]
def get_rs2(instruction_bin):
return instruction_bin[-25:-20]
def get_funct3(instruction_bin):
return instruction_bin[-15:-12]
def get_funct7(instruction_bin):
return instruction_bin[-32:-25]
def immediate_generator(instruction):
imm = ""
# U-TYPE
if (
instruction.name == "LUI"
or instruction.name == "AUIPC"
):
imm = zero_extend(instruction.binary[-32:-12], 11)
# J-TYPES
elif (instruction.name == "JAL"):
imm = sign_extend(zero_extend(instruction.binary[-32] + instruction.binary[-20:-12] + instruction.binary[-21] + instruction.binary[-31:-21], 0), 20)
# I-TYPES
elif (
instruction.name == "JALR"
or instruction.name == "LB"
or instruction.name == "LH"
or instruction.name == "LW"
or instruction.name == "LBU"
or instruction.name == "LHU"
or instruction.name == "ADDI"
or instruction.name == "SLTI"
or instruction.name == "SLTIU"
or instruction.name == "XORI"
or instruction.name == "ORI"
or instruction.name == "ANDI"
):
imm = sign_extend(instruction.binary[-32:-20], 11)
# B-TYPES
elif(
instruction.name == "BEQ"
or instruction.name == "BNE"
or instruction.name == "BLT"
or instruction.name == "BGE"
or instruction.name == "BLTU"
or instruction.name == "BGEU"
):
temp_string = instruction.binary[-32] + instruction.binary[-8] + instruction.binary[-31:-25] + instruction.binary[-12:-8]
imm = sign_extend(zero_extend(temp_string, 0), 12)
# S-TYPES
elif(
instruction.name == "SB"
or instruction.name == "SH"
or instruction.name == "SW"
):
temp_string = instruction.binary[-32:-25] + instruction.binary[-12:-7]
imm = sign_extend(temp_string, 11)
# R-TYPES
elif(
instruction.name == "ADD"
or instruction.name == "SUB"
or instruction.name == "SLL"
or instruction.name == "SLT"
or instruction.name == "SLTU"
or instruction.name == "XOR"
or instruction.name == "SRL"
or instruction.name == "SRA"
or instruction.name == "OR"
or instruction.name == "AND"
or instruction.name == "SLLI"
or instruction.name == "SRLI"
or instruction.name == "SRAI"
or instruction.name == "NOP"
):
imm = sign_extend("0", 0)
return imm
def get_shamt(instruction_bin):
return instruction_bin[-25:-20]
'''Utility Functions: Bitwise Manipulations/Operations and Radix Conversions'''
# @bin = immediate value
# @sign_bit_index = sign bit index in the imm[]
def sign_extend(bin, sign_bit_index, size = 32):
return bin[-(sign_bit_index + 1)] * (size - 1 - sign_bit_index) + bin
# Extends down
def zero_extend(bin, start_index):
return bin + "0" * (start_index + 1)
def twos_complement(bin):
# Find the first 1 from the right
index = bin.rfind("1")
out = bin
# Flip all above the first 1
if(index != -1):
for i in range(index):
temp = list(out)
if(out[i] == "0"):
temp[i] = "1"
else:
temp[i] = "0"
out = "".join(temp)
# if(out[i] == "0"):
# out = out[:i] + "1" + {out[i+1:] if (i+1 < index) else ""}
# else:
# out = out[:i] + "0" + {out[i+1:] if (i+1 < index) else ""}
# out[i] = "1" if out[i] == "0" else "0"
# print(out)
return out
def signed_less_than(op1, op2):
# Positive < Negative
if(int(op1[0]) < int(op2[0])):
res = False
# Negative < Positive
elif(int(op2[0]) < int(op1[0])):
res = True
# Same sign
else:
res = bin_to_dec(op1) < bin_to_dec(op2)
return res
def hex_to_dec(hex):
return int(hex, 16)
def dec_to_hex(dec, size):
hex = format(dec, f'#0{size + 2}x')
hex = hex[2:]
return hex[-size:]
def dec_to_bin(dec, size):
bin = format(dec, f'#0{size + 2}b')
bin = bin[2:]
return bin[-size:]
def bin_to_dec(bin):
return int(bin, 2)
def signed_bin_to_dec(bin, size = 32):
return (bin & ((1 << (size-1)) - 1)) - (bin & (1 << (size-1)))
'''RISC-V PROCESSOR STAGES:'''
def fetch(pipeline, hex_file_path, pc, stall, first=False):
[f_instruction, d_instruction, x_instruction, m_instruction, w_instruction] = pipeline.queue
''' Gets the instruction 1 clock cycle after is is done computing for the relevant fetch pc information'''
# print("FETCH STALL CHECK:")
# print (stall)
if(not stall):
if(is_branch_type(m_instruction.name) and m_instruction.pc_sel == "1"):
# print("FETCH BRANCH (memory ALU)")
pc = bin_to_dec(m_instruction.alu_result)
elif(is_jump_type(x_instruction.name)):
# print("FETCH JUMP (execute ALU)")
pc = bin_to_dec(x_instruction.alu_result)
elif(not first):
# print("FETCH PC+4")
pc += 4
hex_file = glob.glob(hex_file_path)
if(not hex_file):
return False
# print(int((pc - hex_to_dec(SP_BASE))/4))
instruction_hex = "0" * 8
for file in hex_file:
with open(file, 'r') as f:
instruction_hex = f.readlines()[int((pc - hex_to_dec(SP_BASE))/4)]
# print(instruction_hex)
# print(int((pc - hex_to_dec(SP_BASE))/4))
f_instruction.pc = dec_to_bin(pc, 32)
f_instruction.binary = dec_to_bin(hex_to_dec(instruction_hex), 32)
return True
def fetch_check(pipeline, line, stall):
'''Checks the state of the pipeline one clock cycle after, during current fetch'''
# External: In trace
args = get_trace_args(line)
pc = dec_to_bin(hex_to_dec(args[0]), 32)
instruction_bin = dec_to_bin(hex_to_dec(args[1]), 32)
# Internal: In processor
[f_instruction, d_instruction, x_instruction, m_instruction, w_instruction] = pipeline.queue
res = True
err = None
operation = "PC+4"
if(is_jump_type(x_instruction.name)):
operation = "JUMP ALU"
elif(is_branch_type(m_instruction.name) and m_instruction.pc_sel == "1"):
operation = "BRANCH ALU"
stalled = "(STALLED EXPECTED) " if stall else ""
if(pc != f_instruction.pc):
res = False
err = (f'<FETCH>: {stalled}pc: Got: {dec_to_hex(bin_to_dec(pc), 8)}, Expected: {dec_to_hex(bin_to_dec(f_instruction.pc), 8)} (Expected operation: {operation})')
elif(instruction_bin != f_instruction.binary):
res = False
err = (f'<FETCH>: {stalled}instruction (binary): Got: {instruction_bin}, Expected: {f_instruction.binary}')
return (res, err)
def decode(instruction, reg_file):
instruction_name = "N/A"
opcode = get_opcode(instruction.binary)
rd = get_rd(instruction.binary)
rs1 = get_rs1(instruction.binary)
rs2 = get_rs2(instruction.binary)
funct3 = get_funct3(instruction.binary)
funct7 = get_funct7(instruction.binary)
# imm = immediate_generator(instruction.binary)
shamt = get_shamt(instruction.binary)
rs1_data = reg_file.get(bin_to_dec(rs1))
rs2_data = reg_file.get(bin_to_dec(rs2))
# U-TYPES
if(opcode == "0110111"): instruction_name = "LUI"
elif(opcode == "0010111"): instruction_name = "AUIPC"
# J-TYPE
elif(opcode == "1101111"): instruction_name = "JAL"
# B-TYPES
elif(opcode == "1100011" and funct3 == "000"): instruction_name = "BEQ"
elif(opcode == "1100011" and funct3 == "001"): instruction_name = "BNE"
elif(opcode == "1100011" and funct3 == "100"): instruction_name = "BLT"
elif(opcode == "1100011" and funct3 == "101"): instruction_name = "BGE"
elif(opcode == "1100011" and funct3 == "110"): instruction_name = "BLTU"
elif(opcode == "1100011" and funct3 == "111"): instruction_name = "BGEU"
# I-TYPES
elif(opcode == "1100111"): instruction_name = "JALR"
elif(opcode == "0000011" and funct3 == "000"): instruction_name = "LB"
elif(opcode == "0000011" and funct3 == "001"): instruction_name = "LH"
elif(opcode == "0000011" and funct3 == "010"): instruction_name = "LW"
elif(opcode == "0000011" and funct3 == "100"): instruction_name = "LBU"
elif(opcode == "0000011" and funct3 == "101"): instruction_name = "LHU"
elif(opcode == "0010011" and funct3 == "000"): instruction_name = "ADDI"
elif(opcode == "0010011" and funct3 == "010"): instruction_name = "SLTI"
elif(opcode == "0010011" and funct3 == "011"): instruction_name = "SLTIU"
elif(opcode == "0010011" and funct3 == "100"): instruction_name = "XORI"
elif(opcode == "0010011" and funct3 == "110"): instruction_name = "ORI"
elif(opcode == "0010011" and funct3 == "111"): instruction_name = "ANDI"
elif(opcode == "0010011" and funct3 == "001"): instruction_name = "SLLI"
elif(opcode == "0010011" and funct3 == "101" and funct7 == "0000000"): instruction_name = "SRLI"
elif(opcode == "0010011" and funct3 == "101" and funct7 == "0100000"): instruction_name = "SRAI"
# S-TYPES
elif(opcode == "0100011" and funct3 == "000"): instruction_name = "SB"
elif(opcode == "0100011" and funct3 == "001"): instruction_name = "SH"
elif(opcode == "0100011" and funct3 == "010"): instruction_name = "SW"
# R-TYPES
elif(opcode == "0110011" and funct3 == "000" and funct7 == "0000000"): instruction_name = "ADD"
elif(opcode == "0110011" and funct3 == "000" and funct7 == "0100000"): instruction_name = "SUB"
elif(opcode == "0110011" and funct3 == "001"): instruction_name = "SLL"
elif(opcode == "0110011" and funct3 == "010"): instruction_name = "SLT"
elif(opcode == "0110011" and funct3 == "011"): instruction_name = "SLTU"
elif(opcode == "0110011" and funct3 == "100"): instruction_name = "XOR"
elif(opcode == "0110011" and funct3 == "101" and funct7 == "0000000"): instruction_name = "SRL"
elif(opcode == "0110011" and funct3 == "101" and funct7 == "0100000"): instruction_name = "SRA"
elif(opcode == "0110011" and funct3 == "110"): instruction_name = "OR"
elif(opcode == "0110011" and funct3 == "111"): instruction_name = "AND"
elif(opcode == "1110011" and funct3 == "000" and funct7 == "0000000"): instruction_name = "ECALL"
elif(opcode == "0000000"): instruction_name = "NOP"
else:
instruction_name = "N/A"
return False
instruction.name = instruction_name
instruction.opcode = opcode
instruction.rd = rd
instruction.rs1 = rs1
instruction.rs2 = rs2
instruction.funct3 = funct3
instruction.funct7 = funct7
instruction.shamt = shamt
instruction.rs1_data = rs1_data
instruction.rs2_data = rs2_data
imm = immediate_generator(instruction)
instruction.imm = imm
if (instruction_name == "JALR"):
instruction.alu_result = dec_to_bin(bin_to_dec(instruction.imm) + bin_to_dec(instruction.rs1_data), 32)
# print(f'JALR to {instruction.alu_result}')
elif (instruction_name == "JAL"):
instruction.alu_result = dec_to_bin(bin_to_dec(instruction.imm) + bin_to_dec(instruction.pc), 32)
# print(f'JAL to {instruction.alu_result}')
# print("Instruction Immediate: ")
# print (instruction.imm)
# print("Instruction PC: ")
# print (instruction.pc)
# print("ALU Result: ")
# print (instruction.alu_result)
# print("Decode Instruction")
# print(get_print_instruction(instruction))
# print("Decode RS1")
# print(instruction.rs1)
# print("Decode RS2")
# print(instruction.rs2)
# print("Decode RS1 Data")
# print(instruction.rs1_data)
# print("Decode RS2 Data")
# print(instruction.rs2_data)
# print("Decode ID: ")
# print(instruction.id)
return True
def decode_check(instruction, line):
args = get_trace_args(line)
# External: In trace file
pc = dec_to_bin(hex_to_dec(args[0]), 32)
opcode = dec_to_bin(hex_to_dec(args[1]), 7)
rd = dec_to_bin(hex_to_dec(args[2]), 5)
rs1 = dec_to_bin(hex_to_dec(args[3]), 5)
rs2 = dec_to_bin(hex_to_dec(args[4]), 5)
funct3 = dec_to_bin(hex_to_dec(args[5]), 3)
funct7 = dec_to_bin(hex_to_dec(args[6]), 7)
imm = dec_to_bin(hex_to_dec(args[7]), 32)
shamt = dec_to_bin(hex_to_dec(args[8]), 5)
res = True
err = None
# PC CHECK!!!
if(pc != instruction.pc):
res = False
err = (
f'<{instruction.name}>: {dec_to_hex(bin_to_dec(instruction.binary), 8)} - incorrect PC in DECODE stage. Got: {pc}. Expected {instruction.pc}'
)
# U-TYPES & J-TYPE
if (
(
instruction.name == "LUI"
or instruction.name == "AUIPC"
or instruction.name == "JAL"
)
and not
(
opcode == instruction.opcode
and rd == instruction.rd
and imm == instruction.imm
)
):
res = False
err = (
f'<{instruction.name}>: {dec_to_hex(bin_to_dec(instruction.binary), 8)} - opcode: Got: {opcode}, Expected: {instruction.opcode}.'
f'\nrd: Got: {rd}, Expected: {instruction.rd}.'
f'\nimm: Got: {imm}, Expected: {instruction.imm}.'
)
# I-TYPES
elif (
(
instruction.name == "JALR"
or instruction.name == "LB"
or instruction.name == "LH"
or instruction.name == "LW"
or instruction.name == "LBU"
or instruction.name == "LHU"
or instruction.name == "ADDI"
or instruction.name == "SLTI"
or instruction.name == "SLTIU"
or instruction.name == "XORI"
or instruction.name == "ORI"
or instruction.name == "ANDI"
)
and not
(
opcode == instruction.opcode
and rd == instruction.rd
and funct3 == instruction.funct3
and rs1 == instruction.rs1
and imm == instruction.imm
)
):
res = False
err = (
f'<{instruction.name}>: {dec_to_hex(bin_to_dec(instruction.binary), 8)} - opcode: Got: {opcode}, Expected: {instruction.opcode}.'
f'\nrd: Got: {rd}, Expected: {instruction.rd}.'
f'\nfunct3: Got: {funct3}, Expected: {instruction.funct3}.'
f'\nrs1: Got: {rs1}, Expected: {instruction.rs1}.'
f'\nimm: Got: {imm}, Expected: {instruction.imm}.'
)
# B-TYPES
elif(
(
instruction.name == "BEQ"
or instruction.name == "BNE"
or instruction.name == "BLT"
or instruction.name == "BGE"
or instruction.name == "BLTU"
or instruction.name == "BGEU"
)
and not
(
opcode == instruction.opcode
and imm == instruction.imm
and funct3 == instruction.funct3
and rs1 == instruction.rs1
and rs2 == instruction.rs2
)
):
res = False
err = (
f'<{instruction.name}>: {dec_to_hex(bin_to_dec(instruction.binary), 8)} - opcode: Got: {opcode}, Expected: {instruction.opcode}.'
f'\nimm: Got: {imm}, Expected: {instruction.imm}.'
f'\nfunct3: Got: {funct3}, Expected: {instruction.funct3}.'
f'\nrs1: Got: {rs1}, Expected: {instruction.rs1}.'
f'\nrs2: Got: {rs2}, Expected: {instruction.rs2}.'
)
# S-TYPES
elif(
(
instruction.name == "SB"
or instruction.name == "SH"
or instruction.name == "SW"
)
and not
(
opcode == instruction.opcode
and imm == instruction.imm
and rs1 == instruction.rs1
and rs2 == instruction.rs2
and funct3 == instruction.funct3
)
):
res = False
err = (
f'<{instruction.name}>: {dec_to_hex(bin_to_dec(instruction.binary), 8)} - opcode: Got: {opcode}, Expected: {instruction.opcode}.'
f'\nimm: Got: {imm}, Expected: {instruction.imm}.'
f'\nfunct3: Got: {funct3}, Expected: {instruction.funct3}.'
f'\nrs1: Got: {rs1}, Expected: {instruction.rs1}.'
f'\nrs2: Got: {rs2}, Expected: {instruction.rs2}.'
)
# R-TYPES with SHAMT
elif(
(
instruction.name == "SLLI"
or instruction.name == "SRLI"
or instruction.name == "SRAI"
)
and not
(
opcode == instruction.opcode
and rd == instruction.rd
and funct3 == instruction.funct3
and rs1 == instruction.rs1
and shamt == instruction.shamt
and funct7 == instruction.funct7
)
):
res = False
err = (
f'<{instruction.name}>: {dec_to_hex(bin_to_dec(instruction.binary), 8)} - opcode: Got: {opcode}, Expected: {instruction.opcode}.'
f'\nrd: Got: {rd}, Expected: {instruction.rd}.'
f'\nfunct3: Got: {funct3}, Expected: {instruction.funct3}.'
f'\nrs1: Got: {rs1}, Expected: {instruction.rs1}.'
f'\nshamt: Got: {shamt}, Expected: {instruction.shamt}.'
f'\nfunct7: Got: {funct7}, Expected: {instruction.funct7}.'
)
# R-TYPES
elif(
(
instruction.name == "ADD"
or instruction.name == "SUB"
or instruction.name == "SLL"
or instruction.name == "SLT"
or instruction.name == "SLTU"
or instruction.name == "XOR"
or instruction.name == "SRL"
or instruction.name == "SRA"
or instruction.name == "OR"
or instruction.name == "AND"
)
and not
(
opcode == instruction.opcode
and rd == instruction.rd
and funct3 == instruction.funct3
and rs1 == instruction.rs1
and rs2 == instruction.rs2
and funct7 == instruction.funct7
)
):
res = False
err = (
f'<{instruction.name}>: {dec_to_hex(bin_to_dec(instruction.binary), 8)} - opcode: Got: {opcode}, Expected: {instruction.opcode}.'