-
Notifications
You must be signed in to change notification settings - Fork 11
/
cpp.ml
1683 lines (1487 loc) · 66.5 KB
/
cpp.ml
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
(*! C++ backend !*)
open Common
module Extr = Cuttlebone.Extr
let debug = false
(* #line pragmas make the C++ code harder to read, and they cover too-large a
scope (in particular, the last #line pragma in a program overrides positions
for all subsequent code, while we'd want to use the C++ positions for these
lines) *)
let add_line_pragmas = false
(* The overhead of recording offsets and copying only the corresponding data
seems too high to make the stack-based approach worthwhile, even when a rule
touches many registers (copying the whole log at once is quite fast, while
iterating through the list of modified registers is much slower, even when
using explicit offsets into the structures rather than register names). *)
let use_dynamic_logs = false
let use_offsets_in_dynamic_log = false
type ('pos_t, 'var_t, 'fn_name_t, 'rule_name_t, 'reg_t, 'ext_fn_t) cpp_rule_t = {
rl_external: bool;
rl_name: 'rule_name_t;
rl_reg_histories: 'reg_t -> Extr.register_history;
rl_body: (('pos_t, 'reg_t) Extr.register_annotation,
'var_t, 'fn_name_t, 'reg_t, 'ext_fn_t) Extr.rule;
}
type ('pos_t, 'var_t, 'fn_name_t, 'rule_name_t, 'reg_t, 'ext_fn_t) cpp_input_t = {
cpp_classname: string;
cpp_module_name: string;
cpp_pos_of_pos: 'pos_t -> Pos.t;
cpp_var_names: 'var_t -> string;
cpp_fn_names: 'fn_name_t -> string;
cpp_rule_names: ?prefix:string -> 'rule_name_t -> string;
cpp_scheduler: ('pos_t, 'rule_name_t) Extr.scheduler;
cpp_rules: ('pos_t, 'var_t, 'fn_name_t, 'rule_name_t, 'reg_t, 'ext_fn_t) cpp_rule_t list;
cpp_registers: 'reg_t array;
cpp_register_sigs: 'reg_t -> reg_signature;
cpp_register_kinds: 'reg_t -> Extr.register_kind;
cpp_ext_sigs: 'ext_fn_t -> (ffi_signature * [`Function | `Method]);
cpp_extfuns: string option;
}
type cpp_output_t =
{ co_modname: string; co_hpp: Buffer.t; co_cpp: Buffer.t }
let sprintf = Printf.sprintf
let fprintf = Printf.fprintf
type program_info =
{ mutable pi_committed: bool;
mutable pi_needs_multiprecision: bool;
mutable pi_user_types: (string * typ) list;
pi_ext_funcalls: (Common.ffi_signature, unit) Hashtbl.t }
let fresh_program_info () =
{ pi_committed = false;
pi_needs_multiprecision = false;
pi_user_types = [];
pi_ext_funcalls = Hashtbl.create 50 }
let assert_uncommitted { pi_committed; _ } =
assert (not pi_committed)
let request_multiprecision pi =
assert_uncommitted pi;
pi.pi_needs_multiprecision <- true
let register_type (pi: program_info) nm tau =
match List.assoc_opt nm pi.pi_user_types with
| Some tau' ->
if tau <> tau' then
failwith (sprintf "Incompatible uses of type name `%s':\n%s\n%s"
nm (typ_to_string tau) (typ_to_string tau'))
| None ->
assert_uncommitted pi;
pi.pi_user_types <- (nm, tau) :: pi.pi_user_types
let gensym_prefix = "_"
let gensym, gensym_reset = make_gensym gensym_prefix
(* Mangling takes care of collisions with the gensym *)
module Mangling = struct
let cpp_reserved =
StringSet.of_list
["alignas"; "alignof"; "and"; "and_eq"; "asm"; "atomic_cancel";
"atomic_commit"; "atomic_noexcept"; "auto"; "bitand"; "bitor"; "bool";
"break"; "case"; "catch"; "char"; "char8_t"; "char16_t"; "char32_t";
"class"; "compl"; "concept"; "const"; "consteval"; "constexpr";
"constinit"; "const_cast"; "continue"; "co_await"; "co_return";
"co_yield"; "decltype"; "default"; "delete"; "do"; "double";
"dynamic_cast"; "else"; "enum"; "explicit"; "export"; "extern"; "false";
"float"; "for"; "friend"; "goto"; "if"; "inline"; "int"; "long";
"mutable"; "namespace"; "new"; "noexcept"; "not"; "not_eq"; "nullptr";
"operator"; "or"; "or_eq"; "private"; "protected"; "public"; "reflexpr";
"register"; "reinterpret_cast"; "requires"; "return"; "short"; "signed";
"sizeof"; "static"; "static_assert"; "static_cast"; "struct"; "switch";
"synchronized"; "template"; "this"; "thread_local"; "throw"; "true";
"try"; "typedef"; "typeid"; "typename"; "union"; "unsigned"; "using";
"virtual"; "void"; "volatile"; "wchar_t"; "while"; "xor"; "xor_eq"]
let cuttlesim_reserved =
StringSet.of_list
["array"; "unit"; "bits"]
let reserved =
StringSet.union cpp_reserved cuttlesim_reserved
let mangling_prefix = "renamed_cpp"
let specials_re = Str.regexp (sprintf "^\\(_[A-Z]\\|%s\\|%s\\)" mangling_prefix gensym_prefix)
let dunder_re = Str.regexp "__+"
let dunder_anchored_re = Str.regexp "^.*__"
let dunder_target_re = Str.regexp "_\\(dx\\)\\([0-9]\\)_"
let valid_name_re = Str.regexp "^[A-Za-z_][A-Za-z0-9_]*"
let needs_mangling name =
StringSet.mem name reserved
|| Str.string_match specials_re name 0
|| Str.string_match dunder_anchored_re name 0
let escape_dunders name =
let name = Str.global_replace dunder_target_re "_\\10\\2_" name in
let subst _ = sprintf "_dx%d_" (Str.match_end () - Str.match_beginning ()) in
Str.global_substitute dunder_re subst name
let check_valid name =
if not @@ Str.string_match valid_name_re name 0 then
failwith (sprintf "Invalid name: `%s'" name)
let add_prefix prefix name =
if prefix = "" then name else prefix ^ "_" ^ name
let mangle_name ?(prefix="") name =
check_valid name;
let unmangled = add_prefix prefix name in
if needs_mangling unmangled then
escape_dunders (add_prefix prefix (mangling_prefix ^ name))
else unmangled
let mangle_register_sig r =
{ r with reg_name = mangle_name r.reg_name }
let mangle_function_sig (f, kind) =
{ f with ffi_name = mangle_name f.ffi_name }, kind
let default v = function
| Some v' -> v'
| None -> v
let mangle_unit u =
{ u with (* The prefixes are needed to prevent collisions with ‘prims::’ *)
cpp_classname = mangle_name ~prefix:"module" u.cpp_classname;
cpp_var_names = (fun v -> v |> u.cpp_var_names |> mangle_name);
cpp_fn_names = (fun v -> v |> u.cpp_fn_names |> mangle_name);
cpp_rule_names = (fun ?prefix rl ->
rl |> u.cpp_rule_names |> mangle_name ~prefix:(default "rule" prefix));
cpp_register_sigs = (fun r -> r |> u.cpp_register_sigs |> mangle_register_sig);
cpp_ext_sigs = (fun f -> f |> u.cpp_ext_sigs |> mangle_function_sig) }
end
let cpp_enum_name pi sg =
let name = Mangling.mangle_name ~prefix:"enum" sg.enum_name in
register_type pi name (Enum_t sg); name
let cpp_struct_name pi sg =
let name = Mangling.mangle_name ~prefix:"struct" sg.struct_name in
register_type pi sg.struct_name (Struct_t sg); name
let cpp_type_of_size
(pi: program_info)
(stem: string) (sz: int) =
assert (sz >= 0);
if sz > 64 then
request_multiprecision pi;
if sz = 0 then
"unit"
else if sz <= 1024 then
sprintf "%s<%d>" stem sz
else
failwith (sprintf "Unsupported size: %d" sz)
let cpp_value_type_of_size
(pi: program_info)
(sz: int) =
cpp_type_of_size pi "bits_t" sz
let rec cpp_type_of_type
(pi: program_info)
(tau: typ) =
match tau with
| Bits_t sz -> cpp_type_of_size pi "bits" sz
| Enum_t sg -> cpp_enum_name pi sg
| Struct_t sg -> cpp_struct_name pi sg
| Array_t sg -> cpp_type_of_array pi sg
and cpp_type_of_array pi { array_type; array_len } =
sprintf "array<%s, %d>"
(cpp_type_of_type pi array_type) array_len
let cpp_enumerator_name pi ?(enum=None) nm =
let nm = Mangling.mangle_name nm in
match enum with
| None -> nm
| Some sg -> sprintf "%s::%s" (cpp_enum_name pi sg) nm
let cpp_field_name nm =
Mangling.mangle_name nm
let register_subtypes (pi: program_info) tau =
let rec loop tau = match tau with
| Bits_t sz -> if sz > 64 then request_multiprecision pi
| Enum_t sg -> ignore (cpp_enum_name pi sg)
| Struct_t sg -> ignore (cpp_struct_name pi sg);
List.iter (loop << snd) sg.struct_fields
| Array_t { array_type; _ } -> loop array_type in
loop tau
let z_to_str (base: [`Bin | `Hex]) bitlen z =
let b, w = match base with
| `Hex -> "x", (bitlen + 7) / 8
| `Bin -> "b", bitlen in
let fmt = sprintf "%%0%d%s" w b in
Z.format fmt z
let cpp_const_init (pi: program_info) immediate sz cst =
assert (sz >= 0);
if sz > 64 then
request_multiprecision pi;
if sz = 0 then
if immediate then "prims::tt.v" else "prims::tt"
else
let imm_suffix = if immediate then "v" else "" in
let wide = sz > 8 in
let trivial = Z.equal cst Z.zero || Z.equal cst Z.one in
let bitlen = if wide && trivial then 0 else sz in
if bitlen <= 8 && sz <= 64 then
let lit = z_to_str `Bin bitlen cst in
let prefix = sprintf "%d'" sz in
prefix ^ lit ^ "_b" ^ imm_suffix
else if sz <= 1024 then
let lit = z_to_str `Hex bitlen cst in
let prefix = sprintf "0x%d'" sz in
prefix ^ lit ^ "_x" ^ imm_suffix
else
failwith (sprintf "Unsupported size: %d" sz)
let cpp_type_needs_allocation _tau =
false (* boost::multiprecision has literals *)
let assert_bits (tau: typ) =
match tau with
| Bits_t sz -> sz
| _ -> failwith "Expecting bits, not struct or enum"
let cpp_ext_funcall f (kind: [`Function | `Method]) a =
(* The current implementation of external functions requires the client to
pass a class implementing those functions as a template argument. An
other approach would have made external functions virtual methods, but
then they couldn't have been templated functions. *)
(* Originally, the call was written as ‘extfuns.template %s()’to ensure that
‘extfuns.xyz<p>()’ would not parsed as a comparison, but clang rejects this
for non-templated functions in version 10. Users will have to declare
their function names to be ‘template xyz<p>’ instead of ‘xyz<p>’ *)
sprintf "extfuns.%s(%s%s)" f (if kind = `Method then "*this, " else "") a
let cpp_bits1_fn_name (f: Extr.PrimTyped.fbits1) =
match f with
| Not _ -> "~"
| SExt (_sz, width) -> sprintf "prims::sext<%d>" width
| ZExtL (_sz, width) -> sprintf "prims::zextl<%d>" width
| ZExtR (_sz, width) -> sprintf "prims::zextr<%d>" width
| Repeat (_sz, times) -> sprintf "prims::repeat<%d>" times
| Slice (_sz, offset, width) -> sprintf "prims::slice<%d, %d>" offset width
| Lowered (IgnoreBits _sz) -> "prims::ignore"
| Lowered (DisplayBits _) -> failwith "Do not use DisplayBits; use Display with Unpack instead"
let cpp_bits2_fn_name (f: Extr.PrimTyped.fbits2) =
match f with
| And _ -> `Infix "&"
| Or _ -> `Infix "|"
| Xor _ -> `Infix "^"
| Lsl _ -> `Infix "<<"
| Lsr _ -> `Infix ">>"
| Asr _ -> `Fn "prims::asr"
| Concat _ -> `Fn "prims::concat"
| Sel _ -> `Array
| SliceSubst (_sz, offset, _width) -> `Fn (sprintf "prims::slice_subst<%d>" offset)
| IndexedSlice (_sz, width) -> `Fn (sprintf "prims::islice<%d>" width)
| Plus _ -> `Infix "+"
| Minus _ -> `Infix "-"
| Mul _ -> `Infix "*"
| EqBits (_, true) -> `Infix "!="
| EqBits (_, false) -> `Infix "=="
| Compare (true, cmp, _) ->
`Fn (match cmp with CLt -> "slt" | CGt -> "sgt" | CLe -> "sle" | CGe -> "sge")
| Compare (false, cmp, _) ->
`Infix (match cmp with CLt -> "<" | CGt -> ">" | CLe -> "<=" | CGe -> ">=")
let cuttlesim_hpp =
(* resources.ml is auto-generated *)
Resources.cuttlesim_hpp
let cuttlesim_hpp_fname =
"cuttlesim.hpp"
let reconstruct_switch action =
let rec loop v = function
| Extr.If (_, _,
Extr.Binop (_,
(Extr.PrimTyped.Eq (_, false) |
Extr.PrimTyped.Bits2 (Extr.PrimTyped.EqBits (_, false))),
Extr.Var (_, v', ((Extr.Bits_t _ | Extr.Enum_t _) as tau), _m),
value),
tbr, fbr) when (match v with Some v -> v' = v | None -> true) ->
(match Cuttlebone.Util.interp_arithmetic value with
| None -> None
| Some cst ->
let default, branches = match loop (Some v') fbr with
| Some (_, _, default, branches) -> default, branches
| None -> fbr, [] in
Some (v', tau, default, (cst, tbr) :: branches))
| _ -> None in
match loop None action with
| Some (_, _, _, [_]) | None -> None
| res -> res
type target_info =
{ tau: typ; mutable declared: bool; name: var_t }
type assignment_target =
| NoTarget
| VarTarget of target_info
type assignment_result =
| NotAssigned
| Assigned of var_t
| PureExpr of string
| ImpureExpr of string
let assignment_result_to_string (d: assignment_result) =
match d with
| NotAssigned -> sprintf "NotAssigned"
| Assigned v -> sprintf "Assigned %s" v
| PureExpr s -> sprintf "PureExpr %s" s
| ImpureExpr s -> sprintf "ImpureExpr %s" s
let compile (type pos_t var_t fn_name_t rule_name_t reg_t ext_fn_t)
(hpp: (pos_t, var_t, fn_name_t, rule_name_t, reg_t, ext_fn_t) cpp_input_t) =
let buffer = ref (Buffer.create 0) in
let hpp = Mangling.mangle_unit hpp in
let nl _ = Buffer.add_string !buffer "\n" in
let pk k fmt = Printf.kbprintf k !buffer fmt in
let p fmt = pk nl fmt in
let pr fmt = pk ignore fmt in
let p_buffer b = Buffer.add_buffer !buffer b in
let set_buffer b = let b' = !buffer in buffer := b; b' in
let program_info = fresh_program_info () in
let cpp_type_of_type = cpp_type_of_type program_info in
let cpp_type_of_array = cpp_type_of_array program_info in
let cpp_value_type_of_size = cpp_value_type_of_size program_info in
let cpp_enum_name = cpp_enum_name program_info in
let cpp_struct_name = cpp_struct_name program_info in
let cpp_enumerator_name = cpp_enumerator_name program_info in
let cpp_const_init = cpp_const_init program_info in
let reg_list =
Array.to_list hpp.cpp_registers in
let may_fail_fast =
Cuttlebone.Util.may_fail_without_revert reg_list in
let needs_data0_and_data1 =
Cuttlebone.Util.need_data0_and_data1 reg_list in
let rec iter_sep sep body = function
| [] -> ()
| item :: [] -> body item
| item :: items -> body item; sep (); iter_sep sep body items in
let p_comment fmt =
pr "/* "; pk (fun _ -> pr " */"; nl ()) fmt in
let p_ifdef condition pbody =
p "#if%s" condition;
pbody ();
p "#endif" in
let p_ifnminimal pbody =
p_ifdef "ndef SIM_MINIMAL" pbody in
let p_scoped header ?(terminator="") pbody =
p "%s {" header;
let r = pbody () in
p "}%s" terminator;
r in
let p_fn ~typ ~name ?(args="") ?(annot="") pbody =
p_scoped (sprintf "%s %s(%s)%s" typ name args annot) pbody in
let p_includeguard pbody =
let cpp_define = sprintf "%s_HPP" (String.uppercase_ascii hpp.cpp_classname) in
p "#ifndef %s" cpp_define;
p "#define %s" cpp_define;
nl ();
pbody ();
p "#endif" in
let p_cpp_decl ?(prefix = "") ?init typ name =
pr "%s" prefix;
match init with
| None -> p "%s %s;" typ name
| Some init -> p "%s %s = %s;" typ name init in
let p_decl ?(prefix = "") ?init tau name =
p_cpp_decl ~prefix ?init (cpp_type_of_type tau) name in
let bits_to_Z bits =
Z.(Array.fold_right (fun b z ->
(if b then one else zero) + shift_left z 1)
bits zero) in
let rec sp_value ?(immediate=false) (v: value) =
match v with
| Bits bs -> sp_bits_value ~immediate bs
| Enum (sg, v) -> sp_enum_value sg v
| Struct (sg, fields) -> sp_struct_value sg fields
| Array (tau, values) -> sp_array_value tau values
and sp_bits_value ?(immediate=false) bs =
let z = bits_to_Z bs in
let bitlength = Array.length bs in
cpp_const_init immediate bitlength z
and sp_enum_value sg v =
match enum_find_field_opt sg v with
| None -> sprintf "static_cast<%s>(%s.v)" (cpp_enum_name sg) (sp_bits_value v)
| Some nm -> cpp_enumerator_name ~enum:(Some sg) nm
and sp_struct_value sg fields =
let fields = String.concat ", " (List.map sp_value fields) in
sprintf "%s{ %s }" (cpp_struct_name sg) fields
and sp_array_value sg values =
let vals = String.concat ", " (List.map sp_value (Array.to_list values)) in
sprintf "%s{%s}" (cpp_type_of_array sg) vals
in
let sp_binop op a1 a2 =
match op with
| `Infix op -> sprintf "(%s %s %s)" a1 op a2
| `Fn f -> sprintf "%s(%s, %s)" f a1 a2
| `Array -> sprintf "%s[%s]" a1 a2 in
let sp_equality ?(negated=false) a1 a2 =
sp_binop (`Infix (if negated then "!=" else "==")) a1 a2 in
let sp_initializer tau =
(* This is needed for readability rather than performance, since GCC is
smart enough to optimize unpack(0). *)
sprintf "%s{}" (cpp_type_of_type tau) in
let sp_parenthesized arg =
if arg = "" then "" else sprintf "(%s)" arg in
let sp_packer ?(arg = "") tau =
let parg = sp_parenthesized arg in
match tau with
| Bits_t _ -> arg
| Enum_t _ | Struct_t _ | Array_t _ -> sprintf "prims::pack%s" parg in
let sp_unpacker ?(arg = "") tau =
let parg = sp_parenthesized arg in
match tau with
| Bits_t _ -> arg
| Enum_t sg ->
sprintf "prims::unpack<%s>%s" (cpp_enum_name sg) parg
| Struct_t sg ->
sprintf "prims::unpack<%s>%s" (cpp_struct_name sg) parg
| Array_t sg ->
sprintf "prims::unpack<%s>%s" (cpp_type_of_array sg) parg in
let p_enum_decl sg =
let esz = enum_sz sg in
let nm = cpp_enum_name sg in
if esz = 0 then failwith (sprintf "Enum %s is empty (its members are zero-bits wide)" nm);
if esz > 64 then failwith (sprintf "Enum %s is too large (its members are %d-bits wide; the limit is 64)" nm esz);
let decl = sprintf "enum class %s : %s" nm (cpp_value_type_of_size esz) in
p_scoped decl ~terminator:";" (fun () ->
iter_sep (fun () -> p ", ")
(fun (name, v) ->
let nm = cpp_enumerator_name name in
let vstr = sp_bits_value ~immediate:true v in
p "%s = %s" nm vstr)
sg.enum_members) in
let p_struct_decl sg =
let decl = sprintf "struct %s" (cpp_struct_name sg) in
p_scoped decl ~terminator:";" (fun () ->
List.iter (fun (name, tau) -> p_decl tau (cpp_field_name name)) sg.struct_fields) in
let p_printer tau =
let v_arg = "val" in
let v_tau = cpp_type_of_type tau in
let v_style = "const fmtopts opts" in
let v_argdecl = sprintf "std::ostream& os, const %s& %s" v_tau v_arg in
let p_printer pbody =
p_fn ~typ:"static _unused std::ostream&" ~name:"fmt"
~args:(sprintf "%s, %s" v_argdecl v_style) (fun () ->
pbody (); p "return os;") in
let p_enum_printer sg =
p_printer (fun () ->
p_scoped (sprintf "switch (%s)" v_arg) (fun () ->
List.iter (fun (nm, _v) ->
let lbl = cpp_enumerator_name ~enum:(Some sg) nm in
p "case %s: os << \"%s::%s\"; break;" lbl sg.enum_name nm) (* unmangled *)
sg.enum_members;
let v_sz = typ_sz tau in
let bits_sz_tau = cpp_type_of_type (Bits_t v_sz) in
let v_cast = sprintf "%s::mk(%s)" bits_sz_tau v_arg in
p "default: os << \"%s{\"; fmt(os, %s, opts) << \"}\";"
sg.enum_name v_cast)) in (* unmangled *)
let p_struct_printer sg =
p_printer (fun () ->
p "os << \"%s { \";" sg.struct_name; (* unmangled *)
List.iter (fun (fname, _) ->
p "os << \".%s = \"; fmt(os, %s.%s, opts) << \"; \";" (* unmangled *)
fname v_arg (cpp_field_name fname))
sg.struct_fields;
p "os << \"}\";") in
match tau with
| Bits_t _ | Array_t _ -> ()
| Enum_t sg -> p_enum_printer sg
| Struct_t sg -> p_struct_printer sg in
let p_operators tau =
let v_sz = typ_sz tau in
let v1, v2 = "v1", "v2" in
let v_tau = cpp_type_of_type tau in
let v_argdecl v = sprintf "const %s %s" v_tau v in
let bits_tau = cpp_type_of_type (Bits_t v_sz) in
let p_ostream_printer () =
let args = sprintf "std::ostream& os, const %s& val" v_tau in
p_fn ~typ:"static _unused std::ostream&" ~name:"operator<<" ~args
(fun () -> p "return prims::fmt(os, val);") in
let p_eq prbody =
p_fn ~typ:"static _unused bits<1> "
~args:(sprintf "%s, %s" (v_argdecl v1) (v_argdecl v2))
~name:"operator==" (fun () -> pr "return "; prbody (); p ";");
p_fn ~typ:"static _unused bits<1> "
~args:(sprintf "%s, %s" (v_argdecl v1) (v_argdecl v2))
~name:"operator!=" (fun () -> pr "return !(%s == %s);" v1 v2)in
let p_enum_eq _sg =
p_eq (fun () -> pr "%s::mk(%s) == %s::mk(%s)" bits_tau v1 bits_tau v2) in
let sp_field_eq v1 v2 field =
let field = cpp_field_name field in
let eq = sp_equality (v1 ^ "." ^ field) (v2 ^ "." ^ field) in
sprintf "bool%s" eq in
let p_struct_eq sg =
p_eq (fun () ->
pr "bits<1>::mk(";
iter_sep (fun () -> pr " && ") (fun (nm, _) ->
pr "%s" (sp_field_eq v1 v2 nm))
sg.struct_fields;
pr ")") in
(match tau with
| Bits_t _ | Array_t _ -> ()
| Enum_t sg -> p_enum_eq sg
| Struct_t sg -> p_struct_eq sg);
nl ();
p_ifnminimal (fun () ->
p_ostream_printer ()) in
let p_prims tau =
let v_sz = typ_sz tau in
let v_arg = "val" in
let v_tau = cpp_type_of_type tau in
let v_argdecl v = sprintf "const %s %s" v_tau v in
let bits_arg = "bs" in
let bits_tau = cpp_type_of_type (Bits_t v_sz) in
let bits_argdecl = sprintf "const %s %s" bits_tau bits_arg in
let p_pack pbody =
p_fn ~typ:("template <> _unused " ^ bits_tau)
~args:(v_argdecl v_arg) ~name:"pack<>" pbody in
let p_unpack pbody =
let decl = sprintf "template <> struct _unpack<%s, %d>" v_tau v_sz in
p_scoped decl ~terminator:";" (fun () ->
p_fn ~typ:("static " ^ v_tau)
~args:bits_argdecl ~name:"unpack" pbody) in
let p_enum_pack _ =
p_pack (fun () -> p "return %s::mk(%s);" bits_tau v_arg) in
let p_enum_unpack _ =
p_unpack (fun () -> p "return static_cast<%s>(%s.v);" v_tau bits_arg) in
let p_struct_pack sg =
let var = "packed" in
p_pack (fun () ->
p_decl (Bits_t v_sz) var ~init:(cpp_const_init false v_sz Z.zero);
List.iteri (fun idx (fname, ftau) ->
let sz = typ_sz ftau in
let fname = cpp_field_name fname in
let fval = sprintf "%s.%s" v_arg fname in
let fpacked = sp_packer ftau ~arg:fval in
if idx <> 0 then p "%s <<= %d;" var sz;
p "%s |= prims::widen<%d>(%s);" var v_sz fpacked)
sg.struct_fields;
p "return %s;" var) in
let p_struct_unpack sg =
let var = "unpacked" in
p_unpack (fun () ->
p_decl tau var ~init:"{}";
List.fold_right (fun (fname, ftau) offset ->
let sz = typ_sz ftau in
let fname = cpp_field_name fname in
let fval = sprintf "prims::truncate<%d>(%s >> %du)"
sz bits_arg offset in
let unpacked = sp_unpacker ~arg:fval ftau in
p "%s.%s = %s;" var fname unpacked;
offset + sz)
sg.struct_fields 0 |> ignore;
p "return %s;" var) in
let p_type_info () =
let decl = sprintf "template <> struct type_info<%s>" v_tau in
p_scoped decl ~terminator:";" (fun () ->
p_cpp_decl ~prefix:"static constexpr " ~init:(sprintf "%d" v_sz)
"prims::bitwidth" "size") in
p_type_info ();
nl ();
match tau with
| Bits_t _ | Array_t _ -> ()
| Enum_t sg -> p_enum_pack sg; nl (); p_enum_unpack sg
| Struct_t sg -> p_struct_pack sg; nl (); p_struct_unpack sg in
let complete_user_types () =
let reg_typ (_, t) = register_subtypes program_info t in
List.iter reg_typ program_info.pi_user_types;
program_info.pi_user_types in
let p_type_declarations () =
p "//////////////";
p "// TYPEDEFS //";
p "//////////////";
nl ();
let types = complete_user_types () in
let types = topo_sort_types (sort_types (List.map snd types)) in
let enums, structs = partition_types types in
List.iter p_enum_decl enums;
nl ();
iter_sep nl p_struct_decl structs;
nl ();
iter_sep nl p_operators types;
nl ();
p_scoped "namespace prims" (fun () ->
p_ifnminimal (fun () ->
iter_sep nl p_printer types);
nl ();
iter_sep nl p_prims types) in
let p_preamble () =
p "//////////////";
p "// PREAMBLE //";
p "//////////////";
nl ();
program_info.pi_committed <- true;
if program_info.pi_needs_multiprecision then (
p "#define NEEDS_BOOST_MULTIPRECISION";
nl ());
p "#include \"%s\"" cuttlesim_hpp_fname in
let iter_registers f regs =
let sigs = Array.map hpp.cpp_register_sigs regs in
Array.iter f sigs in
let all_register_sigs =
Array.map hpp.cpp_register_sigs hpp.cpp_registers in
let iter_all_registers f =
Array.iter f all_register_sigs in
let reg_sig_w_kind r =
(hpp.cpp_register_kinds r, hpp.cpp_register_sigs r) in
let iter_all_registers_with_kind =
let sigs = Array.map reg_sig_w_kind hpp.cpp_registers in
fun f -> Array.iter f sigs in
let p_impl () =
p "////////////////////";
p "// IMPLEMENTATION //";
p "////////////////////";
nl ();
let p_sim_class pbody =
p_scoped (sprintf "template <typename extfuns_t> class %s" hpp.cpp_classname)
~terminator:";" pbody in
let p_state_register r =
p_decl (reg_type r) r.reg_name in
let p_state_methods () =
let p_dump_register r =
p "os << \"%s = \" << %s << std::endl;"
r.reg_name r.reg_name in
let p_dump () =
p_fn ~typ:"void" ~name:"dump" ~annot:" const"
~args:"std::ostream& os = std::cout"
(fun () -> iter_all_registers p_dump_register) in
let p_vcd_decl r =
p "cuttlesim::vcd::var(os, \"%s\", %d);"
r.reg_name (typ_sz (reg_type r)) in
let p_vcd_header () =
p_fn ~typ:"static _unused void" ~name:"vcd_header"
~args:"std::ostream& os" (fun () ->
p_ifdef "ndef SIM_VCD_SCOPES" (fun () ->
p "#define SIM_VCD_SCOPES { \"TOP\", \"%s\" }" hpp.cpp_module_name);
p "cuttlesim::vcd::begin_header(os, SIM_VCD_SCOPES);";
iter_all_registers p_vcd_decl;
p "cuttlesim::vcd::end_header(os, SIM_VCD_SCOPES);") in
let p_dumpvar r =
p "cuttlesim::vcd::dumpvar(os, \"%s\", %s, previous.%s, force);"
r.reg_name r.reg_name r.reg_name in
let p_vcd_dumpvars () =
p_fn ~typ:"void" ~name:"vcd_dumpvars"
~args:(sprintf "%s, %s, %s, %s"
"std::uint_fast64_t cycle_id"
"_unused std::ostream& os"
"const state_t& previous"
"const bool force")
~annot:" const" (fun () ->
p "os << '#' << cycle_id << std::endl;";
iter_all_registers p_dumpvar) in
let p_readvar i r =
let hdr = if i == 0 then "if" else "else if" in
p_scoped (sprintf "%s (var == \"%s\")" hdr r.reg_name) (fun () ->
let tau = reg_type r in
p "%s = prims::unpack<%s>(bits<%d>::of_str(val));"
r.reg_name (cpp_type_of_type tau) (typ_sz tau)) in
let p_vcd_readvars () =
p_fn ~typ:"std::uint_fast64_t" ~name:"vcd_readvars"
~args:"_unused std::istream& is" (fun () ->
p "std::string var{}, val{};";
p "std::uint_fast64_t cycle_id = std::numeric_limits<std::uint_fast64_t>::max();";
p "cuttlesim::vcd::read_header(is);";
p_scoped "while (cuttlesim::vcd::readvar(is, cycle_id, var, val))" (fun () ->
Array.iteri p_readvar all_register_sigs);
p "return cycle_id;") in
p_ifnminimal (fun () ->
p_dump ();
nl ();
p_vcd_header ();
nl ();
p_vcd_dumpvars ();
nl ();
p_vcd_readvars ()) in
let p_state_t () =
p_scoped "struct state_t" ~terminator:";" (fun () ->
iter_all_registers p_state_register;
nl ();
p_state_methods ()) in
let p_snapshot_t () =
p "using snapshot_t = cuttlesim::snapshot_t<state_t>;" in
let p_reg_name_t () =
let p_decl_rwset_register r =
p "%s," r.reg_name in
let name_sz =
(* Compute the smallest bitwidth that can fit all names *)
Cuttlebone.Util.log2 (1 + Array.length hpp.cpp_registers) in
p_scoped (sprintf "enum class reg_name_t : bits_t<%d>" name_sz)
~terminator:";" (fun () ->
p "_invalid = 0,";
iter_all_registers p_decl_rwset_register) in
let p_dynamic_log_t () =
if not use_offsets_in_dynamic_log then
(p_reg_name_t ();
nl ());
let dynlog_type =
if use_offsets_in_dynamic_log
then "cuttlesim::offsets" else "reg_name_t" in
let decl =
sprintf "%s struct dynamic_log_t : %s"
"template<int capacity>"
(sprintf "cuttlesim::stack<%s, capacity>" dynlog_type) in
p_scoped decl ~terminator:";" (fun () ->
p_fn ~typ:"void" ~name:"apply" ~args:"log_t& dst, log_t& src"
(fun () ->
(* Unrolling this loop by copying everything up to capacity
doesn't help. Nor does it help to get rid of the switch by
recording struct offsets instead of register names into the
dynamic log. *)
p_scoped "for (int idx = 0; idx < this->sz; idx++)" (fun () ->
if use_offsets_in_dynamic_log then
let ri ptr = sprintf "reinterpret_cast<char*>(%s)" ptr in
p "this->data[idx].memcpy(%s, %s, %s, %s);"
(ri "&dst.state") (ri "&src.state")
(ri "&dst.rwset") (ri "&src.rwset")
else
p_scoped "switch (this->data[idx])" (fun () ->
let p_apply_one r =
p "case reg_name_t::%s:" r.reg_name;
p "dst.state.%s = src.state.%s;" r.reg_name r.reg_name;
p "dst.rwset.%s = src.rwset.%s;" r.reg_name r.reg_name;
p "break;" in
iter_all_registers p_apply_one)))) in
let p_rwset_t () =
let rwset_type_of_kind = function
| Extr.Value -> None
| Extr.Wire -> Some "wire_rwset"
| Extr.Register -> Some "reg_rwset"
| Extr.EHR -> Some "ehr_rwset" in
let p_decl_rwset_register (kd, r) =
match rwset_type_of_kind kd with
| None -> ()
| Some rwset -> p "cuttlesim::%s %s;" rwset r.reg_name in
p_scoped "struct rwset_t" ~terminator:";" (fun () ->
iter_all_registers_with_kind p_decl_rwset_register) in
let p_log_t () =
p_scoped "struct log_t" ~terminator:";" (fun () ->
p "rwset_t rwset;";
p "state_t state;";
nl ();
p_fn ~typ:"const state_t&" ~name:"snapshot" ~annot:" const" (fun () ->
p "return state;");
p_fn ~typ:"explicit" ~name:"log_t" ~args:"const state_t& init"
~annot:" : rwset{}, state(init)" (fun () -> ())) in
let backslash_re =
Str.regexp "\\\\" in
let sp_escaped_string s =
Str.global_replace backslash_re "\\\\\\\\" s in
let p_pos (pos: Pos.t) =
if add_line_pragmas then
match pos with
| Unknown | StrPos _ | Filename _ -> ()
| Range (filename, { rbeg = { line; _ }; _ }) ->
p "#line %d \"%s\"" line (sp_escaped_string filename) in
(* Map used to avoid collisions between function names *)
let internal_fnames = Hashtbl.create 20 in
let p_rule (rule: (pos_t, var_t, fn_name_t, rule_name_t, reg_t, ext_fn_t) cpp_rule_t) =
gensym_reset ();
let filter_registers_by_history cond =
List.filter (fun reg -> cond reg (rule.rl_reg_histories reg))
(Array.to_list hpp.cpp_registers)
|> Array.of_list in
(* Check for registers that would require keeping track of data0 and data1
separately, and issue a warning if there are any. *)
let _ =
match needs_data0_and_data1 rule.rl_body with
| [] -> ()
| conflicts ->
let names = List.map (fun r -> (hpp.cpp_register_sigs r).reg_name) conflicts |> String.concat ", " in
Printf.eprintf "Rule %s reads registers [%s] at port 1 \
after writing to them at port 1.
These reads should observe the old value of the registers, but \
implementing this in simulation causes unnecessary performance issues.
If you actually want to observe the old values, use let bindings to save \
them before writing to the registers.\n"
(hpp.cpp_rule_names rule.rl_name)
names in
let rwset_footprint =
(* No need to save or reset a register's read-write set if it's only
read at port 0, or if it's a value (i.e. a register for which reads
and writes cannot fail in any rule, in which case we don't generate a
read-write set at all). *)
filter_registers_by_history (fun reg { hr1; hw0; hw1; _ } ->
hpp.cpp_register_kinds reg <> Value &&
Extr.(hr1 <> TFalse || hw0 <> TFalse || hw1 <> TFalse)) in
let rwdata_footprint =
(* No need to save or reset a register's data if it's only read *)
filter_registers_by_history (fun _reg { hw0; hw1; _ } ->
Extr.(hw0 <> TFalse || hw1 <> TFalse)) in
if debug then (
let debug_footprint name fp =
Printf.printf "Footprints for %s in %s:\n"
name (hpp.cpp_rule_names rule.rl_name);
Array.iter (fun r ->
let nm = (hpp.cpp_register_sigs r).reg_name in
let rfp = rule.rl_reg_histories r in
let pr = function
| Extr.TTrue -> "true"
| Extr.TFalse -> "false"
| Extr.TUnknown -> "?" in
Printf.printf " %s: {r0=%s; r1=%s; w0=%s; w1=%s; cf=%s}\n" nm
(pr rfp.hr0) (pr rfp.hr1) (pr rfp.hw0) (pr rfp.hw1) (pr rfp.hcf))
fp in
debug_footprint "rwset" rwset_footprint;
debug_footprint "rwdata" rwdata_footprint);
let large_footprint footprint = (* FIXME should be tweaked based on the speed of memset *)
5 * Array.length footprint > 4 * Array.length hpp.cpp_registers in
let rule_max_log_size =
Extr.rule_max_log_size rule.rl_body in
let use_dynamic_log =
(* LATER: Refine this criterion based on rule_max_log_size; at the moment
this measure isn't precise enough to be truly useful, because it
overestimates log sizes in imperative switches. *)
use_dynamic_logs && (Array.length rwdata_footprint > 10 ||
Array.length rwset_footprint > 10) in
let dl_suffix =
if use_dynamic_log
then (if use_offsets_in_dynamic_log then "_DOL" else "_DL")
else "" in
let fail safe = sprintf "FAIL%s" (if safe then "_FAST" else dl_suffix) in
let commit = sprintf "COMMIT%s" dl_suffix in
let call = sprintf "CALL_FN" in
let rw_suffix reg =
if hpp.cpp_register_kinds reg = Value then "_FAST" else dl_suffix in
let read reg pt =
sprintf "READ%d%s" pt (rw_suffix reg) in
let write reg pt = sprintf "WRITE%d%s" pt (rw_suffix reg) in
let p_copy field src dst footprint =
let src = sprintf "%s.%s" src field in
let dst = sprintf "%s.%s" dst field in
if large_footprint footprint then
p "%s = %s;" dst src
else
iter_registers (fun { reg_name; _ } ->
p "%s.%s = %s.%s;" dst reg_name src reg_name)
footprint in
let p_commit_reset src dst =
if large_footprint rwdata_footprint &&
large_footprint rwset_footprint then
p "%s = %s;" dst src
else (
p_copy "state" src dst rwdata_footprint;
p_copy "rwset" src dst rwset_footprint) in
let p_reset () = p_commit_reset "Log" "log" in
let p_commit () = p_commit_reset "log" "Log" in
let p_declare_target = function
| VarTarget ({ tau; declared = false; name } as ti) ->
p_decl tau name;
ti.declared <- true
| _ -> () in
let gensym_target_info tau prefix =
{ tau; declared = false; name = gensym prefix } in
let gensym_target tau prefix =
VarTarget (gensym_target_info tau prefix) in
let maybe_gensym_target existing_target tau0 prefix =
(* Return ‘existing_target’ if it can store a value of type ‘tau0’;
otherwise, gensym a target starting with ‘prefix’. This allows us to
print ‘subst(y, f, 1)’ with target ‘x’ as ‘x = y; x.f = 1’ instead of
‘tmp = y; x = tmp; x.f = 1’. *)
match existing_target with
| VarTarget { tau; _ } when tau = tau0 -> existing_target
| VarTarget _ | NoTarget -> gensym_target tau0 prefix in
let ensure_target tau t =
match t with
| NoTarget -> gensym_target_info tau "ignored"
| VarTarget info -> info in
let p_assign_expr ?(prefix = "") target result =
match target, result with
| VarTarget ({ declared; name; tau } as ti), (PureExpr e | ImpureExpr e) ->
if declared && name <> e then
p "%s = %s;" name e
else if not declared then