-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathc_backend.py
3529 lines (3205 loc) · 146 KB
/
c_backend.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
# © 2021 Intel Corporation
# SPDX-License-Identifier: MPL-2.0
import sys, os
import itertools
import operator
import re
from contextlib import nullcontext
from functools import reduce
from abc import ABC, abstractmethod
import dataclasses
import json
from pathlib import Path
from . import objects, logging, crep, output, ctree, serialize, structure
from . import traits, compat
import dml.globals
from .structure import get_attr_name, port_class_ident, need_port_proxy_attrs
from .logging import *
from .messages import *
from .output import *
from .ctree import *
from .expr import *
from .expr_util import *
from .symtab import *
from .codegen import *
from .types import *
from .set import Set
prototypes = []
c_split_threshold = None
log_object_t = TNamed("log_object_t")
conf_object_t = TNamed("conf_object_t")
attr_value_t = TNamed('attr_value_t')
structfilename = None
def get_attr_flags(obj):
conf = param_str(obj, 'configuration')
persist = param_bool(obj, 'persistent')
internal = (param_bool_fixup(obj, 'internal', True)
or obj.is_confidential())
if conf == 'required':
flags = 'Sim_Attr_Required'
elif conf == 'optional':
flags = 'Sim_Attr_Optional'
elif conf == 'pseudo':
flags = 'Sim_Attr_Pseudo'
else:
raise EPARAM(param_expr_site(obj, "configuration"), "configuration")
if persist:
flags += "|Sim_Attr_Persistent"
if internal:
flags += "|Sim_Attr_Internal"
return flags
def get_short_doc(node):
if dml.globals.dml_version == (1, 2):
if node.is_confidential():
return "confidential"
elif param_defined(node, 'desc'):
return param_str(node, 'desc')
else:
return None
else:
return param_str_or_null(node, 'shown_desc')
def get_long_doc(node):
doc = None
if param_defined(node, 'documentation'):
doc = param_str_fixup(node, 'documentation', "")
# always check desc to catch EIDXVAR even if it isn't used
desc = get_short_doc(node)
if doc != None:
return "confidential" if node.is_confidential() else doc
else:
return desc
# This should be output at every point where we are leaving
# a code path controlled by the DML model, and the DML state might have
# changed since last we notified
def output_dml_state_change(device_ref):
# This is only for 1.4 devices, or 1.2 devices using a specific flag
if (dml.globals.dml_version == (1, 2) and
not dml.globals.state_change_dml12):
return
out(f"if (unlikely({device_ref}->_has_state_callbacks)) " + "{\n",
postindent = 1)
out(f"{crep.cname(dml.globals.device)}_notify_state_change("
f"{device_ref});\n")
out("}\n", preindent = -1)
registered_attribute_names = {}
def register_attribute(site, port, name):
'''remember that attribute 'name' is registered on port 'port',
and report error if this name was not free.
'port' is a Bank or Port, or None for device.'''
global registered_attribute_names
if name in dml.globals.illegal_attributes:
report(EANAME(site, name))
key = (port, name)
if key in registered_attribute_names:
report(EATTRCOLL(site, registered_attribute_names[key]))
registered_attribute_names[key] = site
# Creating the C struct definition is done in two steps. First, the
# structure is built up using the DMLType type, with a TStruct as the
# base. Then this is printed.
def print_device_substruct(node):
'''Return the type of the generated C type used to store a node's
local state, i.e., data objects plus implicit storage. Return None
if the node needs no storage.'''
def arraywrap(node, typ):
for arraylen in reversed(node.dimsizes):
typ = TArray(typ, mkIntegerLiteral(node.site, arraylen))
return typ
def composite_ctype(node, unfiltered_members, label=None):
'''Helper. Unfiltered_members is a list of (name, type) pairs, where
type=None entries are ignored.'''
members = {name: typ for (name, typ) in unfiltered_members if typ}
if not members:
return None
if not label:
# mangle names so x_y.z and x.y_z give different idents
label = '__devstruct_' + '_'.join("%d%s" % (s.count('_'), s)
for s in crep.ancestor_cnames(node))
structtype = TStruct(members, label)
structtype.print_struct_definition()
return structtype
if node.objtype == 'device':
members = [("obj", conf_object_t)]
for (v, _) in dml.globals.static_vars:
members.append((v.value, v.type))
members.append(('_immediate_after_state',
TPtr(TNamed('_dml_immediate_after_state_t'))))
return composite_ctype(node,
members + [(crep.cname(sub), print_device_substruct(sub))
for sub in node.get_components()],
label=crep.cname(node))
elif ((node.objtype == 'session' or node.objtype == 'saved')
or (dml.globals.dml_version == (1, 2)
and node.objtype == 'interface')):
return arraywrap(node, crep.node_storage_type(node, node.site))
elif node.objtype == 'hook':
return arraywrap(node, TNamed('_dml_hook_t'))
elif (node.objtype in {'register', 'field'}
and dml.globals.dml_version == (1, 2)):
allocate = param_bool_fixup(node, 'allocate', True)
if node.simple_storage:
return (arraywrap(node, crep.node_storage_type(node))
if allocate else None)
else:
@list
@apply
def members():
if allocate:
yield ('__DMLfield',
arraywrap(node, crep.node_storage_type(node)))
for sub in node.get_components():
if not sub.ident:
# implicit field
assert sub.objtype == 'field'
if not sub.simple_storage:
raise ICE(sub.site,
'implicit fields may not contain '
+ 'data/saved variables or hooks')
# storage is inherited from the parent register
continue
yield (crep.cname(sub), print_device_substruct(sub))
return composite_ctype(node, members)
elif node.objtype in {'bank', 'port', 'subdevice'}:
if node.name is None:
assert dml.globals.dml_version == (1, 2)
obj = []
else:
# really a _port_object_t* rather than conf_object_t*, but
# there is no DML type for the former
obj = [("_obj", arraywrap(node, TPtr(conf_object_t)))]
return composite_ctype(node,
obj + [(crep.cname(sub),
print_device_substruct(sub))
for sub in node.get_components()])
elif dml.globals.dml_version == (1, 2) and node.objtype == 'attribute':
composite_type = composite_ctype(node,
[(crep.cname(sub),
print_device_substruct(sub))
for sub in node.get_components()])
allocate_type = crep.node_storage_type(node)
if allocate_type:
if composite_type:
report(EATTRDATA(node,
param_expr_site(node, 'allocate_type'),
[session.site for session in
node.get_recursive_components('session')]))
return arraywrap(node, allocate_type)
else:
return composite_type
elif node.objtype in {'interface', 'group', 'event', 'connect',
'register', 'field', 'implement', 'attribute'}:
return composite_ctype(node,
[(crep.cname(sub), print_device_substruct(sub))
for sub in node.get_components()])
elif node.objtype in {'parameter', 'method'}:
return None
else:
raise Exception("Unknown group node " + repr(node))
def make_guard_sym(filename):
guard = re.compile(r'[^_A-Z0-9]').sub('_', filename.upper())
if not guard[0].isalpha() and guard[0] != '_':
return '_' + guard
return guard
def emit_guard_start(filename):
guard = make_guard_sym(filename)
if not re.match(r'[_A-Z][_A-Z0-9]*$', guard):
raise ICE(None, 'bad guard symbol %s' % guard)
out('#ifndef %s\n#define %s\n\n' % (guard, guard))
def emit_guard_end(filename):
out('\n#endif /* not %s */\n' % make_guard_sym(filename))
def generate_structfile(device, filename, outprefix):
out("/* Generated by dmlc, do not edit! */\n\n")
emit_guard_start(filename)
out('typedef struct %s %s_t;\n\n' % (crep.cname(device),
crep.cname(device)))
out('conf_class_t *%s(void);\n\n' % (init_function_name(device, outprefix)))
for (name, (func, export_site)) in list(exported_methods.items()):
if export_site.dml_version() != (1, 2):
out("extern %s;\n"
% func.rettype.declaration(
"%s(%s)" % (name,
", ".join((["conf_object_t *_obj"]
* (not func.independent))
+ [t.declaration(n)
for (n, t) in (
func.cparams
if func.independent
else func.cparams[1:])]))))
emit_guard_end(filename)
def generate_hfile(device, headers, filename):
out("/* Generated by dmlc, do not edit! */\n\n")
emit_guard_start(filename)
out('#define DML_PREFIX(x) '+crep.cname(device)+'_##x\n\n')
legacy_attrs = int(compat.legacy_attributes in dml.globals.enabled_compat)
out(f'#define DML_LEGACY_ATTRS {legacy_attrs}\n')
with allow_linemarks():
for c in headers:
c.toc()
out('\n')
out('\n')
out('#include <simics/util/help-macros.h>\n')
out('#include <stdint.h>\n')
out('#include "'+os.path.basename(structfilename)+'"\n\n')
for name in dml.globals.traits:
out(f'typedef _traitref_t {cident(name)};\n')
# Constraints from C:
# - Types must be defined before they are referred to
# - Structs can be referred to by struct label before they are defined,
# but the struct's definition (member list) must appear before
# it can be used as a direct member of another struct. An indirect member
# (struct x *member) may however appear before the struct's definition.
# - An 'extern typedef struct', cannot be referred to by struct label,
# only by typename. But we don't need to worry about declaration order,
# an extern typedef cannot depend on a non-extern typedef.
# We do the following to solve this:
# - start by creating a typedef for each named struct type.
# This way, we can use 'X' and 'struct X' interchangeably.
# - Named structs are consistently referenced by their typedef name
# - Each anonymous struct is assigned a unique struct label, and the
# type is always referenced as 'struct LABEL'. The first time
# an anonymous struct is referenced, the reference is preceded by
# a struct definition, defining the struct's fields.
# - topologically sort types based on C declaration dependencies.
# In this ordering, a struct definition appears after all types
# it depends on, except that it may appear before structs it
# refers to *indirectly*, i.e. via a pointer.
# typedefs for named structs come first, because in:
# typedef struct { int i; } X;
# typedef struct { X *x; } Y;
# the C declaration of Y may appear before that of X, and the
# C code for Y currently names the member type 'X' rather than 'struct X'.
for tn in global_type_declaration_order:
if tn not in typedefs:
continue
t = typedefs[tn]
if isinstance(t, TStruct):
out('typedef %sstruct %s %s;\n' % (
'const ' if t.const else '', cident(tn), cident(tn)))
for tn in global_type_declaration_order:
if tn in global_anonymous_structs:
global_anonymous_structs[tn].print_struct_definition()
else:
t = typedefs[tn]
if isinstance(t, TStruct):
t.print_struct_definition()
else:
out('typedef ')
t.print_declaration(cident(tn))
out('\n')
out('\n')
for (_, t) in TStruct.late_global_struct_defs:
t.print_struct_definition()
out('\n')
for t in dml.globals.traits.values():
for memo_outs_struct in t.vtable_memoized_outs.values():
memo_outs_struct.print_struct_definition()
print_vtable_struct_declaration(t)
out('\n')
for info in dml.globals.type_sequence_infos.values():
if info.struct:
info.struct.print_struct_definition()
out(f'typedef struct {info.struct.label} {info.struct.label}_t;\n')
out('\n')
for typ in (typ
for info in itertools.chain(
dml.globals.after_delay_infos.values(),
dml.globals.after_on_hook_infos,
dml.globals.immediate_after_infos.values())
for typ in info.types_to_declare):
typ.print_struct_definition()
out('\n')
print_device_substruct(device)
out('// allows generated code to store device struct offsets in uint32,\n')
out('// which saves space\n')
out(f'STATIC_ASSERT(sizeof(struct {crep.cname(device)}) <= UINT32_MAX);\n')
if dml.globals.log_groups:
i = 1
for g in dml.globals.log_groups:
out('static const uint64 %s UNUSED = %dULL;\n'
% (crep.cloggroup(g), i))
i <<= 1
out('\n')
out('void hard_reset_'+crep.cname(device)
+ '('+crep.structtype(device)+' *_obj);\n')
out('void soft_reset_'+crep.cname(device)
+ '('+crep.structtype(device)+' *_obj);\n')
emit_guard_end(filename)
def generate_protofile(device):
linkage = 'extern' if c_split_threshold else 'static'
out('\n/* generated function prototypes */\n')
for proto in prototypes:
out("%s %s UNUSED;\n" % (linkage, proto))
def get_attr_fname(node, port, group_prefix):
port_prefix = port.attrname() + '_' if port else ''
if node.objtype == 'register' and node.is_confidential():
return port_prefix + get_anonymized_name(node)
else:
return port_prefix + group_prefix + crep.cname(node)
def generate_attr_setter(fname, node, port, dimsizes, cprefix, loopvars,
allow_cutoff=False):
device = dml.globals.device
proto = ('set_error_t ' + fname +
'(conf_object_t *_obj, attr_value_t *_val, lang_void *_aux)')
start_function_definition(proto)
out('{\n', postindent = 1)
if port:
out(' _port_object_t *_portobj = (_port_object_t *)_obj;\n')
out(crep.structtype(device)+' *_dev UNUSED = ('
+ crep.structtype(device)+'*)_portobj->dev;\n')
index_array = mkLit(port.site, '_portobj->indices',
TPtr(TInt(32, False, const=True)))
port_indices = tuple(mkIndex(port.site, index_array,
mkIntegerLiteral(port.site, i))
for i in range(port.dimensions))
else:
out(crep.structtype(device)+' *_dev UNUSED = ('
+ crep.structtype(device)+'*)_obj;\n')
port_indices = ()
out('set_error_t _status = Sim_Set_Illegal_Value;\n')
if loopvars:
out('uint32 ' + ','.join(v.str for v in loopvars) + ';\n')
fscope = Symtab(global_scope)
valuevar = '*_val'
for (dim, (dimsize, loopvar)) in enumerate(zip(dimsizes, loopvars)):
out('for (%s = 0; %s < %d; %s++) {\n'
% (loopvar.read(), loopvar.read(), dimsize, loopvar.read()),
postindent = 1)
list_item = 'SIM_attr_list_item(%s, %s)' % (valuevar, loopvar.read())
if allow_cutoff:
in_list = ('%s < SIM_attr_list_size(%s)'
% (loopvar.read(), valuevar))
if dim:
in_list = 'SIM_attr_is_list(%s) && %s' % (valuevar, in_list)
list_item = '%s ? %s : SIM_make_attr_nil()' % (in_list, list_item)
out('attr_value_t attr%d = %s;\n' % (dim, list_item))
valuevar = 'attr%d' % (dim,)
with NoFailure(node.site), crep.DeviceInstanceContext():
setcode = [
codegen_inline_byname(
node, port_indices + loopvars,
'_set_attribute' if dml.globals.dml_version == (1, 2)
else 'set_attribute',
[mkLit(node.site, valuevar, TNamed('attr_value_t'))],
[mkLit(node.site, '_status', TNamed('set_error_t'))],
node.site,
inhibit_copyin = not loopvars)]
code = mkCompound(None, declarations(fscope) + setcode)
code.toc_inline()
if dimsizes:
# abort on first bad value
out('if (_status != Sim_Set_Ok) goto exit;\n')
for _ in dimsizes:
out('}\n', preindent = -1)
out('exit:\n')
output_dml_state_change('_dev')
out('return _status;\n')
out('}\n\n', preindent = -1)
splitting_point()
def generate_attr_getter(fname, node, port, dimsizes, cprefix, loopvars):
device = dml.globals.device
proto = ('attr_value_t ' + fname+'(conf_object_t *_obj, lang_void *_aux)')
start_function_definition(proto)
out('{\n', postindent = 1)
if port:
out(' _port_object_t *_portobj = (_port_object_t *)_obj;\n')
out(crep.structtype(device)+' *_dev UNUSED = ('
+ crep.structtype(device)+'*)_portobj->dev;\n')
index_array = mkLit(port.site, '_portobj->indices',
TPtr(TInt(32, False, const=True)))
port_indices = tuple(mkIndex(port.site, index_array,
mkIntegerLiteral(port.site, i))
for i in range(port.dimensions))
else:
out(crep.structtype(device)+' *_dev UNUSED = ('
+ crep.structtype(device)+'*)_obj;\n')
port_indices = ()
out('attr_value_t _val0;\n')
if loopvars:
out('uint32 ' + ', '.join(v.str for v in loopvars) + ';\n')
fscope = Symtab(global_scope)
valuevar = mkLit(node.site, '_val0', attr_value_t)
assert len(dimsizes) == len(loopvars)
for (dim, loopvar, depth) in zip(dimsizes, loopvars,
list(range(len(dimsizes)))):
next_valuevar = mkLit(node.site, '_val%s' % (depth + 1,), attr_value_t)
out('%s = SIM_alloc_attr_list(%d);\n' % (valuevar.read(), dim))
out('for (%s = 0; %s < %d; %s++) {\n'
% (loopvar.read(), loopvar.read(), dim, loopvar.read()),
postindent = 1)
out('attr_value_t %s;\n' % (next_valuevar.read()))
valuevar = next_valuevar
with NoFailure(node.site), crep.DeviceInstanceContext():
getcode = codegen_inline_byname(
node, port_indices + loopvars,
'_get_attribute' if dml.globals.dml_version == (1, 2)
else 'get_attribute',
[], [valuevar], node.site)
code = mkCompound(node.site, declarations(fscope) + [getcode])
code.toc_inline()
for depth, loopvar in reversed(list(enumerate(loopvars))):
out('SIM_attr_list_set_item(&_val%d, %s, _val%d);\n'
% (depth, loopvar.read(), depth + 1))
out('}\n', preindent = -1)
output_dml_state_change('_dev')
out('return _val0;\n')
out('}\n\n', preindent = -1)
splitting_point()
# dimsizes, loopvars, prefix are relative to port.
def check_attribute(node, port, prefix):
config_param = param_str_fixup(node, 'configuration', 'none')
if config_param == 'none':
return
if not get_long_doc(node):
if (node.objtype in {'attribute', 'connect'}
and config_param == 'required'):
report(WNDOCRA(node, node.logname()))
attrname = get_attr_name(prefix, node)
register_attribute(node.site, port, attrname)
if port and need_port_proxy_attrs(port):
register_attribute(node.site, None, "%s_%s" % (port.name, attrname))
# dimsizes, loopvars, prefix are relative to port.
def generate_attribute_common(initcode, node, port, dimsizes, prefix,
loopvars):
assert dml.globals.dml_version == (1, 2)
attrname = get_attr_name(prefix, node)
config_param = param_str_fixup(node, 'configuration', 'none')
if config_param == 'none':
return
for _ in node.arraylens():
loopvars += (mkLit(None, '_i'+str(len(loopvars)+1), TInt(32, False)),)
dimsizes += node.arraylens()
doc = get_long_doc(node)
if doc:
pass
elif node.objtype == 'register':
doc = 'register ' + node.logname_anonymized()
elif (node.objtype in {'attribute', 'connect'}
and config_param == 'required'):
report(WNDOCRA(node, node.logname()))
doc = "Undocumented"
else:
doc = "Undocumented"
# append the required interfaces to the docstring
if node.objtype == 'connect':
ifaces = [i for i in node.get_components('interface')
if param_bool(i, 'required')]
if ifaces:
doc += (
'\n\nRequired interfaces: '
+ ', '.join('<iface>' + i.name + '</iface>' for i in ifaces)
+ '.')
doc = mkStringConstant(node.site, doc)
fname = get_attr_fname(node, port, prefix)
allow_cutoff = (node.objtype == 'connect'
and param_str(node, 'configuration') == 'optional')
if node.writable:
setter = 'set_'+fname
generate_attr_setter(setter, node, port, dimsizes, prefix, loopvars,
allow_cutoff)
else:
setter = '0'
if node.readable:
getter = 'get_'+fname
generate_attr_getter(getter, node, port, dimsizes, prefix, loopvars)
else:
getter = '0'
attr_flag = get_attr_flags(node)
attr_type = param_str(node, 'attr_type')
for dim in reversed(dimsizes):
if allow_cutoff:
attr_type = "[%s{0:%d}]" % (attr_type, dim)
else:
attr_type = "[%s{%d}]" % (attr_type, dim)
register_attribute(node.site, port, attrname)
if port:
if need_port_proxy_attrs(port):
if port.dimensions == 0:
register_attribute(
node.site, None, "%s_%s" % (port.name, attrname))
initcode.out(
'_register_port_attr(class, %s, offsetof(%s, %s), %s,'
% (port_class_ident(port),
crep.structtype(dml.globals.device),
crep.cref_portobj(port, ()),
'true' if port.objtype == "bank" else 'false')
+ ' "%s", "%s", %s, %s, %s, "%s", %s);\n'
% (port.name, attrname, getter, setter,
attr_flag, attr_type, doc.read()))
else:
assert port.dimensions == 1
# Generate an accessor attribute for legacy reasons
register_attribute(
node.site, None, "%s_%s" % (port.name, attrname))
member = crep.cref_portobj(
port, (mkLit(port.site, '0', TInt(32, False)),))
(dimsize,) = port.dimsizes
initcode.out(
'_register_port_array_attr(class, %s, offsetof(%s, %s),'
% (port_class_ident(port),
crep.structtype(dml.globals.device),
member)
+ ' %d, %s, "%s", "%s", %s, %s, %s, "%s",'
% (dimsize, 'true' if port.objtype == "bank" else 'false',
port.name, attrname, getter, setter, attr_flag,
attr_type)
+ ' %s);\n' % (doc.read(),))
else:
initcode.out(
'_register_port_attr_no_aux(%s,'
' "%s", %s, %s, %s, "%s", %s);\n'
% (port_class_ident(port),
attrname, getter, setter,
attr_flag, attr_type, doc.read()))
else:
initcode.out(
f'_DML_register_attribute(class, "{attrname}", '
+ f'{getter}, NULL, {setter}, NULL, {attr_flag}, "{attr_type}", '
+ f'{doc.read()});\n')
# Output register attribute functions and return a string with
# initialization code
def generate_attributes(initcode, node, port=None,
dimsizes=(), prefix='', loopvars=()):
if node.objtype in {'connect', 'attribute', 'register'}:
try:
if dml.globals.dml_version == (1, 2):
generate_attribute_common(
initcode, node, port, dimsizes, prefix, loopvars)
else:
check_attribute(node, port, prefix)
except DMLError as e:
report(e)
return
if node.objtype in {'parameter', 'method', 'session', 'saved', 'hook'}:
return
# Registration order is undefined but has significance, so
# register attributes of subobjects in an order that is deterministic,
# platform-independent, and unaffected by adding or removing
# objects.
children = sorted(node.get_components(),
key=lambda o: o.name or '')
if node.objtype in {'group', 'implement', 'event'}:
prefix += crep.cname(node) + '_'
for _ in node.arraylens():
loopvars += (mkLit(None, '_i' + str(len(loopvars) + 1),
TInt(32, False)),)
dimsizes += node.arraylens()
for child in children:
generate_attributes(initcode, child, port, dimsizes, prefix,
loopvars)
elif node.objtype in {'device', 'bank', 'port', 'subdevice'}:
if node.objtype in {'bank', 'port', 'subdevice'} and (
# anonymous bank
dml.globals.dml_version != (1, 2) or node.name != None):
port = node
for child in children:
generate_attributes(initcode, child, port)
else:
raise ICE(node, f"unknown object type {node.objtype}")
def find_connects(node, subobj_parent):
if node.objtype == 'connect':
yield (subobj_parent, node)
for sub in node.get_components():
if sub.objtype in {'bank', 'port', 'subdevice'}:
yield from find_connects(sub, sub)
else:
yield from find_connects(sub, subobj_parent)
def generate_subobj_connects(init_code, device, prefixes=("",)):
if dml.globals.dml_version != (1, 2):
t = dml.globals.traits['init_as_subobj']
for (parent, node) in find_connects(device, device):
if t in node.traits.ancestors:
classname = mkStringConstant(
None, param_str(node, 'classname')).quoted
desc = (mkStringConstant(None, param_str(node, "desc")).quoted
if param_defined(node, 'desc') else 'NULL')
cls = port_class_ident(parent)
for indices in itertools.product(
*(list(range(i)) for i in node.dimsizes[
parent.dimensions:])):
name = node.logname_anonymized(
indices, relative=parent.objtype)
init_code.out(
f'_DML_register_subobj_connect({cls}, '
+ f'{classname}, "{name}", {desc});\n')
def apply(f):
return f()
@apply
class PORTOBJ(object):
"""Marker that indicates that a method is wrapped for a port object,
and indices are taken from that object"""
def wrap_method(meth, wrapper_name, indices=()):
"""Wrap a method in a C function taking a conf_object_t pointer as first
argument, and returning the optional output argument. Since this is a
common DML surface area, we inject DML context checks into it.
indices is either a tuple of integers, or PORTOBJ if the first arg
is a port object
"""
inparams = [t.declaration(p) for p, t in meth.inp]
if not meth.outp:
retvar = None
rettype = TVoid()
elif len(meth.outp) == 1:
retvar, rettype = meth.outp[0]
else:
raise ICE(meth, "many return types")
start_function_definition(rettype.declaration('%s(%s)' % (
wrapper_name, ", ".join(["conf_object_t *_obj"] + inparams))))
out('{\n', postindent = 1)
devstruct = crep.structtype(dml.globals.device)
if indices is PORTOBJ:
out('_port_object_t *_portobj = (_port_object_t *)_obj;\n')
out(devstruct+' *_dev UNUSED = (' + devstruct + ' *)_portobj->dev;\n')
index_array = mkLit(meth.site, '_portobj->indices',
TPtr(TInt(32, False, const=True)))
indices = tuple(mkIndex(meth.site, index_array,
mkIntegerLiteral(meth.site, i))
for i in range(meth.dimensions))
else:
assert meth.dimensions == len(indices)
out(devstruct+' *_dev UNUSED = ('+devstruct+'*)_obj;\n')
indices = tuple(mkIntegerLiteral(meth.site, i) for i in indices)
with crep.DeviceInstanceContext():
if retvar:
mkDeclaration(meth.site, retvar, rettype,
init = get_initializer(meth.site, rettype,
None, None, None)).toc()
with LogFailure(meth.site, meth, indices):
inargs = [mkLit(meth.site, v, t) for v, t in meth.inp]
outargs = [mkLit(meth.site, v, t) for v, t in meth.outp]
codegen_call(meth.site, meth,
indices,
inargs, outargs).toc()
output_dml_state_change('_dev')
if retvar:
out('return '+retvar+';\n')
out('}\n', preindent = -1)
out('\n')
splitting_point()
def generate_implement_method(device, ifacestruct, meth, indices):
# FIXME: this is how it should be done, but we have to fix
# codegen_method so it generates a function that returns
# the value if there is a single output parameter.
#
# meth.func.fail = IgnoreFailure()
# meth.func.confobj = 1
# codegen_method(meth)
# out(meth.get_c())
try:
require_fully_typed(None, meth)
# Calculate the expected method signature
member_type = ifacestruct.get_member_qualified(meth.name)
if not member_type:
raise EMEMBER(meth.site, meth.parent.name, meth.name)
member_type = safe_realtype(member_type)
if not isinstance(member_type, TPtr):
raise EIMPLMEMBER(
meth.site,
f'{meth.parent.name}_interface_t.{meth.name}',
ifacestruct.declaration_site)
func_type = member_type.base
if not isinstance(func_type, TFunction):
raise EIMPLMEMBER(meth.site,
f'{meth.parent.name}_interface_t.{meth.name}',
ifacestruct.declaration_site)
iface_input_types = func_type.input_types[1:]
iface_num_outputs = 0 if func_type.output_type.void else 1
# Check the signature
if len(meth.inp) != len(iface_input_types):
raise EMETH(meth.site, None,
'different number of input parameters')
if len(meth.outp) != iface_num_outputs:
raise EMETH(meth.site, None,
'different number of output parameters')
if func_type.varargs:
# currently impossible to implement a varargs interface
# method in DML
raise EMETH(meth.site, None, 'interface method is variadic')
for ((mp, mt), it) in zip(meth.inp, iface_input_types):
if not safe_realtype_unconst(mt).eq(safe_realtype_unconst(it)):
raise EARGT(meth.site, 'implement', meth.name,
mt, mp, it, 'method')
if iface_num_outputs and dml.globals.dml_version != (1, 2):
[(_, mt)] = meth.outp
if not safe_realtype_unconst(mt).eq(
safe_realtype_unconst(func_type.output_type)):
raise EARGT(meth.site, 'implement', meth.name,
mt, '<return value>', func_type.output_type,
'method')
if indices is PORTOBJ:
name = '_DML_PIFACE_' + crep.cref_method(meth)
else:
name = '_DML_IFACE_' + crep.cref_method(meth) + "".join([
"__%d" % idx for idx in indices])
wrap_method(meth, name, indices)
except DMLError as e:
report(e)
return f".{meth.name} = NULL,\n"
return ".%s = &%s,\n" % (meth.name, name)
def interface_block(device, ifacestruct, methods, indices = ()):
if not methods:
# Empty interface, but we need at least one initialiser (some
# compilers complain if we declare an uninitialised const
# variable). There is at least one member, probably a
# placeholder, so try placating it with a zero.
return "{ 0 }"
indent = ' ' * indent_level
indent2 = indent * 2
return "{\n%s%s%s}" % (
indent2,
indent2.join(generate_implement_method(device, ifacestruct, meth,
indices)
for meth in methods),
indent)
def string_literal(pystr):
if pystr is None:
return 'NULL'
else:
return '"%s"' % (ctree.string_escape(pystr.encode('utf-8')),)
def generate_implement(code, device, impl):
varname = crep.cname(impl) + "_interface"
methods = impl.get_components('method')
typename = param_str(impl,
'c_type' if dml.globals.dml_version == (1, 2)
else '_c_type')
ifacetype = TNamed(typename)
ifacetype.declaration_site = impl.site
ifacestruct = safe_realtype(ifacetype)
if not isinstance(ifacestruct, (TStruct, TExternStruct)):
raise EIFTYPE(impl.site, ifacetype)
port = impl.parent
assert port.objtype in {'port', 'bank', 'device', 'subdevice'}
assert not impl.local_dimensions()
if not port.name:
# anonymous bank
assert dml.globals.dml_version == (1, 2)
raise EANONPORT(impl.site, port)
code.out("{\n", postindent = 1)
if not port.parent:
# device
code.out("static const %s = %s;\n" %
(ifacetype.declaration(varname),
interface_block(device, ifacestruct, methods, ())))
code.out('SIM_register_interface(class, "%s", &%s);\n' %
(impl.name, varname))
else:
desc = string_literal(get_short_doc(port))
code.out("static const %s = %s;\n" % (
ifacetype.declaration(varname),
interface_block(device, ifacestruct, methods, PORTOBJ)))
code.out('SIM_register_interface(%s, "%s", &%s);\n'
% (port_class_ident(port), impl.name, varname))
# Legacy interface ports are only added for ports and banks that were
# available in Simics 5, i.e. zero or one dimensional direct
# descendants of the device object
if (port.parent is dml.globals.device
and port.objtype in {'port', 'bank'}
and compat.port_proxy_ifaces in dml.globals.enabled_compat):
if port.local_dimensions() == 0:
code.out("static const %s = %s;\n" % (
ifacetype.declaration('port_iface'),
interface_block(device, ifacestruct, methods, ())))
code.out('SIM_register_port_interface'
'(class, "%s", &port_iface, "%s", %s);\n'
% (impl.name, crep.cname(port), desc))
elif port.local_dimensions() == 1:
[arrlen] = port.arraylens()
code.out("static const %s%s = %s;\n" %
(ifacetype.declaration("ifaces"),
"[%s]" % (arrlen,),
"{%s\n}" % ",\n".join(
"%s" % interface_block(device, ifacestruct,
methods, (i, ))
for i in range(arrlen))))
code.out("interface_array_t iface_vect = VNULL;\n")
idxvar = "i0"
code.out("for (int %s = 0; %s < %d; %s++)\n" %
(idxvar, idxvar, arrlen, idxvar),
postindent = 1)
access = "[%s]" % idxvar
code.out("VADD(iface_vect, &ifaces%s);\n" % access,
postindent = -1)
code.out('VT_register_port_array_interface'
'(class, "%s", &iface_vect, "%s", %s);\n'
% (impl.name, crep.cname(port), desc))
code.out('VFREE(iface_vect);\n')
code.out("}\n", preindent = -1)
def port_prefix(port):
return {'bank': 'bank.', 'port': 'port.', 'subdevice': ''}[port.objtype]
def find_port_parent(port, indices):
'''Given a port or bank node, find the port node that correspond to
port object's port parent, and the name of the port object
relative to port parent and the device. The return value is a
triple (node, prefix, suffix), where node is the port parent,
suffix is the conf-object name as descendant of the port parent,
and (prefix+suffix) is the conf-object name as descendant of the
device. E.g., for a node subdev.p, returns (subdev.obj, "subdev",
"port.p").'''
ancestor = port.parent
suffix_parts = [port_prefix(port) + port.name_anonymized
+ ''.join(f'[{i}]' for i in indices[ancestor.dimensions:])]
indices = indices[:ancestor.dimensions]
while ancestor.objtype not in {'device', 'subdevice'}:
assert ancestor.objtype == 'group'
name = ancestor.name_anonymized
idx = ''.join(f'[{i}]' for i in indices[ancestor.parent.dimensions:])
suffix_parts.append(f'{name}{idx}.')
ancestor = ancestor.parent
indices = indices[:ancestor.dimensions]
if ancestor.objtype == 'device':
prefix = ''
else:
(_, prefix_prefix, prefix_suffix) = find_port_parent(ancestor, indices)
prefix = f'{prefix_prefix}{prefix_suffix}.'
return (ancestor, prefix, ''.join(reversed(suffix_parts)))
def node_ancestors(node, since):
while True:
if node is since:
return
yield node
node = node.parent
def generate_port_class(code, device, port):
(port_parent, prefix, suffix) = find_port_parent(
port, ('%d',) * port.dimensions)
portclass_name_comps = [o.name_anonymized
for o in node_ancestors(port, device)]
portclass_name_comps.append(param_str_fixup(device, 'classname', ''))
portclass_name = '.'.join(reversed(portclass_name_comps))
desc = string_literal(get_short_doc(port))
doc = string_literal(get_long_doc(port))
code.out(f'{port_class_ident(port)} = _register_port_class('
f'"{portclass_name}", {desc}, {doc});\n')
port_parent_class = ('class' if port_parent.objtype == 'device'
else port_class_ident(port_parent))
port_dims = port.dimensions - port_parent.dimensions
if port_dims:
for (i, sz) in enumerate(port.dimsizes[port_parent.dimensions:]):
code.out(f'for (int _i{i} = 0; _i{i} < {sz}; ++_i{i}) {{\n',
postindent=1)
fmtargs = ''.join(f', _i{i}' for i in range(port_dims))
code.out(f'strbuf_t portname = sb_newf("{suffix}"{fmtargs});\n')
code.out(f'SIM_register_port({port_parent_class}, sb_str(&portname),'
f' {port_class_ident(port)}, {desc});\n')
code.out('sb_free(&portname);\n')
for _ in range(port_dims):
code.out('}\n', preindent=-1)
else:
code.out(f'SIM_register_port({port_parent_class},'
f' "{suffix}", {port_class_ident(port)}, {desc});\n')
def generate_port_classes(code, device):
for port in device.get_recursive_components('port', 'bank', 'subdevice'):
if port.name is None:
assert dml.globals.dml_version == (1, 2)
continue
generate_port_class(code, device, port)
add_variable_declaration(f'conf_class_t *{port_class_ident(port)}')
def generate_implements(code, device):
for impl in device.get_recursive_components('implement'):
try: