forked from stevehoover/warp-v
-
Notifications
You must be signed in to change notification settings - Fork 0
/
warp-v.tlv
6117 lines (5619 loc) · 298 KB
/
warp-v.tlv
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
\m5_TLV_version 1d: tl-x.org
\SV
// -----------------------------------------------------------------------------
// Copyright (c) 2018, Steven F. Hoover
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * The name Steven F. Hoover
// may not be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// -----------------------------------------------------------------------------
// This code is mastered in https://github.com/stevehoover/warp-v.git
// For usage examples, visit warp-v.org.
\m5
///debug_level(max)
use(m5-1.0)
\SV
m4_include_lib(['https://raw.githubusercontent.com/stevehoover/tlv_lib/3543cfd9d7ef9ae3b1e5750614583959a672084d/fundamentals_lib.tlv'])
\m5
/// A highly-parameterized CPU generator, configurable for:
/// o An ISA of your choice, where the following ISAs are currently defined herein:
/// - An uber-simple mini CPU for academic use
/// - RISC-V (incomplete)
/// o Pipeline staging (from 1 to 7 stages)
/// o Architectural parameters, like memory size, etc.
/// This file includes:
/// o The configurable (esp. for pipeline depth) ISA-independent CPU logic.
/// o ISA-specific decode and execute logic for mini-CPU, RISC-V, and a dummy
/// (for diagrams).
/// o A simple RISC-V assembler. (The Mini ISA needs no assembler as it uses strings for instructions.)
/// o A tiny test program for each ISA
/// If you've come here to learn about RISC-V design with TL-Verilog, the WARP-V source code
/// may not be the best place to start. WARP-V is highly parameterized using M5 (docs available
/// within the Makerchip IDE) and this parameterization can be confusing to someone new to
/// TL-Verilog. You might be better served to start with:
/// o A "RVMYTH" TL-Verilog RISC-V design created in the Microprocessor for You in
/// Thirty Hours (MYTH) Workshop:
/// https://github.com/stevehoover/RISC-V_MYTH_Workshop/blob/master/student_projects.md
/// o A TL-Verilog RISC-V design course: https://makerchip.com/sandbox?tabs=Courses
/// o By compiling this code in Makerchip, the "Nav-TLV" tab will contain the
/// preprocessed code. Parameterization has been resolved in this code, and you can
/// navigate the code interactively and find corresponding source lines by clicking
/// Nav-TLV line numbers.
/// Note that the "Diagram" may fail to generate due to the size of the design.
/// The CPU
/// The code is parameterized, using the M5 macro preprocessor, for adjustable pipeline
/// depth.
///
/// Overview:
/// o One instruction traverses the single free-flowing CPU pipeline per cycle.
/// o There is no branch or condition or target prediction.
/// o Instructions are in-order, but the uarch supports loads that return their
/// data out of order (though, they do not).
///
/// Redirects:
///
/// The PC is redirected, and inflight instructions are squashed (their results are
/// not committed) for:
/// o no-fetch cycles (squashes only the no-fetch instruction itself)
/// o 2nd-issue of split (long-latency) instructions (squashes only the clobbered instruction itself,
/// which reissues next cycle)
/// o jumps, which go to an absolute jump target address
/// o predicted-taken branches, which speculatively redirect to the computed branch target
/// o unconditioned and mispredicted taken branches, which go to branch target
/// o mispredicted not-taken branches which go to the next sequential PC
/// o instructions that read or write a pending register
/// (See "Loads", below.)
/// o traps, which go to a trap target
///
/// Loads:
///
/// o Load instructions complete without writing their destination registers. Destination
/// registers are instead marked "pending", and reads of pending registers are replayed.
/// o This could again result in a read of the same pending register and can repeat until
/// the load returns. Writes to pending registers are also replayed, so there can be at
/// most one oustanding load to any given register.
/// o This way, out-of-order loads are
/// supported (though loads are implemented to have a fixed latency). A returning load
/// reserves an instruction slot at the beginning of the pipeline to reserve a register
/// write port. The returning load writes its result and clears the destination
/// register's pending flag.
///
/// To support L1 and L2 caches, it would be reasonable to delay register write (if
/// necessary) to wait for L1 hits (extending the bypass window), and mark "pending"
/// for L1 misses. Power could be saved by going idle on replay until load will return
/// data.
///
/// Long-latency pipelined instructions:
///
/// Long-latency pipelined instructions can utilize the same split issue and pending
/// mechanisms as load instructions.
///
/// Long-latency non-pipelined instructions:
///
/// o In the current implementation, bit manipulation(few), floating point and integer multiplication /
/// division instructions are non-pipelined, followed by "no-fetch" cycles
/// until the next redirect (which will be a second issue of the instruction).
/// o The data required during second can be passed to the commit stage using /orig_inst scope
/// o It does not matter whether registers are marked pending, but we do.
/// o Process redirect conditions take care of the correct handling of PC for such instrctions.
/// o \TLV m_extension() can serve as a reference implementation for correctly stalling the pipeline
/// for such instructions
///
/// Handling loads and long-latency instructions:
///
/// o For any instruction that requires second issue, some of its attributes (such as
/// destination register, raw value, rs1/rs2/rd) depending on where they are consumed
/// need to be retained. $ANY construct is used to make this logic generic and use-dependent.
/// o In case of loads, the /orig_load_inst scope is used to hook up the
/// mem pipeline to the CPU pipeline in first pipestage (of CPU) to reserve slot for the load
/// flowing from mem to CPU in the second issue.
/// o For non-pipelined instructions such as mul-div, the /hold_inst scope retains the values
/// till the second issue.
/// o Both the scopes are merged into /orig_inst scope depending on which instruction the second
/// issue belongs to.
///
/// Bypass:
///
/// Register bypass is provided if one instruction's result is not written to the
/// register file in time for the next instruction's read. An additional bypass is
/// provided for each additional cycle between read and write.
///
/// Memory:
///
/// The program is stored in its own instruction memory (for simplicity).
/// Data memory is separate.
///
/// Futures:
///
/// TODO: It might be cleaner to split /instr into two scopes: /fetch_instr and /commit_instr, where
/// /fetch_instr reflects the instruction fetched from i-memory (1st issue), and /commit_instr reflects the
/// instruction that will be committed (2nd issue). The difference is long-latency instructions which commit
/// in place of the fetch instruction. There have been several subtle bugs where the fetch
/// instruction leaks into the commit instruction (esp. reg. bypass), and this would help to
/// avoid them.
///
/// TODO: Replays can be injected later in the pipeline - at the end of fetch. Unlike redirect, we
/// already have the raw instruction bits to inject. The replay mechanism can be separated from
/// redirects.
///
/// TODO: Once Makerchip supports multifile editing, split this up.
/// WARP should be a library, and each CPU uses this library to create a CPU.
/// Stages should be defined using a generic mechanism (just defining m5_*_STAGE constants).
/// Redirects should be defined using a generic mechanism to define each redirect, then
/// instantiate the logic (including PC logic).
/// IMem, RF should be m5+ macros.
/// Should create generic instruction definition macros (like the RISC-V ones, but generic).
/// ============
/// Mini-CPU ISA
/// ============
/// A dirt-simple CPU for educational purposes.
/// What's interesting about this CPU?
/// o It's super small.
/// o It's easy to play with an learn from.
/// o Instructions are short, kind-of-readable strings, so no assembler is needed.
/// They would map directly to a denser (~17-bit) encoding if desired.
/// o The only instruction formats are op, load, and store.
/// o Branch/Jump: There is no special format for control-flow instructions. Any
/// instruction can write the PC (relative or absolute). A conditional branch
/// will typically utilize a condition operation that provides a branch target or
/// zero. The condition can be predicted as per traditional branch prediction
/// (though there is no branch predictor in this example as it stands).
/// ISA:
///
/// Instructions are 5-character strings: "D=1o2"
///
/// =: Appears in every instruction (just for readability).
/// D, 2, 1: "a" - "h" for register values;
/// "0" - "7" for immediate constants (sources, or "0" for unused dest);
/// "P" for absolute dest PC (jump);
/// "p" for relative dest PC (branch), PC = PC + 1 + result(signed).
///
/// o: operator
/// Op: (D = 1 o 2) (Eg: "c=a+b"):
/// +, -, *, /: Arithmetic. *, / are unsigned.
/// =, !, <, >, [, ]: Compare (D = (1 o r) ? all-1s : 0) (] is >=, [ is <=)
/// (On booleans these are XNOR, XOR, !1&2, 1&!2, !1|2, 1|!2)
/// &, |: Bitwise
/// (Can be used on booleans as well as vectors.)
/// (There are no operators for NAND and NOR and unary !.)
/// ~ : Extended constant (D = {1[2:0], 2[2:0]})
/// , : Combine (D = {1[11:6], 2[5:0]})
/// ? : Conditional (D = 2 ? `0 : 1)
/// Load (Eg: "c=a:b") (D = [1 + 2] (typically 1 would be an immediate offset):
/// ) : Load
/// Store (Eg: "0=a;b") ([2] = 1):
/// ( : Store
///
/// A full-width immediate load sequence, to load octal 2017 is:
/// a=2~0
/// b=1~7
/// a=a,b
/// A typical local conditional branch sequence is:
/// a=0-6 // offset
/// c=c-1 // decrementing loop counter
/// p=a?c // branch by a (to PC+1-6) if c is non-negative (MSB==0)
/// ==========
/// RISC-V ISA
/// ==========
/// This design is a RISC-V (RV32IMF) implementation.
/// The ISA is characterized using M5 macros, and the microarchitecture is generated from this characterization, so
/// the ISA can be modified through M5 definitions.
/// Notes:
/// o Unaligned load/store are handled by trapping, though no s/w is available to handle the trap.
/// The implementation is based on "The RISC-V Instruction Set Manual Vol. I: User-Level ISA," Version 2.2: https://riscv.org/specifications/
/// ======
/// MIPS I
/// ======
/// WIP.
/// Unlike RISC-V, this does not use M5 to characterize the ISA.
/// Not implemented:
/// o FPU
/// o Mult/Div and HI/LO regs
/// o Branch/Load delay slots
/// No compliance testing has been done. This code is intended to demonstrate the flexibility of TL-Verilog,
/// not to provide a production-worthy MIPS I design.
/// =====
/// Power
/// =====
/// WIP.
/// Unlike RISC-V, this does not use M5 to characterize the ISA.
/// No compliance testing has been done. This code is intended to demonstrate the flexibility of TL-Verilog,
/// not to provide a production-worthy Power design.
/// =========
/// DUMMY ISA
/// =========
/// This "ISA" can be selected to produce diagrams of the CPU without the ISA details.
/// It is also useful as a starting point and reference for other ISAs, as it illustrates which signals are required.
/// =========
/// Libraries
/// =========
/// =============
/// Configuration
/// =============
/// For passing configuration via the command line.
if_def(CONFIG_EXPR, ['m5_CONFIG_EXPR'])
/// For a while, remain backward-compatible with M4 parameterization.
macro(import_m4_params, ['m4_ifdef(m4_m4prefix(['$1']), ['m5_var(['$1'], m4_defn(m4_m4prefix(['$1'])))'])m5_if($# > 1, ['$0(m5_shift($@))'])']) /// TODO
import_m4_params(PROG_NAME, ISA, EXT_F, EXT_E, EXT_M, EXT_B, NUM_CORES, NUM_VCS, NUM_PRIOS, MAX_PACKET_SIZE, soft_reset, cpu_blocked,
BRANCH_PRED, EXTRA_REPLAY_BUBBLE, EXTRA_PRED_TAKEN_BUBBLE, EXTRA_JUMP_BUBBLE,
EXTRA_BRANCH_BUBBLE, EXTRA_INDIRECT_JUMP_BUBBLE, EXTRA_NON_PIPELINED_BUBBLE,
EXTRA_TRAP_BUBBLE, NEXT_PC_STAGE, FETCH_STAGE, DECODE_STAGE, BRANCH_PRED_STAGE,
REG_RD_STAGE, EXECUTE_STAGE, RESULT_STAGE, REG_WR_STAGE, MEM_WR_STAGE, LD_RETURN_ALIGN,
DMEM_STYLE, IMEM_STYLE, VIZ, FORMAL)
/// TODO: A convenient hack for local development that can be removed.
var(local, 0)
if(m5_local, [
var(warpv_includes, ['./warp-v_includes/'])
], [
var(warpv_includes, ['https://raw.githubusercontent.com/stevehoover/warp-v_includes/ac8c318cc21eb5dc77dff635b1b6a60932aba82b/'])
])
/// This is where you configure the CPU.
/// Note that WARP-V has a configurator at warp-v.org.
/// default_var(..) allows external definition to take precedence.
/// Default parameters for formal verification continuous integration testing.
/// FORMAL is only used within Makerchip in debug mode (for VIZ).
default_var(FORMAL, 0) // Uncomment to test formal verification in Makerchip.
if_eq(m5_FORMAL, 1, [
default_var(
ISA, RISCV,
EXT_M, 1,
VIZ, 1,
STANDARD_CONFIG, 4-stage)
default_var(RISCV_FORMAL_ALTOPS, m5_EXT_M)
])
/// Machine:
default_var(
['# ISA (MINI, RISCV, MIPSI, POWER, DUMMY, etc.)'],
ISA, RISCV,
['# A standard configuration that provides default values. (1-stage, 2-stage, 4-stage, 6-stage, none (and define individual parameters))'],
STANDARD_CONFIG, 4-stage,
['# Number of words in the data memory.'],
DMEM_SIZE, 32)
/// --------------
/// For multi-core
/// --------------
default_var(
['# Number of cores. Previously this was defined externally as m5_CORE_CNT (via m5_define_hier), so accept that too.'],
NUM_CORES, m5_if_def(CORE_CNT, ['m5_CORE_CNT'], 1))
/// Only relevant, and only defined, if NUM_CORES > 1:
if(m5_NUM_CORES > 1, [
default_var(
['# VCs (meaningful if > 1 core).'],
NUM_VCS, 2,
['# Number of priority levels in the NoC (meaningful if > 1 core).'],
NUM_PRIOS, 2,
['# Max number of payload flits in a packet.'],
MAX_PACKET_SIZE, 3)
])
default_var(
['# Include visualization'],
VIZ, 1,
['# For implementation (vs. simulation). (0/1)'],
IMPL, 0,
['# Build for formal verification (0/1).'],
FORMAL, 0,
['# riscv-formal uses alternate operations (add/sub and xor with a constant value)
instead of actual mul/div, this is enabled automatically when formal is used.
This can be enabled for testing in Makerchip environment.'],
RISCV_FORMAL_ALTOPS, 0)
default_var(
['# IMem style: SRAM, HARDCODED_ARRAY, STUBBED, EXTERN'],
IMEM_STYLE, m5_if(m5_IMPL, SRAM, HARDCODED_ARRAY),
['# DMem style: SRAM, ARRAY, STUBBED'],
DMEM_STYLE, m5_if(m5_IMPL, SRAM, ARRAY),
['# RF style: ARRAY, STUBBED'],
RF_STYLE, ARRAY)
default_var(
['# A hook for a software-controlled reset. None by default.'],
soft_reset, 1'b0,
['# A hook for CPU back-pressure in m5_REG_RD_STAGE.
Various sources of back-pressure can add to this expression.
Currently, this is envisioned for CSR writes that cannot be processed, such as
NoC packet writes.'],
cpu_blocked, 1'b0)
/// Define the implementation configuration, including pipeline depth and staging.
/// Define the following:
/// Stages:
/// NEXT_PC_STAGE: Determining fetch PC for the NEXT instruction (not this one).
/// FETCH_STAGE: Instruction fetch.
/// DECODE_STAGE: Instruction decode.
/// BRANCH_PRED_STAGE: Branch predict (taken/not-taken). Currently, we mispredict to a known branch target,
/// so branch prediction is only relevant if target is computed before taken/not-taken is known.
/// For other ISAs prediction is forced to fallthrough, and there is no pred-taken redirect.
/// REG_RD_STAGE: Register file read.
/// EXECUTE_STAGE: Operation execution.
/// RESULT_STAGE: Select execution result.
/// BRANCH_TARGET_CALC_STAGE: Calculate branch target (generally EXECUTE, but some designs
/// might produce offset from EXECUTE, then compute target).
/// MEM_WR_STAGE: Memory write.
/// REG_WR_STAGE: Register file write.
/// Deltas (default to 0):
/// DELAY_BRANCH_TARGET_CALC: 1 to delay branch target calculation 1 stage from its nominal (ISA-specific) stage.
/// Latencies (default to 0):
/// LD_RETURN_ALIGN: Alignment of load return pseudo-instruction into |mem pipeline.
/// If |mem stages reflect nominal alignment w/ load instruction, this is the
/// nominal load latency.
/// Deltas (default to 0):
/// EXTRA_PRED_TAKEN_BUBBLE: 0 or 1. 0 aligns PC_MUX with BRANCH_TARGET_CALC.
/// EXTRA_REPLAY_BUBBLE: 0 or 1. 0 aligns PC_MUX with RD_REG for replays.
/// EXTRA_JUMP_BUBBLE: 0 or 1. 0 aligns PC_MUX with EXECUTE for jumps.
/// EXTRA_PRED_TAKEN_BUBBLE: 0 or 1. 0 aligns PC_MUX with EXECUTE for pred_taken.
/// EXTRA_INDIRECT_JUMP_BUBBLE: 0 or 1. 0 aligns PC_MUX with EXECUTE for indirect_jump.
/// EXTRA_BRANCH_BUBBLE: 0 or 1. 0 aligns PC_MUX with EXECUTE for branches.
/// EXTRA_TRAP_BUBBLE: 0 or 1. 0 aligns PC_MUX with EXECUTE for traps.
/// BRANCH_PRED: {fallthrough, two_bit, ...}
case(STANDARD_CONFIG,
['1-stage'], [
/// No pipeline
default_var(
NEXT_PC_STAGE, 0,
FETCH_STAGE, 0,
DECODE_STAGE, 0,
BRANCH_PRED_STAGE, 0,
REG_RD_STAGE, 0,
EXECUTE_STAGE, 0,
RESULT_STAGE, 0,
REG_WR_STAGE, 0,
MEM_WR_STAGE, 0,
LD_RETURN_ALIGN, 1)
default_var(BRANCH_PRED, fallthrough)
],
['2-stage'], [
/// 2-stage pipeline.
default_var(
NEXT_PC_STAGE, 0,
FETCH_STAGE, 0,
DECODE_STAGE, 0,
BRANCH_PRED_STAGE, 0,
REG_RD_STAGE, 0,
EXECUTE_STAGE, 1,
RESULT_STAGE, 1,
REG_WR_STAGE, 1,
MEM_WR_STAGE, 1,
LD_RETURN_ALIGN, 2)
default_var(BRANCH_PRED, two_bit)
],
['4-stage'], [
/// A reasonable 4-stage pipeline.
default_var(
NEXT_PC_STAGE, 0,
FETCH_STAGE, 0,
DECODE_STAGE, 1,
BRANCH_PRED_STAGE, 1,
REG_RD_STAGE, 1,
EXECUTE_STAGE, 2,
RESULT_STAGE, 2,
REG_WR_STAGE, 3,
MEM_WR_STAGE, 3,
EXTRA_REPLAY_BUBBLE, 1,
LD_RETURN_ALIGN, 4)
default_var(BRANCH_PRED, two_bit)
],
['6-stage'], [
/// Deep pipeline
default_var(
NEXT_PC_STAGE, 1,
FETCH_STAGE, 1,
DECODE_STAGE, 3,
BRANCH_PRED_STAGE, 4,
REG_RD_STAGE, 4,
EXECUTE_STAGE, 5,
RESULT_STAGE, 5,
REG_WR_STAGE, 6,
MEM_WR_STAGE, 7,
EXTRA_REPLAY_BUBBLE, 1,
LD_RETURN_ALIGN, 7)
default_var(BRANCH_PRED, two_bit)
])
/// Supply defaults for extra cycles.
default_var(
DELAY_BRANCH_TARGET_CALC, 0,
EXTRA_PRED_TAKEN_BUBBLE, 0,
EXTRA_REPLAY_BUBBLE, 0,
EXTRA_JUMP_BUBBLE, 0,
EXTRA_BRANCH_BUBBLE, 0,
EXTRA_INDIRECT_JUMP_BUBBLE, 0,
EXTRA_NON_PIPELINED_BUBBLE, 1,
EXTRA_TRAP_BUBBLE, 1)
/// --------------------------
/// ISA-Specific Configuration
/// --------------------------
case(ISA, MINI, [
/// Mini-CPU Configuration:
/// Force predictor to fallthrough, since we can't predict early enough to help.
var(BRANCH_PRED, fallthrough)
], RISCV, [
/// RISC-V Configuration:
/// ISA options:
/// Currently supported uarch variants:
/// RV32IM 2.0, w/ FA ISA extensions WIP.
/// Machine width
default_var(
['# Include visualization. (0/1)'],
VIZ, 1,
['# Width of a "word". (32 for RV32X or 64 for RV64X)'],
WORD_WIDTH, 32)
define_vector(WORD, m5_WORD_WIDTH)
/// ISA extensions, 1, or 0 (following M5 boolean convention).
/// TODO. Currently formal checks are broken when EXT_F is set to 1.
/// TODO. Currently formal checks takes long time(~48 mins) when EXT_B is set to 1.
/// Hence, its disabled at present.
default_var(
EXT_I, 1,
EXT_E, 0,
EXT_M, 0,
EXT_A, 0,
EXT_F, 0,
EXT_D, 0,
EXT_Q, 0,
EXT_L, 0,
EXT_C, 0,
EXT_B, 0,
EXT_J, 0,
EXT_T, 0,
EXT_P, 0,
EXT_V, 0,
EXT_N, 0)
default_var(['# For the time[h] CSR register, after this many cycles, time increments.'],
CYCLES_PER_TIME_UNIT, 1000000000)
], MIPSI, [
], POWER, [
], [
/// Dummy "ISA".
var(DMEM_SIZE, 4) // Override for narrow address.
/// Force predictor to fallthrough, since we can't predict early enough to help.
var(BRANCH_PRED, ['fallthrough'])
])
default_var(VIZ, 0) // Default to 0 unless already defaulted to 1, based on ISA.
default_var(
['# Which program to assemble. The default depends on the ISA extension(s) choice.'],
PROG_NAME, m5_if_eq(m5_ISA, RISCV, m5_if_eq(m5_EXT_F, 1, fpu_test, m5_if_eq(m5_EXT_M, 1, divmul_test, m5_if_eq(m5_EXT_B, 1, bmi_test, cnt10))), cnt10))
///m5_if_eq(m5_EXT_F, 1, fpu_test, cnt10)
///m5_if_eq(m5_EXT_B, 1, bmi_test, cnt10)
/// =====Done Defining Configuration=====
define_hier(DATA_MEM_WORDS, m5_DMEM_SIZE)
/// For multi-core only:
if(m5_NUM_CORES > 1, [
/// Define hierarchies based on parameters.
define_hier(CORE, m5_NUM_CORES)
define_hier(VC, m5_NUM_VCS)
define_hier(PRIO, m5_NUM_PRIOS)
/// RISC-V Only
if_eq(m5_ISA, ['RISCV'], [''], ['m5_errprint_nl(['Multi-core supported for RISC-V only.'])'])
/// Headere flit fields.
define_vector_with_fields(FLIT, 32, UNUSED, m5_calc(m5_CORE_INDEX_CNT * 2 + m5_VC_INDEX_CNT), VC, m5_calc(m5_CORE_INDEX_CNT * 2), SRC, m5_CORE_INDEX_CNT, DEST, 0)
])
/// Characterize ISA and apply configuration.
/// Characterize the ISA, including:
/// NOMINAL_BRANCH_TARGET_CALC_STAGE: An expression that will evaluate to the earliest stage at which the branch target
/// can be available.
/// HAS_INDIRECT_JUMP: (0/1) Does this ISA have indirect jumps.
/// Defaults:
var(HAS_INDIRECT_JUMP, 0)
case(ISA, ['MINI'], [
/// Mini-CPU Characterization:
var(NOMINAL_BRANCH_TARGET_CALC_STAGE, m5_EXECUTE_STAGE)
], ['RISCV'], [
/// RISC-V Characterization:
var(NOMINAL_BRANCH_TARGET_CALC_STAGE, m5_DECODE_STAGE)
var(HAS_INDIRECT_JUMP, 1)
], ['MIPSI'], [
/// MIPS I Characterization:
var(NOMINAL_BRANCH_TARGET_CALC_STAGE, m5_DECODE_STAGE)
var(HAS_INDIRECT_JUMP, 1)
], ['POWER'], [
], ['DUMMY'], [
/// DUMMY Characterization:
var(NOMINAL_BRANCH_TARGET_CALC_STAGE, m5_DECODE_STAGE)
])
/// Calculated stages:
var(BRANCH_TARGET_CALC_STAGE, m5_calc(m5_NOMINAL_BRANCH_TARGET_CALC_STAGE + m5_DELAY_BRANCH_TARGET_CALC))
/// Calculated alignments:
var(REG_BYPASS_STAGES, m5_calc(m5_REG_WR_STAGE - m5_REG_RD_STAGE))
/// Latencies/bubbles calculated from stage parameters and extra bubbles:
/// (zero bubbles minimum if triggered in next_pc; minimum bubbles = computed-stage - next_pc-stage)
vars(PRED_TAKEN_BUBBLES, m5_calc(m5_BRANCH_PRED_STAGE - m5_NEXT_PC_STAGE + m5_EXTRA_PRED_TAKEN_BUBBLE),
REPLAY_BUBBLES, m5_calc(m5_REG_RD_STAGE - m5_NEXT_PC_STAGE + m5_EXTRA_REPLAY_BUBBLE),
JUMP_BUBBLES, m5_calc(m5_EXECUTE_STAGE - m5_NEXT_PC_STAGE + m5_EXTRA_JUMP_BUBBLE),
BRANCH_BUBBLES, m5_calc(m5_EXECUTE_STAGE - m5_NEXT_PC_STAGE + m5_EXTRA_BRANCH_BUBBLE),
INDIRECT_JUMP_BUBBLES, m5_calc(m5_EXECUTE_STAGE - m5_NEXT_PC_STAGE + m5_EXTRA_INDIRECT_JUMP_BUBBLE),
NON_PIPELINED_BUBBLES, m5_calc(m5_EXECUTE_STAGE - m5_NEXT_PC_STAGE + m5_EXTRA_NON_PIPELINED_BUBBLE),
TRAP_BUBBLES, m5_calc(m5_EXECUTE_STAGE - m5_NEXT_PC_STAGE + m5_EXTRA_TRAP_BUBBLE),
/// Bubbles between second issue of a long-latency instruction and
/// the replay of the instruction it squashed (so always zero).
SECOND_ISSUE_BUBBLES, 0)
vars(/// Bubbles between a no-fetch cycle and the next cycles (so always zero).
NO_FETCH_BUBBLES, 0)
var(stages_js, [''])
/// Define stages
/// $1: VIZ left of stage in diagram
/// $2: Stage name
/// $3: Next $1
macro(stages, ['m5_if_eq(['$2'],,,['m5_append_var(stages_js, ['defineStage("$2", ']m5_get($2_STAGE) - m5_NEXT_PC_STAGE[', $1, $3); '])m5_stages(m5_shift(m5_shift($@)))'])'])
stages(
8.5, NEXT_PC,
13, FETCH,
21, DECODE,
33, BRANCH_PRED,
41, REG_RD,
58, EXECUTE,
73.3, RESULT,
77.2, REG_WR,
93, MEM_WR,
100)
var(VIZ_STAGE, m5_MEM_WR_STAGE)
/// Retiming experiment.
///
/// The idea here, is to move all logic into @0 and see how well synthesis results compare vs. the timed model with
/// retiming enabled. In theory, synthesis should be able to produce identical results.
///
/// Unfortunately, this modeling does not work because of the redirection logic. When timed @0, the $GoodPathMask would
/// need to be redistributed, with each bit in a different stage to enable $commit to be computed in @0. So, to make
/// this work, each bit of $GoodPathMask would have to become a separate signal, and each signal assignment would need
/// its own @stage scope, affected by RETIMING_EXPERIMENT. Since this is all generated by M5, it was too
/// complicated to justify the experiment.
///
/// For now, the RETIMING_EXPERIMENT sets $commit to 1'b1, and produces results that make synthesis look good.
///
/// This option moves all logic into stage 0 (after determining relative timing interactions based on their original configuration).
/// The resulting SV is to be used for retiming experiments to see how well logic synthesis is able to retime the design.
if_def(RETIMING_EXPERIMENT, [
vars(NEXT_PC_STAGE, 0,
FETCH_STAGE, 0,
DECODE_STAGE, 0,
BRANCH_PRED_STAGE, 0,
BRANCH_TARGET_CALC_STAGE, 0,
REG_RD_STAGE, 0,
EXECUTE_STAGE, 0,
RESULT_STAGE, 0,
REG_WR_STAGE, 0,
MEM_WR_STAGE, 0)
])
/// ========================
/// Check Legality of Config
/// ========================
/// (Not intended to be exhaustive.)
/// Check that expressions are ordered.
fn(ordered, ..., {
if_eq(['$2'], [''], [''], {
if(m5_get($1) > m5_get($2), {
errprint(['$1 (']m5_get($1)[') is greater than $2 (']m5_get($2)[').']m5_nl)
})
ordered(m5_shift($@))
})
})
/// TODO:; It should be NEXT_PC_STAGE-1, below.
ordered(NEXT_PC_STAGE, FETCH_STAGE, DECODE_STAGE, BRANCH_PRED_STAGE, REG_RD_STAGE,
EXECUTE_STAGE, RESULT_STAGE, REG_WR_STAGE, MEM_WR_STAGE)
/// Check reg bypass limit
if(m5_REG_BYPASS_STAGES > 3, ['m5_errprint(['Too many stages of register bypass (']m5_REG_BYPASS_STAGES[').'])'])
/// ==================
/// Default Parameters
/// ==================
/// These may be overridden by specific ISA.
var(BIG_ENDIAN, 0)
/// =======================
/// ISA-specific Parameters
/// =======================
/// Macros for ISA-specific code.
var(isa, m5_translit(m5_ISA, ['A-Z'], ['a-z'])) // A lower-case version of ISA.
/// Instruction Memory macros are responsible for providing the instruction memory interface for fetch, as:
/// Inputs:
/// |fetch@m5_FETCH$Pc[m5_calc(m5_PC_MIN + m5_binary_width(m5_NUM_INSTRS-1) - 1):m5_PC_MIN]
/// Outputs:
/// |fetch/instr?$fetch$raw[m5_INSTR_RANGE] (at or after @m5_FETCH_STAGE--at for retiming experiment; +1 for fast array read)
default_var(IMEM_MACRO_NAME, m5_isa['_imem'])
/// For each ISA, define:
/// define_vector(INSTR, XX) // (or, define_vector_with_fields(...)) Instruction vector.
/// define_vector(ADDR, XX) // An address.
/// var(BITS_PER_ADDR, XX) // Each memory address holds XX bits.
/// define_vector(WORD, XX) // Width of general-purpose registers.
/// define_hier(REGS, XX) // General-purpose register file.
case(ISA,
['MINI'], [
define_vector_with_fields(INSTR, 40, DEST_CHAR, 32, EQUALS_CHAR, 24, SRC1_CHAR, 16, OP_CHAR, 8, SRC2_CHAR, 0)
define_vector(ADDR, 12)
var(BITS_PER_ADDR, 12) /// Each memory address holds 12 bits.
define_vector(WORD, 12)
define_hier(REGS, 8) /// (Plural to avoid name conflict w/ SV "reg" keyword.)
],
['RISCV'], [
/// Definitions matching "The RISC-V Instruction Set Manual Vol. I: User-Level ISA", Version 2.2.
define_vector(INSTR, 32)
define_vector(ADDR, 32)
var(BITS_PER_ADDR, 8) /// 8 for byte addressing.
define_vector(WORD, 32)
define_hier(REGS, m5_if(m5_EXT_E, 16, 32), 1)
define_hier(FPU_REGS, 32, 0) /// (though, the hierarchy is called /regs, not /fpu_regs)
],
['MIPSI'], [
define_vector_with_fields(INSTR, 32, OPCODE, 26, RS, 21, RT, 16, RD, 11, SHAMT, 6, FUNCT, 0)
define_vector(ADDR, 32)
var(BITS_PER_ADDR, 8) /// 8 for byte addressing.
define_vector(WORD, 32)
define_hier(REGS, 32, 1)
],
['POWER'], [
],
['DUMMY'], [
define_vector(INSTR, 2)
define_vector(ADDR, 2)
var(BITS_PER_ADDR, 2)
define_vector(WORD, 2)
define_hier(REGS, 8)
])
/// Computed ISA uarch Parameters (based on ISA-specific parameters).
var(ADDRS_PER_WORD, m5_calc(m5_WORD_CNT / m5_BITS_PER_ADDR))
var(SUB_WORD_BITS, m5_binary_width(m5_calc(m5_ADDRS_PER_WORD - 1)))
var(ADDRS_PER_INSTR, m5_calc(m5_INSTR_CNT / m5_BITS_PER_ADDR))
var(SUB_PC_BITS, m5_binary_width(m5_calc(m5_ADDRS_PER_INSTR - 1)))
define_vector(PC, m5_ADDR_HIGH, m5_SUB_PC_BITS)
var(FULL_PC, ['{$Pc, ']m5_SUB_PC_BITS[''b0}'])
define_hier(DATA_MEM_ADDRS, m5_calc(m5_DATA_MEM_WORDS_HIGH * m5_ADDRS_PER_WORD)) // Addressable data memory locations.
var(INJECT_RETURNING_LD, m5_calc(m5_LD_RETURN_ALIGN > 0))
var(PENDING_ENABLED, m5_INJECT_RETURNING_LD)
/// ==============
/// VIZ Parameters
/// ==============
var(/// Amount to shift mem left (to make room for FP regs).
VIZ_MEM_LEFT_ADJUST, m5_if(m5_EXT_F, 190, 0))
/// =========
/// Redirects
/// =========
/// These macros characterize redirects, generate logic, and generate visualization.
/// Redirect processing is performed based on the following:
/// o Redirects are currently provided in a strict order that is not parameterized.
/// o Redirects on earlier instructions mask those of later instructions (using $GoodPathMask and
/// prioritization within the redirect cycle).
/// o A redirect may mask later redirect triggers on the same instruction, depending whether
/// the redirect is aborting or non-aborting.
/// o Non-aborting redirects do not mask later redirect triggers, so later non-aborting
/// redirects have priority.
/// o Aborting redirects mask later redirect triggers, so earlier aborting
/// redirects have priority
/// TODO: It is possible to create a generic macro for a pipeline with redirects.
/// The PC redirection would become $ANY redirection. Redirected transactions would come from subhierarchy of
/// pipeline, eg: |fetch/branch_redir$pc (instead of |fetch$branch_target).
/// TODO: The code would be a little cleaner to create a multi-line macro body for redirect conditions, such as
/// \TLV redirect_conditions()
/// m5_\redirect_condition_logic
/// which becomes:
/// \TLV redirect_conditions()
/// @2
/// $trigger1_redir = $trigger1 && >>2$GoodPath[2]; // Aborting trigger.
/// @2
/// $trigger2_redir = $trigger2 && !(1'b0 || $trigger1) && >>2$GoodPath[2];
/// @3
/// $trigger3_redir = $trigger3 && !(1'b0 || $trigger1) && >>3$GoodPath[3];
/// ...
/// This would replace m5_redir_cond (and m5_redirect_masking_triggers).
/// Redirects are described in the TLV code. Supporting macro definitions are here.
/// m5_process_redirect_conditions appends definitions to the following macros whose initial values are given here.
var(NEGATIVE_ONE, -1)
var(redirect_list, ['NEGATIVE_ONE']) /// list fed to m5_ordered
var(redirect_squash_terms, ['']) /// & terms to apply to $GoodPathMask, each reflects the redirect shadow and abort of a trigger that becomes visible.
var(redirect_shadow_terms, ['['']']) /// & terms to apply to $RvfiGoodPathMask, each reflects the redirect shadow of a trigger that becomes visible (for formal verif only).
var(redirect_pc_terms, ['']) /// ternary operator terms for redirecting PC (later-stage redirects must be first)
var(abort_terms, ['1'b0']) /// || terms for an instruction's abort condition
macro(redirect_masking_triggers, ['1'b0']) /// || terms combining earlier aborting triggers on the same instruction, using "$1" for alignment.
/// Each trigger uses this term as it is built to mask its effect, so aborting triggers have the final say.
var(redirect_viz, ['']) /// JS code to provide parameters for visualization of the waterfall diagram.
var(redirect_cell_viz, ['']) /// JS code to provide parameters for visualization of a cell of waterfall diagram.
/// Redirection conditions. These conditions must be defined from fewest bubble cycles to most.
/// See redirection logic for more detail.
/// Create several defines with items per redirect condition.
var(NUM_REDIRECT_CONDITIONS, 0) // Incremented for each condition.
macro(process_redirect_conditions, [
if_eq(['$@'], ['['']'], [''], [
process_redirect_condition($1, m5_NUM_REDIRECT_CONDITIONS)
process_redirect_conditions(m5_shift($@))
])
var(NUM_REDIRECT_CONDITIONS, m5_calc(m5_NUM_REDIRECT_CONDITIONS + 1))
])
var(MAX_REDIRECT_BUBBLES, m5_TRAP_BUBBLES)
/// Called by m5_process_redirect_conditions (plural) for each redirect condition from fewest bubbles to most to append
/// to various definitions, initialized above.
/// Args:
/// $1: name of define of number of bubble cycles (The same name can be used multiple times, but once per aborting redirect.)
/// $2: condition signal of triggering instr. This condition must be explicitly masked by earlier
/// trigger conditions that take priority.
/// $3: target PC signal of triggering instruction
/// $4: 1 for an aborting redirect (0 otherwise)
/// $5: VIZ text for redirect bullet
/// $6: VIZ color for redirect bullet
/// $7: VIZ bullet left
/// $8: VIZ bullet top
/// $9: 1 for bad-path redirects (used by RVFI only)
/// $10: (opt) ['wait'] to freeze fetch until subsequent redirect
macro(process_redirect_condition, [
/// expression in @m5_NEXT_PC_STAGE asserting for the redirect condition.
/// = instruction triggers this condition && it's on the current path && it's not masked by an earlier aborting redirect
/// of this instruction.
/// Params: $@ (m5_redirect_masking_triggers contains param use)
macro(redir_cond,
['(>>']m5_get($1_BUBBLES)['$2 && !(']m5_eval(m5_redirect_masking_triggers())[') && $GoodPathMask'][m5_get($1_BUBBLES)][')'])
append_var(redirect_list, [', $1_BUBBLES'])
append_var(redirect_squash_terms,
[' & (']m5_redir_cond($@)[' ? {{']m5_calc(m5_MAX_REDIRECT_BUBBLES + 1 - m5_get($1_BUBBLES) - $4)['{1'b1}}, {']m5_calc(m5_get($1_BUBBLES) + $4)['{1'b0}}} : {']m5_calc(m5_MAX_REDIRECT_BUBBLES + 1)['{1'b1}})'])
append_var(redirect_shadow_terms,
[' & (']m5_redir_cond($@)[' ? {{']m5_calc(m5_MAX_REDIRECT_BUBBLES + 1 - m5_get($1_BUBBLES) - $9)['{1'b1}}, {']m5_calc(m5_get($1_BUBBLES) + $9)['{1'b0}}} : {']m5_calc(m5_MAX_REDIRECT_BUBBLES + 1)['{1'b1}})'])
prepend_var(redirect_pc_terms,
m5_redir_cond($@)[' ? {>>']m5_get($1_BUBBLES)['$3, ']m5_if_eq($10, wait, 1'b1, 1'b0)['} : '])
if(['$4'], [
///m5_def(ABORT_BEFORE_$1, m5_abort_terms) // The instruction was aborted prior to this abort condition.
append_var(abort_terms,
[' || $2'])
append_macro(redirect_masking_triggers,
['[' || >>['m5_get(']$']['1['_BUBBLES)']$2']'])
])
append_var(redirect_viz,
['ret.$2 = redirect_cond("$2", $5, $6, $7, $8); '])
append_var(redirect_cell_viz,
['if (stage == ']m5_get($1_BUBBLES)[') {ret = ret.concat(render_redir("$2", '/instr$2', $5, $6, ']m5_if_defined_as(EXTRA_$1_BUBBLE, 1, 1, 0)['))}; '])
])
/// Specify and process redirect conditions.
/// TODO: Found a bug...
/// Priority is naturally given to later triggers.
/// Must explicitly mask earlier higher-priority triggers.
///
process_redirect_conditions(
['SECOND_ISSUE, $second_issue, $Pc, 1, "2nd", "orange", 11.8, 26.2, 1'],
['NO_FETCH, $NoFetch, $Pc, 1, "...", "red", 11.8, 30, 1, wait'],
m5_if_eq(m5_BRANCH_PRED, fallthrough, [''], ['['PRED_TAKEN, $pred_taken_branch, $branch_target, 0, "PT", "#0080ff", 37.4, 26.2, 0'],'])
['REPLAY, $replay, $Pc, 1, "Re", "#ff8000", 50, 29.1, 0'],
['JUMP, $jump, $jump_target, 0, "Jp", "purple", 61, 11, 0'],
['BRANCH, $mispred_branch, $branch_redir_pc, 0, "Br", "blue", 70, 20, 0'],
m5_if_eq(m5_HAS_INDIRECT_JUMP, 1, ['['INDIRECT_JUMP, $indirect_jump, $indirect_jump_target, 0, "IJ", "purple", 68, 16, 0'],'], [''])
['NON_PIPELINED, $non_pipelined, $pc_inc, 0, "NP", "red", 75.6, 25, 1, wait'],
['TRAP, $aborting_trap, $trap_target, 1, "AT", "#ff0080", 75.6, 7, 0'],
['TRAP, $non_aborting_trap, $trap_target, 0, "T", "#ff0080", 75.6, 12, 0'])
/// Ensure proper order.
/// TODO: It would be great to auto-sort.
/// TODO: JUMP timing is nominally DECODE for most uarch's (immediate jumps), but this ordering forces
/// redirect to be no earlier than REPLAY (REG_RD).
ordered(m5_redirect_list)
/// A macro for generating a when condition for instruction logic (just for a bit of power savings). (We probably won't
/// bother using it, but it's available in any case.)
/// m5_prev_instr_valid_through(redirect_bubbles) is deasserted by redirects up to the given number of cycles on the previous instruction.
/// Since we can be looking back an arbitrary number of cycles, we'll force invalid if $reset.
macro(prev_instr_valid_through,
['(! $reset && >>m5_calc(1 - $1)$next_good_path_mask[$1])'])
///same as <<m5_calc($1)$GoodPathMask[$1]), but accessible 1 cycle earlier and without $reset term.
/// ====
/// CSRs
/// ====
/// Macro to define a new CSR.
/// Eg: m5_define_csr(['mycsr'], ['12'b123'], ['12, NIBBLE_FIELD, 8, BYTE_FIELD'], ['12'b0'], ['12'hFFF'], 1)
/// $1: CSR name (lowercase)
/// $2: CSR index
/// $3: CSR fields (as in m5_define_fields)
/// $4: Reset value
/// $5: Writable bits mask
/// $6: 0, 1, RO indicating whether to allow side-effect writes.
/// If 1, these signals in scope |fetch@m5_EXECUTE_STAGE must provide a write value:
/// o $csr_<csr_name>_hw_wr: 1/0, 1 if a write is to occur (like hw_wr_mask == '0)
/// o $csr_<csr_name>_hw_wr_value: the value to write
/// o $csr_<csr_name>_hw_wr_mask: mask of bits to write
/// Side-effect writes take place prior to corresponding CSR software reads and writes, though it should be
/// rare that a bit can be written by both hardware and software.
/// If RO, the CSR is read-only and code can be simpler. The CSR signal must be provided:
/// o $csr_<csr_name>: The read-only CSR value (used in |fetch@m5_EXECUTE_STAGE).
/// Variables set by this macro:
/// List of CSRs.
var(csrs, [''])
var(num_csrs, 0)
/// Arguments given to this macro for each CSR.
/// Initial value of CSR read result expression, initialized to ternary default case (X).
var(csrrx_rslt_expr, m5_WORD_CNT'bx)
/// Initial value of OR expression for whether CSR index is valid.
var(valid_csr_expr, ['1'b0'])
/// VIZ initEach and renderEach JS code to define fabricjs objects for the CSRs.
var(csr_viz_init_each, [''])
var(csr_viz_render_each, [''])
/// m5_define_csr(name, index (12-bit SV-value), fields (as in m5_define_vector), reset_value (SV-value), writable_mask (SV-value), side-effect_writes (bool))
/// Adds a CSR.
/// Requires provision of: $csr_<name>_hw_[wr, wr_mask, wr_value].
macro(define_csr, [
define_vector_with_fields(['CSR_']m5_uppercase(['$1']), $3)
append_var(csrs, m5_if_eq(m5_csrs, [''], [''], ['[',']'])['['$1']'])
var(csr_$1_args, ['$@'])
set(csrrx_rslt_expr, ['$is_csr_$1 ? {{']m5_calc(32 - m5_get(['CSR_']m5_uppercase(['$1'])['_CNT']))['{1'b0}}, $csr_$1} : ']m5_csrrx_rslt_expr)
set(valid_csr_expr, m5_valid_csr_expr[' || $is_csr_$1'])
/// VIZ
set(csr_viz_init_each, m5_csr_viz_init_each['csr_objs["$1_box"] = new fabric.Rect({top: 40 + 18 * ']m5_num_csrs[', left: 20, fill: "white", width: 175, height: 14, visible: true}); csr_objs["$1"] = new fabric.Text("", {top: 40 + 18 * ']m5_num_csrs[', left: 30, fontSize: 14, fontFamily: "monospace"}); '])
set(csr_viz_render_each, m5_csr_viz_render_each['let old_val_$1 = '/instr$csr_$1'.asInt(NaN).toString(); let val_$1 = '/instr$csr_$1'.step(1).asInt(NaN).toString(); let $1mod = ']m5_if_eq($6, 1, [''/instr$csr_$1_hw_wr'.asBool(false)'], ['val_$1 === old_val_$1'])['; let $1name = String("$1"); let oldVal$1 = $1mod ? `(${old_val_$1})` : ""; this.getInitObject("$1").set({text: $1name + ": " + val_$1 + oldVal$1}); this.getInitObject("$1").set({fill: $1mod ? "blue" : "black"}); '])
set(num_csrs, m5_calc(m5_num_csrs + 1))
])
case(ISA, RISCV, [
if_defined_as(NO_COUNTER_CSRS, 1, [''], [
/// TODO: This should move to risc-v_defs (which now has a basic map from name to value for the assembler).
/// Define Counter CSRs
/// Name Index Fields Reset Value Writable Mask Side-Effect Writes
define_csr(cycle, 12'hC00, ['32, CYCLE, 0'], ['32'b0'], ['{32{1'b1}}'], 1)
define_csr(cycleh, 12'hC80, ['32, CYCLEH, 0'], ['32'b0'], ['{32{1'b1}}'], 1)
define_csr(time, 12'hC01, ['32, CYCLE, 0'], ['32'b0'], ['{32{1'b1}}'], 1)
define_csr(timeh, 12'hC81, ['32, CYCLEH, 0'], ['32'b0'], ['{32{1'b1}}'], 1)
define_csr(instret, 12'hC02, ['32, INSTRET, 0'], ['32'b0'], ['{32{1'b1}}'], 1)
define_csr(instreth, 12'hC82, ['32, INSTRETH, 0'], ['32'b0'], ['{32{1'b1}}'], 1)
if(m5_EXT_F, [
define_csr(fflags, 12'h001, ['5, FFLAGS, 0'], ['5'b0'], ['{5{1'b1}}'], 1)
define_csr(frm, 12'h002, ['3, FRM, 0'], ['3'b0'], ['{3{1'b1}}'], 1)
define_csr(fcsr, 12'h003, ['8, FCSR, 0'], ['8'b0'], ['{8{1'b1}}'], 1)
])
])
/// For NoC support
if(m5_NUM_CORES > 1, [
/// As defined in: https://docs.google.com/document/d/1cDUv8cuYF2kha8r6DSv-8pwszsrSP3vXsTiAugRkI1k/edit?usp=sharing
/// TODO: Find appropriate indices.
/// Name Index Fields Reset Value Writable Mask Side-Effect Writes
define_csr(pktdest, 12'h800, ['m5_CORE_INDEX_HIGH, DEST, 0'], ['m5_CORE_INDEX_HIGH'b0'], ['{m5_CORE_INDEX_HIGH{1'b1}}'], 0)
define_csr(pktwrvc, 12'h801, ['m5_VC_INDEX_HIGH, VC, 0'], ['m5_VC_INDEX_HIGH'b0'], ['{m5_VC_INDEX_HIGH{1'b1}}'], 0)
define_csr(pktwr, 12'h802, ['m5_WORD_HIGH, DATA, 0'], ['m5_WORD_HIGH'b0'], ['{m5_WORD_HIGH{1'b1}}'], 0)
define_csr(pkttail, 12'h803, ['m5_WORD_HIGH, DATA, 0'], ['m5_WORD_HIGH'b0'], ['{m5_WORD_HIGH{1'b1}}'], 0)
define_csr(pktctrl, 12'h804, ['1, BLOCK, 0'], ['1'b0'], ['1'b1'], 0)
define_csr(pktrdvcs, 12'h808, ['m5_VC_HIGH, VCS, 0'], ['m5_VC_HIGH'b0'], ['{m5_VC_HIGH{1'b1}}'], 0)
define_csr(pktavail, 12'h809, ['m5_VC_HIGH, AVAIL_MASK, 0'], ['m5_VC_HIGH'b0'], ['{m5_VC_HIGH{1'b1}}'], 1)
define_csr(pktcomp, 12'h80a, ['m5_VC_HIGH, AVAIL_MASK, 0'], ['m5_VC_HIGH'b0'], ['{m5_VC_HIGH{1'b1}}'], 1)
define_csr(pktrd, 12'h80b, ['m5_WORD_HIGH, DATA, 0'], ['m5_WORD_HIGH'b0'], ['{m5_WORD_HIGH{1'b0}}'], RO)
define_csr(core, 12'h80d, ['m5_CORE_INDEX_HIGH, CORE, 0'], ['m5_CORE_INDEX_HIGH'b0'], ['{m5_CORE_INDEX_HIGH{1'b1}}'], RO)
define_csr(pktinfo, 12'h80c, ['m5_calc(m5_CORE_INDEX_HIGH + 3), SRC, 3, MID, 2, AVAIL, 1, COMP, 0'],
['m5_calc(m5_CORE_INDEX_HIGH + 3)'b100'], ['m5_calc(m5_CORE_INDEX_HIGH + 3)'b0'], 1)