-
Notifications
You must be signed in to change notification settings - Fork 297
/
CodegenCFunctions.tpl
7917 lines (7229 loc) · 334 KB
/
CodegenCFunctions.tpl
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
// This file defines templates for transforming Modelica/MetaModelica code to C
// code. They are used in the code generator phase of the compiler to write
// target code.
//
// CodegenC.tpl has the root template translateModel while
// this template contains only translateFunctions.
// These templates do not return any
// result but instead write the result to files. All other templates return
// text and are used by the root templates (most of them indirectly).
package CodegenCFunctions
import interface SimCodeTV;
import CodegenUtil.*;
import ExpressionDumpTpl;
/* public */ template generateEntryPoint(Path entryPoint, String url) "used in Compiler/Script/CevalScript.mo"
::=
let name = ("omc_" + underscorePath(entryPoint))
<<
/* This is an automatically generated entry point to a MetaModelica function */
#if defined(__cplusplus)
extern "C" {
#endif
#if defined(OMC_ENTRYPOINT_STATIC)
#include <stdio.h>
#include <openmodelica.h>
DLLImport extern int __omc_main(int argc, char **argv);
int main(int argc, char **argv)
{
return __omc_main(argc, argv);
}
#else
#include <meta/meta_modelica.h>
#include <stdio.h>
extern void
#if defined(OMC_GENERATE_RELOCATABLE_CODE)
(*<%name%>)
#else
<%name%>
#endif
(threadData_t*,modelica_metatype);
#ifdef _OPENMP
#include<omp.h>
/* Hack to make gcc-4.8 link in the OpenMP runtime if -fopenmp is given */
int (*force_link_omp)(void) = omp_get_num_threads;
#endif
static int rml_execution_failed()
{
fflush(NULL);
fprintf(stderr, "Execution failed!\n");
fflush(NULL);
return 1;
}
DLLExport int __omc_main(int argc, char **argv)
{
MMC_INIT(0);
{
void *lst = mmc_mk_nil();
int i = 0;
for (i=argc-1; i>0; i--) {
lst = mmc_mk_cons(mmc_mk_scon(argv[i]), lst);
}
<%mainTop('<%name%>(threadData, lst);',url)%>
}
<%if Flags.isSet(HPCOM) then "terminateHpcOmThreads();" %>
fflush(NULL);
EXIT(0);
return 0;
}
#endif
#if defined(__cplusplus)
} /* end extern "C" */
#endif
>>
end generateEntryPoint;
template mainTop(Text mainBody, String url)
::=
<<
{
MMC_TRY_TOP()
MMC_TRY_STACK()
<%mainBody%>
MMC_ELSE()
rml_execution_failed();
fprintf(stderr, "Stack overflow detected and was not caught.\nSend us a bug report at <%url%>\n Include the following trace:\n");
printStacktraceMessages();
fflush(NULL);
return 1;
MMC_CATCH_STACK()
MMC_CATCH_TOP(return rml_execution_failed());
}
>>
end mainTop;
/* public */ template translateFunctions(FunctionCode functionCode)
"Generates C code and Makefile for compiling and calling Modelica and
MetaModelica functions.
used in Compiler/SimCode/SimCodeMain.mo"
::=
match functionCode
case fc as FUNCTIONCODE(__) then
let()= System.tmpTickResetIndex(0,2) /* auxFunction index */
let()= System.tmpTickResetIndex(0,20) /*parfor index*/
let &staticPrototypes = buffer ""
let filePrefix = name
let _= (if mainFunction then textFile(functionsMakefile(functionCode), '<%filePrefix%>.makefile'))
let()= textFile(functionsHeaderFile(filePrefix, mainFunction, functions, extraRecordDecls, staticPrototypes), '<%filePrefix%>.h')
let()= textFileConvertLines(functionsFile(filePrefix, mainFunction, functions, literals, staticPrototypes), '<%filePrefix%>.c')
let()= textFile(externalFunctionIncludes(fc.externalFunctionIncludes), '<%filePrefix%>_includes.h')
let()= textFile(recordsFile(filePrefix, extraRecordDecls, false /*isSimulation*/), '<%filePrefix%>_records.c')
// If ParModelica generate the kernels file too.
if acceptParModelicaGrammar() then
let()= textFile(functionsParModelicaKernelsFile(filePrefix, mainFunction, functions), '<%filePrefix%>_kernels.cl')
"" // Return empty result since result written to files directly
end match
end translateFunctions;
template translateFunctionHeaderFiles(FunctionCode functionCode)
::=
match functionCode
case fc as FUNCTIONCODE(__) then
let()= System.tmpTickResetIndex(0,2) /* auxFunction index */
let()= System.tmpTickResetIndex(0,20) /*parfor index*/
let &staticPrototypes = buffer ""
let filePrefix = name
let _= (if mainFunction then textFile(functionsMakefile(functionCode), '<%filePrefix%>.makefile'))
let()= textFile(functionsHeaderFile(filePrefix, mainFunction, functions, extraRecordDecls, staticPrototypes), '<%filePrefix%>.h')
let()= textFile(externalFunctionIncludes(fc.externalFunctionIncludes), '<%filePrefix%>_includes.h')
let()= textFile(recordsFile(filePrefix, extraRecordDecls, false /*isSimulation*/), '<%filePrefix%>_records.c')
"" // Return empty result since result written to files directly
end match
end translateFunctionHeaderFiles;
template functionsFile(String filePrefix,
Option<Function> mainFunction,
list<Function> functions,
list<Exp> literals,
Text &staticPrototypes)
"Generates the contents of the main C file for the function case."
::=
<<
#include "omc_simulation_settings.h"
#include "<%filePrefix%>.h"
<% /* Note: The literals may not be part of the header due to separate compilation */
literals |> literal hasindex i0 fromindex 0 => literalExpConst(literal,i0) ; separator="\n";empty
%>
#include "util/modelica.h"
#include "<%filePrefix%>_includes.h"
<%if acceptParModelicaGrammar() then
<<
/* the OpenCL Kernels file name needed in libParModelicaExpl.a */
const char* omc_ocl_kernels_source = "<%filePrefix%>_kernels.cl";
/* the OpenCL program. Made global to avoid repeated builds */
extern cl_program omc_ocl_program;
/* The default OpenCL device. If not set (=0) show the selection option.*/
unsigned int default_ocl_device = <%getDefaultOpenCLDevice()%>;
>>
%>
<%if staticPrototypes then
<<
/* default, do not make protected functions static */
#if !defined(PROTECTED_FUNCTION_STATIC)
#define PROTECTED_FUNCTION_STATIC
#endif
<%staticPrototypes%>
>>
%>
<%match mainFunction case SOME(fn) then functionBody(fn,true,false)%>
<%functionBodies(functions,false)%>
<%\n%>
>>
end functionsFile;
template functionsHeaderFile(String filePrefix,
Option<Function> mainFunction,
list<Function> functions,
list<RecordDeclaration> extraRecordDecls,
Text &staticPrototypes)
"Generates the contents of the main C file for the function case."
::=
<<
#ifndef <%makeC89Identifier(filePrefix)%>__H
#define <%makeC89Identifier(filePrefix)%>__H
<%commonHeader(filePrefix)%>
#ifdef __cplusplus
extern "C" {
#endif
<%extraRecordDecls |> rd => recordDeclarationHeader(rd) ;separator="\n"%>
<%match mainFunction case SOME(fn) then functionHeader(fn,true,false,staticPrototypes)%>
<%functionHeaders(functions, false, staticPrototypes)%>
#ifdef __cplusplus
}
#endif
#endif<%\n%>
>>
/* adrpo: leave a newline at the end of file to get rid of the warning */
end functionsHeaderFile;
template functionsMakefile(FunctionCode fnCode)
"Generates the contents of the makefile for the function case."
::=
match fnCode
case FUNCTIONCODE(makefileParams=MAKEFILE_PARAMS(__)) then
let libsStr = (makefileParams.libs ;separator=" ")
let ParModelicaExpLibs = if acceptParModelicaGrammar() then '-lParModelicaExpl -lOpenCL' // else ""
let ExtraStack = if boolOr(stringEq(makefileParams.platform, "win32"),stringEq(makefileParams.platform, "win64")) then '--stack,16777216,'
let WinMingwExtraLibs = if boolAnd(acceptMetaModelicaGrammar(), boolOr(stringEq(makefileParams.platform, "win32"),stringEq(makefileParams.platform, "win64"))) then '-lOpenModelicaCompiler'
<<
# Makefile generated by OpenModelica
# Platform: <%makefileParams.platform%>
# Dynamic loading uses -O0 by default
# define OMC_CFLAGS_OPTIMIZATION env variable to your desired optimization level to override this
OMC_CFLAGS_OPTIMIZATION=-O0
SIM_OR_DYNLOAD_OPT_LEVEL=$(OMC_CFLAGS_OPTIMIZATION)
CC=<%if acceptParModelicaGrammar() then 'g++' else '<%makefileParams.ccompiler%>'%>
CXX=<%makefileParams.cxxcompiler%>
LINK=<%makefileParams.linker%>
EXEEXT=<%makefileParams.exeext%>
DLLEXT=<%makefileParams.dllext%>
DEBUG_FLAGS=<% if boolOr(acceptMetaModelicaGrammar(), Flags.isSet(Flags.GEN_DEBUG_SYMBOLS)) then " -g" else "$(SIM_OR_DYNLOAD_OPT_LEVEL)" %>
CFLAGS= $(DEBUG_FLAGS) <%makefileParams.cflags%>
CPPFLAGS= <%makefileParams.includes ; separator=" "%> -I"<%makefileParams.omhome%>/include/omc/c" -I"<%makefileParams.omhome%>/include/omc" <%
if Flags.isSet(Flags.OMC_RELOCATABLE_FUNCTIONS) then " -DOMC_GENERATE_RELOCATABLE_CODE"
%>
# define OMC_LDFLAGS_LINK_TYPE env variable to "static" to override this
OMC_LDFLAGS_LINK_TYPE=dynamic
RUNTIME_LIBS=<%makefileParams.runtimelibs%>
LDFLAGS= -L"<%makefileParams.omhome%>/lib/<%Autoconf.triple%>/omc" -Wl,<%ExtraStack%>-rpath,'<%makefileParams.omhome%>/lib/<%Autoconf.triple%>/omc' <%ParModelicaExpLibs%> <%WinMingwExtraLibs%> <%makefileParams.ldflags%> $(RUNTIME_LIBS)
PERL=perl
MAINFILE=<%name%>.c
.PHONY: <%name%>
<%name%>: $(MAINFILE) <%name%>.h <%name%>_records.c
<%\t%> $(CC) $(CFLAGS) $(CPPFLAGS) -c -o <%name%>.o $(MAINFILE)
<%\t%> $(CC) $(CFLAGS) $(CPPFLAGS) -c -o <%name%>_records.o <%name%>_records.c
<%\t%> $(LINK) -o <%name%>$(DLLEXT) <%name%>.o <%name%>_records.o <%libsStr%> $(CFLAGS) $(CPPFLAGS) $(LDFLAGS) -lm
>>
end functionsMakefile;
template commonHeader(String filePrefix)
::=
<<
#include "meta/meta_modelica.h"
#include "util/modelica.h"
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
<%if acceptParModelicaGrammar() then
<<
#include <ParModelica/explicit/openclrt/omc_ocl_interface.h>
>>
%>
>>
end commonHeader;
/* public */ template externalFunctionIncludes(list<String> includes)
"Generates external includes part in function files.
used in Compiler/Template/CodegenFMU.tpl.
Include openmodelica.h, because some Modelica libraries test if some tool depedent variable is set, e.g. TILMedia."
::=
if includes then
<<
#ifdef __cplusplus
extern "C" {
#endif
#include "openmodelica.h" // Defines OPENMODELICA_H_ for libraris to test if called from OpenModelica.
#include "ModelicaUtilities.h" // Make Modelica C util functions available for external includes.
<% (includes ;separator="\n") %>
#ifdef __cplusplus
}
#endif<%\n%>
>>
end externalFunctionIncludes;
template functionHeaders(list<Function> functions, Boolean isSimulation, Text &staticPrototypes)
"Generates function header part in function files."
::=
(functions |> fn => functionHeader(fn, false, isSimulation, staticPrototypes) ; separator="\n\n")
end functionHeaders;
template functionHeadersParModelica(String filePrefix, list<Function> functions)
"Generates the content of the C file for functions in the simulation case."
::=
<<
#ifndef <%makeC89Identifier(filePrefix)%>__H
#define <%makeC89Identifier(filePrefix)%>__H
//#include "helper.cl"
<%parallelFunctionHeadersImpl(functions)%>
#endif
<%\n%>
>>
/* adrpo: leave a newline at the end of file to get rid of the warning */
end functionHeadersParModelica;
template parallelFunctionHeadersImpl(list<Function> functions)
"Generates function header part in function files."
::=
(functions |> fn => parallelFunctionHeader(fn, false) ; separator="\n\n")
end parallelFunctionHeadersImpl;
template functionHeader(Function fn, Boolean inFunc, Boolean isSimulation, Text &staticPrototypes)
"Generates function header part in function files."
::=
match fn
case FUNCTION(__) then
<<
<%functionHeaderNormal(underscorePath(name), functionArguments, outVars, inFunc, visibility, false, isSimulation, staticPrototypes)%>
<%if not funcHasParallelInOutArrays(fn) then functionHeaderBoxed(underscorePath(name), functionArguments, outVars, inFunc, isBoxedFunction(fn), visibility, false, isSimulation, staticPrototypes)%>
>>
case KERNEL_FUNCTION(__) then
<<
<%functionHeaderKernelFunctionInterface(underscorePath(name), functionArguments, outVars)%>
>>
case EXTERNAL_FUNCTION(dynamicLoad=true) then
<<
<%functionHeaderNormal(underscorePath(name), funArgs, outVars, inFunc, visibility, true, isSimulation, staticPrototypes)%>
<%functionHeaderBoxed(underscorePath(name), funArgs, outVars, inFunc, isBoxedFunction(fn), visibility, true, isSimulation, staticPrototypes)%>
<%extFunDefDynamic(fn)%>
>>
case EXTERNAL_FUNCTION(__) then
<<
<%functionHeaderNormal(underscorePath(name), funArgs, outVars, inFunc, visibility, false, isSimulation, staticPrototypes)%>
<%functionHeaderBoxed(underscorePath(name), funArgs, outVars, inFunc, isBoxedFunction(fn), visibility, false, isSimulation, staticPrototypes)%>
<%extFunDef(fn)%>
>>
case RECORD_CONSTRUCTOR(__) then
let fname = underscorePath(name)
let funArgsStr = (funArgs |> var as VARIABLE(__) => ', <%varType(var)%> omc_<%crefStr(name)%>')
let vis = (match visibility case PUBLIC() then "DLLExport")
<<
<% if Flags.isSet(Flags.OMC_RELOCATABLE_FUNCTIONS)
then
<<
typedef <%fname%> (*omctd_<%fname%>)(threadData_t *threadData<%funArgsStr%>);
<%vis%>
omctd_<%fname%> omc_<%fname%>;
>>
else
<<
<%vis%>
<%fname%> omc_<%fname%> (threadData_t *threadData<%funArgsStr%>);
>>
%>
<%functionHeaderBoxed(fname, funArgs, boxedRecordOutVars, inFunc, false, visibility, false, isSimulation, staticPrototypes)%>
>>
end functionHeader;
template parallelFunctionHeader(Function fn, Boolean inFunc)
"Generates function header part in function files."
::=
match fn
case PARALLEL_FUNCTION(__) then
<<
<%functionHeaderParallelImpl(underscorePath(name), functionArguments, outVars, inFunc, false)%>;
>>
end parallelFunctionHeader;
template functionHeaderParallelImpl(String fname, list<Variable> fargs, list<Variable> outVars, Boolean inFunc, Boolean boxed)
"Generates parmodelica paralell function header part in kernels files."
::=
let fargsStr = (fargs |> var => funArgDefinitionKernelFunctionInterface(var) ;separator=", ")
// let &fargsStr += if outVars then ", " + (outVars |> var => tupleOutfunArgDefinitionKernelFunctionInterface(var) ;separator=", ")
// 'void omc_<%fname%>(<%fargsStr%>)'
match outVars
case {} then
'void omc_<%fname%>(<%fargsStr%>)'
case fvar::rest then
let rettype = varType(fvar)
let &fargsStr += if rest then ", " + (rest |> var => tupleOutfunArgDefinitionKernelFunctionInterface(var) ;separator=", ")
'<%rettype%> omc_<%fname%>(<%fargsStr%>)'
else
error(sourceInfo(), 'functionHeaderParallelImpl failed')
end functionHeaderParallelImpl;
template recordDeclaration(RecordDeclaration recDecl)
"Generates structs for a record declaration."
::=
match recDecl
case r as RECORD_DECL_FULL(__) then
<<
<%recordDefinition(dotPath(defPath),
underscorePath(defPath),
(variables |> VARIABLE(__) => '"<%crefStr(name)%>"' ;separator=","),
listLength(variables))%>
<%recordConstructorDef(r.name, r.name, r.variables)%>
<%recordCreateFromVarsDef(r.name, r.variables)%>
<%recordCopyDef(r.name, r.variables)%>
<%if r.usedExternally then recordCopyExternalDefs(r.name, r.variables)%>
>>
case r as RECORD_DECL_ADD_CONSTRCTOR(__) then
<<
<%recordConstructorDef(r.ctor_name, r.name, r.variables)%>
>>
case r as RECORD_DECL_DEF(__) then
<<
<%recordDefinition(dotPath(r.path),
underscorePath(r.path),
(r.fieldNames |> fname => '"<%fname%>"' ;separator=","),
listLength(r.fieldNames))%>
>>
end recordDeclaration;
template recordDeclarationHeader(RecordDeclaration recDecl)
"Generates structs for a record declaration."
::=
match recDecl
case r as RECORD_DECL_FULL(__) then recordDeclarationFullHeader(r)
case r as RECORD_DECL_ADD_CONSTRCTOR(__) then recordDeclarationExtraCtor(r)
// TODO revise me
case r as RECORD_DECL_DEF(__) then 'extern struct record_description <%underscorePath(r.path)%>__desc;<%\n%>'
end recordDeclarationHeader;
template recordDeclarationExtraCtor(RecordDeclaration recDecl)
"Generates structs for a extra record declaration. An extra
record declration is a constructor with some of its elements provided
from outside. Modelica puts a lot of freedom on record creation. You can
generally provide none, some or all elements to create a record without
providing a single constructor. Which means a record with N elements
can have 2^N possible constructions.
e.g.,
record R
Real a=1,b=1,c=1;
end R;
R r1(a=2);
R r2(a=3,c=4);
....
These will be created by additional constructors:
R_1_construct(r1,2);
R_1_3_construct(r2,3,4);
...
Do not worry, these are created once for every use case and ONLY if they
are actually used by something."
::=
match recDecl
case r as RECORD_DECL_ADD_CONSTRCTOR(__) then
let ctor_name = r.ctor_name
let rec_name = r.name
let ctor_macro_name = '<%ctor_name%>_construct'
let ctor_macro_additional_inputs = (r.variables |> var as VARIABLE(__) => if var.bind_from_outside
then (", " + "in_" + crefStr(var.name))
)
let ctor_func_name = '<%ctor_macro_name%>_p'
let ctor_additional_inputs = (r.variables |> var as VARIABLE(__) => if var.bind_from_outside
then (", " + varType(var) + " in_" + crefStr(var.name))
)
<<
void <%ctor_func_name%>(threadData_t *threadData, void* v_ths <%ctor_additional_inputs%>);
#define <%ctor_macro_name%>(td, ths <%ctor_macro_additional_inputs%>) <%ctor_func_name%>(td, &ths <%ctor_macro_additional_inputs%>)
#define alloc_<%ctor_name%>_array(dst,ndims,...) generic_array_create(NULL, dst, <%ctor_func_name%>, ndims, sizeof(<%rec_name%>), __VA_ARGS__)
>>
end recordDeclarationExtraCtor;
template recordDeclarationFullHeader(RecordDeclaration recDecl)
"Generates structs for a record declaration. This will generate
a default record constructor function (no arguments) and a record copy function.
These generated functions are fully recursive. That means records in records
will be handled properly.
It will also generate (#define) array versions of these functions."
::=
match recDecl
case r as RECORD_DECL_FULL(__) then
let rec_name = r.name
let ctor_macro_name = '<%rec_name%>_construct'
let ctor_macro_additional_inputs = (r.variables |> var as VARIABLE(__) => if var.bind_from_outside
then (", " + "in_" + crefStr(var.name))
)
let ctor_func_name = '<%ctor_macro_name%>_p'
let ctor_additional_inputs = (r.variables |> var as VARIABLE(__) => if var.bind_from_outside
then (", " + varType(var) + " in_" + crefStr(var.name))
)
let cpy_macro_name = '<%rec_name%>_copy'
let cpy_func_name = '<%cpy_macro_name%>_p'
let cpy_to_external_macro_name = '<%rec_name%>_copy_to_external'
let cpy_to_external_func_name = '<%cpy_to_external_macro_name%>_p'
let cpy_from_external_macro_name = '<%rec_name%>_copy_from_external'
let cpy_from_external_func_name = '<%cpy_from_external_macro_name%>_p'
let copy_to_vars_name = '<%rec_name%>_copy_to_vars'
let copy_to_vars_name_p = '<%copy_to_vars_name%>_p'
let copy_to_vars_inputs = r.variables |> var as VARIABLE(__) => (", " + varType(var) + "* in_" + crefStr(var.name))
let wrap_vars_macro_name = '<%rec_name%>_wrap_vars'
let wrap_vars_func_name = '<%wrap_vars_macro_name%>_p'
let wrap_vars_macro_inputs = r.variables |> var as VARIABLE(__) => (", " + "in_" + crefStr(var.name))
let wrap_vars_func_inputs = r.variables |> var as VARIABLE(__) => (", " + varType(var) + " in_" + crefStr(var.name))
<<
<% match aliasName
case SOME(str) then
<<
typedef <%str%> <%rec_name%>;
<% if r.usedExternally then
<<
typedef <%str%>_external <%rec_name%>_external;
>>
%>
>>
else
<<
typedef struct {
<%r.variables |> var as VARIABLE(__) => '<%varType(var)%> _<%crefStr(var.name)%>;' ;separator="\n"%>
} <%rec_name%>;
<% if r.usedExternally then
<<
typedef struct {
<%r.variables |> var as VARIABLE(__) => '<%extType(var.ty, true, false, false)%> _<%crefStr(var.name)%>;' ;separator="\n"%>
} <%rec_name%>_external;
>>
%>
>>
%>
extern struct record_description <%underscorePath(r.defPath)%>__desc;
void <%ctor_func_name%>(threadData_t *threadData, void* v_ths <%ctor_additional_inputs%>);
#define <%ctor_macro_name%>(td, ths <%ctor_macro_additional_inputs%>) <%ctor_func_name%>(td, &ths <%ctor_macro_additional_inputs%>)
void <%cpy_func_name%>(void* v_src, void* v_dst);
#define <%cpy_macro_name%>(src,dst) <%cpy_func_name%>(&src, &dst)
<%if r.usedExternally then
<<
void <%cpy_to_external_func_name%>(void* v_src, void* v_dst);
#define <%cpy_to_external_macro_name%>(src,dst) <%cpy_to_external_func_name%>(&src, &dst)
void <%cpy_from_external_func_name%>(void* v_src, void* v_dst);
#define <%cpy_from_external_macro_name%>(src,dst) <%cpy_from_external_func_name%>(&src, &dst)
>>
%>
void <%wrap_vars_func_name%>(threadData_t *threadData , void* v_dst <%wrap_vars_func_inputs%>);
#define <%wrap_vars_macro_name%>(td, dst <%wrap_vars_macro_inputs%>) <%wrap_vars_func_name%>(td, &dst <%wrap_vars_macro_inputs%>)
// This function is not needed anymore. If you want to know how a record
// is 'assigned to' in simulation context see assignRhsExpToRecordCrefSimContext and
// splitRecordAssignmentToMemberAssignments (simCode). Basically the record is
// split up assignments generated for each member individually.
// void <%copy_to_vars_name_p%>(void* v_src <%copy_to_vars_inputs%>);
// #define <%copy_to_vars_name%>(src,...) <%copy_to_vars_name_p%>(&src, __VA_ARGS__)
typedef base_array_t <%rec_name%>_array;
#define alloc_<%rec_name%>_array(dst,ndims,...) generic_array_create(NULL, dst, <%ctor_func_name%>, ndims, sizeof(<%rec_name%>), __VA_ARGS__)
#define <%rec_name%>_array_copy_data(src,dst) generic_array_copy_data(src, &dst, <%cpy_func_name%>, sizeof(<%rec_name%>))
#define <%rec_name%>_array_alloc_copy(src,dst) generic_array_alloc_copy(src, &dst, <%cpy_func_name%>, sizeof(<%rec_name%>))
#define <%rec_name%>_array_get(src,ndims,...) (*(<%rec_name%>*)(generic_array_get(&src, sizeof(<%rec_name%>), __VA_ARGS__)))
#define <%rec_name%>_set(dst,val,...) generic_array_set(&dst, &val, <%cpy_func_name%>, sizeof(<%rec_name%>), __VA_ARGS__)
>>
end recordDeclarationFullHeader;
template recordCopyDef(String rec_name, list<Variable> variables)
"Generates code for copying one instance of a record to another
instance of the same record type."
::=
let &varCopies = buffer ""
let &auxFunction = buffer ""
let dst_pref = 'dst->'
let src_pref = 'src->'
let _ = (variables |> var => recordMemberCopy(var, src_pref, dst_pref, &varCopies, &auxFunction) ;separator="\n")
<<
void <%rec_name%>_copy_p(void* v_src, void* v_dst) {
<%rec_name%>* src = (<%rec_name%>*)(v_src);
<%rec_name%>* dst = (<%rec_name%>*)(v_dst);
<%varCopies%>
}
>>
end recordCopyDef;
template recordCopyExternalDefs(String rec_name, list<Variable> variables)
"Generates code for copying a record to/from the extrenal C counterpart.
The external C counterpart of a record has data types set according to the
Modelica Standard. The main difference right now is Intger tyepes. In
OpenModelica Integer types are represented by 'long' a.k.a modelica_integer.
In the external counter part of the record they are 'int'. These functions
make sure the conversion is done using assigment (possiblly truncating values)
to make sure that the data is not interpreted wrong due to the size differences.
See #8591 for more info."
::=
let &varCopiesTo = buffer ""
let &varCopiesFrom = buffer ""
let &auxFunction = buffer ""
let dst_pref = 'dst->'
let src_pref = 'src->'
let _ = (variables |> var => recordMemberCopyToFromExternal(var, src_pref, dst_pref, true, &varCopiesTo, &auxFunction) ;separator="\n")
let _ = (variables |> var => recordMemberCopyToFromExternal(var, src_pref, dst_pref, false, &varCopiesFrom, &auxFunction) ;separator="\n")
<<
void <%rec_name%>_copy_to_external_p(void* v_src, void* v_dst) {
<%rec_name%>* src = (<%rec_name%>*)(v_src);
<%rec_name%>_external* dst = (<%rec_name%>_external*)(v_dst);
<%varCopiesTo%>
}
void <%rec_name%>_copy_from_external_p(void* v_src, void* v_dst) {
<%rec_name%>_external* src = (<%rec_name%>_external*)(v_src);
<%rec_name%>* dst = (<%rec_name%>*)(v_dst);
<%varCopiesFrom%>
}
>>
end recordCopyExternalDefs;
template recordCreateFromVarsDef(String rec_name, list<Variable> variables)
"Generates code for creating and initializing (shallow copies) a record given values for
ALL its members. This is used internally by the generated code to reconstruct
records from (the scattered) simulation member variables of the record. We do
this when we have to send a record used in equation context to a function.
Note that this is defferent from the constructors we have. This one expects
all the memebers to be already created (allocated and given values whatever the value is).
Its job is to 'wrap' these variables by a given record instance, e.g., so it can be sent to
functions from simulation code.
"
::=
let &auxFunction = buffer ""
let dst_pref = 'dst->'
let src_pref = 'in'
let varCopies = (variables |> var => match var
case var as VARIABLE(__) then
let dstName = dst_pref + contextCrefNoPrevExp(var.name, contextFunction, &auxFunction)
let srcName = src_pref + contextCrefNoPrevExp(var.name, contextFunction, &auxFunction)
'<%dstName%> = <%srcName%>;<%\n%>'
else error(sourceInfo(), "recordCreateFromVarsDef: Unhandled variable type"))
let fn_inputs = (variables |> var as VARIABLE(__) =>
(", " + varType(var) + " " + src_pref + contextCrefNoPrevExp(var.name, contextFunction, &auxFunction))
)
let ctor_additional_inputs = (variables |> var as VARIABLE(__) => if var.bind_from_outside
then (", " + "in_" + crefStr(var.name))
)
<<
void <%rec_name%>_wrap_vars_p(threadData_t *threadData, void* v_dst <%fn_inputs%>) {
<%rec_name%>* dst = (<%rec_name%>*)(v_dst);
<%varCopies%>
}
>>
end recordCreateFromVarsDef;
template recordMemberCopy(Variable var, String src_pref, String dst_pref, Text &varCopies, Text &auxFunction)
"Generates code for copying memembers of a record during a record copy operation.
This function is needed because we need to have a 'localized' operation. Localized as
in references in these copy operations need to be resolved to other mememers of the
record. So we use prefixes (e.g. src->) to generate crefs in these operations."
::=
match var
case var as VARIABLE(__) then
let dstName = dst_pref + contextCrefNoPrevExp(var.name, contextFunction, &auxFunction)
let srcName = src_pref + contextCrefNoPrevExp(var.name, contextFunction, &auxFunction)
match ty
case ty as T_ARRAY(__) then
let varType = expTypeShort(ty)
let &varCopies += '<%varType%>_array_copy_data(<%srcName%>, <%dstName%>);<%\n%>'
""
case ty as T_COMPLEX(complexClassType=RECORD(__)) then
let recType = expTypeShort(ty)
let &varCopies += '<%recType%>_copy(<%srcName%>, <%dstName%>);<%\n%>'
""
else
let &varCopies += '<%dstName%> = <%srcName%>;<%\n%>'
""
end match
end recordMemberCopy;
template recordMemberCopyToFromExternal(Variable var, String src_pref, String dst_pref, Boolean copy_to, Text &varCopies, Text &auxFunction)
"Generates code for copying memembers of a record during a record copy to/from the version
of the record created for use with external C code.
Right now this does not support copying of array or record record memebers. It only handles
simple scalar assignments"
::=
match var
case var as VARIABLE(__) then
let dstName = dst_pref + contextCrefNoPrevExp(var.name, contextFunction, &auxFunction)
let srcName = src_pref + contextCrefNoPrevExp(var.name, contextFunction, &auxFunction)
match ty
case ty as T_ARRAY(__) then
let &varCopies += 'omc_assert(NULL, omc_dummyFileInfo, "Copying of array record members to/from external functions is not yet supported.");<%\n%>'
""
case ty as T_STRING(__) then
let &varCopies += if copy_to then
'<%dstName%> = MMC_STRINGDATA(<%srcName%>);<%\n%>'
else
'omc_assert(NULL, omc_dummyFileInfo, "Copying of string record members from external functions is not yet supported.");<%\n%>'
""
case ty as T_COMPLEX(complexClassType=RECORD(__)) then
let recType = expTypeShort(ty)
let &varCopies += if copy_to then
'<%recType%>_copy_to_external(<%srcName%>, <%dstName%>);<%\n%>'
else
'<%recType%>_copy_from_external(<%srcName%>, <%dstName%>);<%\n%>'
""
else
let &varCopies += '<%dstName%> = <%srcName%>;<%\n%>'
""
end match
end recordMemberCopyToFromExternal;
template recordConstructorDef(String ctor_name, String rec_name, list<Variable> variables)
"Generates code for constructing a record. This means allocating memory for all
members of the record and then initializing them with their default values. Sometimes
we can have modelica derived records (e.g. record A = B(c=exp)), this will be a new
record type whcih needs an exp to be passed to to be initialized correctly. This is
also handled by these function. Check markDerivedRecordOutsideBindings and makeTypeRecordVar
in the OF and NF respectively."
::=
let &varDecls = buffer ""
let &auxFunction = buffer ""
let ctor_additional_inputs = (variables |> var as VARIABLE(__) => if var.bind_from_outside
then (", " + varType(var) + " in" + contextCrefNoPrevExp(var.name, contextFunction, &auxFunction))
)
let varInits = (variables |> var => recordMemberAllocInit(var, appendCurrentCrefPrefix(contextFunction, "ths->"), &varDecls, &auxFunction) /*;separator="\n"*/)
<<
void <%ctor_name%>_construct_p(threadData_t *threadData, void* v_ths <%ctor_additional_inputs%>) {
<%rec_name%>* ths = (<%rec_name%>*)(v_ths);
<%varDecls%>
<%varInits%>
}
>>
end recordConstructorDef;
template recordMemberAllocInit(Variable var, Context context, Text &varDecls, Text &auxFunction)
::=
match var
case var as VARIABLE(__) then
match var.ty
case ty as T_ARRAY(__) then arrayVarAllocInit(var.name, var.ty, ty.dims, var.value, var.bind_from_outside, context, &varDecls, &auxFunction)
case ty as T_COMPLEX(complexClassType=RECORD(__)) then recordVarAllocInit(var.value, var.name, var.bind_from_outside, var.ty, context, &varDecls, &auxFunction)
else simpleVarInit(var.value, var.name, var.bind_from_outside, context, &varDecls, &auxFunction)
end match
end recordMemberAllocInit;
template simpleVarInit(Option<Exp> value, ComponentRef var_cref, Boolean bind_outside, Context context, Text &varDecls, Text &auxFunction)
::=
let var_name = contextCrefNoPrevExp(var_cref, context, &auxFunction)
match value
case SOME(rhs_exp) then
let &preExp = buffer ""
let rhs = if bind_outside then "in" + contextCrefNoPrevExp(var_cref, contextFunction /*unprefixed context*/, &auxFunction)
else daeExp(rhs_exp, context, &preExp, &varDecls, &auxFunction)
<<
<%preExp%>
<%var_name%> = <%rhs%>;<%\n%>
>>
case NONE() then
'// <%var_name%> has no default value.<%\n%>'
end match
end simpleVarInit;
template recordVarAllocInit(Option<Exp> value, ComponentRef var_cref, Boolean bind_outside, Type var_type, Context context, Text &varDecls, Text &auxFunction)
::=
let &preExp = buffer ""
let &ctor_suffix = buffer ""
let type_name = expTypeShort(var_type)
let var_name = contextCrefNoPrevExp(var_cref, context, &auxFunction)
let ctor_additional_inputs = match var_type
case ty as DAE.T_COMPLEX() then
(ty.varLst |> sv hasindex i1 fromindex 1 =>
recordInitOutsideBindings(sv, i1, &ctor_suffix, context, &preExp, &varDecls, &auxFunction); empty /* increase the counter! */
)
end match
let allocation = '<%type_name%><%ctor_suffix%>_construct(threadData, <%var_name%><%ctor_additional_inputs%>);'
match value
case SOME(rhs_exp) then
let &preExp1 = buffer ""
let copy_stmt = if bind_outside then
let in_var_name = "in" + contextCrefNoPrevExp(var_cref, contextFunction /*unprefixed context*/, &auxFunction)
'<%type_name%>_copy(<%in_var_name%>, <%var_name%>);'
else
assignRhsExpToRecordCref(var_cref, rhs_exp, var_type, context, &preExp1, &varDecls, &auxFunction)
<<
<%preExp%>
<%allocation%>
<%preExp1%>
<%copy_stmt%>;
>>
case NONE() then
<<
<%preExp%>
<%allocation%> // <%var_name%> has no default value.<%\n%>
>>
end match
end recordVarAllocInit;
template recordInitOutsideBindings(Var subvar, Integer ix, Text& ctor_suffix, Context context, Text &preExp, Text &varDecls, Text &auxFunction)
::=
match subvar
case TYPES_VAR(binding=EQBOUND(exp=exp), bind_from_outside = true) then
let &ctor_suffix += "_" + ix
", " + daeExp(exp, context, &preExp, &varDecls, &auxFunction)
case TYPES_VAR(bind_from_outside = true) then
error(sourceInfo(), 'Record has binding from outside but found a non EQBOUND binding. Implement me.')
end match
end recordInitOutsideBindings;
template arrayVarAllocInit(ComponentRef var_cref, Type var_type, list<DAE.Dimension> var_dims, Option<DAE.Exp> value, Boolean bind_outside, Context context, Text &varDecls, Text &auxFunction)
::=
let type_name = expTypeShort(var_type)
let var_name = contextCrefNoPrevExp(var_cref, context, &auxFunction)
match value
case SOME(rhs_exp) then
let &preExpBind = buffer ""
let rhs = if bind_outside then "in" + contextCrefNoPrevExp(var_cref, contextFunction /*unprefixed context*/, &auxFunction)
else daeExp(rhs_exp, context, &preExpBind, &varDecls, &auxFunction)
if Expression.hasUnknownDims(var_dims) then
<<
<%preExpBind%>
<%type_name%>_array_alloc_copy(<%rhs%>, <%var_name%>);
>>
else
let &preExpAlloc = buffer ""
let dims_str = (var_dims |> dim => '(_index_t)<%dimension(dim, context, &preExpAlloc, &varDecls, &auxFunction)%>' ;separator=", ")
<<
<%preExpAlloc%>
alloc_<%type_name%>_array(&(<%var_name%>), <%listLength(var_dims)%>, <%dims_str%>);
<%preExpBind%>
<%type_name%>_array_copy_data(<%rhs%>, <%var_name%>);
>>
case NONE() then
// If an array variable has unknown dimensions but does not have a default value (declaration binding)
// then the variable is flexible. That means it can actually change its dimensions whenever it is
// assigned to. Ya it is allowed :/
if Expression.hasUnknownDims(var_dims) then
<<
generic_array_create_flexible(&<%var_name%>, <%listLength(var_dims)%>); // <%var_name%> has unknown size and no default value. It is flexible.<%\n%>
>>
else
let &preExpAlloc = buffer ""
let dims_str = (var_dims |> dim => '(_index_t)<%dimension(dim, context, &preExpAlloc, &varDecls, &auxFunction)%>' ;separator=", ")
<<
<%preExpAlloc%>
alloc_<%type_name%>_array(&(<%var_name%>), <%listLength(var_dims)%>, <%dims_str%>); // <%var_name%> has no default value.<%\n%>
>>
end match
end arrayVarAllocInit;
template recordDefinition(String origName, String encName, String fieldNames, Integer numFields)
"Generates the definition struct for a record declaration."
::=
match encName
case "SourceInfo_SOURCEINFO" then ''
else
/* adrpo: 2011-03-14 make MSVC happy, no arrays of 0 size! */
let fieldsDescription =
match numFields
case 0 then
'const char* <%encName%>__desc__fields[1] = {"no fields"};'
case _ then
'const char* <%encName%>__desc__fields[<%numFields%>] = {<%fieldNames%>};'
<<
#define <%encName%>__desc_added 1
<%fieldsDescription%>
struct record_description <%encName%>__desc = {
"<%encName%>", /* package_record__X */
"<%origName%>", /* package.record_X */
<%encName%>__desc__fields
};
>>
end recordDefinition;
template recordDefinitionHeader(String origName, String encName, Integer numFields)
"Generates the definition struct for a record declaration."
::=
<<
extern struct record_description <%encName%>__desc;
>>
end recordDefinitionHeader;
template functionHeaderNormal(String fname, list<Variable> fargs, list<Variable> outVars, Boolean inFunc, SCode.Visibility visibility, Boolean dynLoad, Boolean isSimulation, Text &staticPrototypes)
::=functionHeaderImpl(fname, fargs, outVars, inFunc, false, visibility, dynLoad, isSimulation, staticPrototypes)
end functionHeaderNormal;
template functionHeaderBoxed(String fname, list<Variable> fargs, list<Variable> outVars, Boolean inFunc, Boolean isBoxed, SCode.Visibility visibility, Boolean dynLoad, Boolean isSimulation, Text &staticPrototypes)
::=
let boxvar =
<<
static const MMC_DEFSTRUCTLIT(boxvar_lit_<%fname%>,2,0) {(void*) <%if Flags.isSet(Flags.OMC_RELOCATABLE_FUNCTIONS) then "&"%>boxptr_<%fname%>,0}};
#define boxvar_<%fname%> MMC_REFSTRUCTLIT(boxvar_lit_<%fname%>)<%\n%>
>>
<<
<%if isBoxed then '#define boxptr_<%fname%> omc_<%fname%><%\n%>' else functionHeaderImpl(fname, fargs, outVars, inFunc, true, visibility, dynLoad, isSimulation, staticPrototypes)%>
<% match visibility
case PROTECTED(__) then
let &staticPrototypes += (if boolOr(isSimulation, Flags.isSet(Flags.OMC_RELOCATABLE_FUNCTIONS)) then "" else boxvar)
if boolOr(isSimulation, Flags.isSet(Flags.OMC_RELOCATABLE_FUNCTIONS)) then '<%boxvar%> /* boxvar early */' else ""
else boxvar %>
>>
end functionHeaderBoxed;
template functionHeaderImpl(String fname, list<Variable> fargs, list<Variable> outVars, Boolean inFunc, Boolean boxed, SCode.Visibility visibility, Boolean dynamicLoad, Boolean isSimulation, Text &staticPrototypes)
"Generates function header for a Modelica/MetaModelica function. Generates a
boxed version of the header if boxed = true, otherwise a normal header"
::=
let &dummy = buffer ""
let prototype = functionPrototype(fname, fargs, outVars, boxed, visibility, isSimulation, true, dummy)
let inFnStr = if boolAnd(boxed,inFunc) then
<<
DLLExport
int in_<%fname%>(threadData_t *threadData, type_description * inArgs, type_description * outVar);
>>
match visibility
case PROTECTED(__) then
if boolOr(isSimulation, Flags.isSet(Flags.OMC_RELOCATABLE_FUNCTIONS)) then
if dynamicLoad then "" else '<%prototype%>;<%\n%>'
else
let &staticPrototypes += if dynamicLoad then "" else '<%prototype%>;<%\n%>'
inFnStr
else
<<
<%inFnStr%>
<%if dynamicLoad then '' else 'DLLExport<%\n%><%prototype%>;'%>
>>
end functionHeaderImpl;
template functionPrototype(String fname, list<Variable> fargs, list<Variable> outVars, Boolean boxed, SCode.Visibility visibility, Boolean isSimulation, Boolean isPrototype, Text &afterBody)
"Generates function header definition for a Modelica/MetaModelica function. Generates a boxed version of the header if boxed = true, otherwise a normal definition"
::=
let static = if isSimulation then "" else (match visibility case PROTECTED(__) then 'PROTECTED_FUNCTION_STATIC ')
let fargsStr = if boxed then
(fargs |> var => ", " + funArgBoxedDefinition(var) )
else
(fargs |> var => ", " + funArgDefinition(var) )
let outarg = (match outVars
case var::_ then (match var
case VARIABLE(__) then if boxed then varTypeBoxed(var) else varType(var)
case FUNCTION_PTR(__) then "modelica_fnptr")
else "void")
let boxPtrStr = if boxed then "boxptr" else "omc"
let fn_name = '<%boxPtrStr%>_<%fname%>'
let fn_name_impl = (if isPrototype then fn_name else '<%boxPtrStr%>impl_<%fname%>')
let fn_name_typedef = (if Flags.isSet(Flags.OMC_RELOCATABLE_FUNCTIONS) then '<%boxPtrStr%>td_<%fname%>' else fn_name)
let fn_name_ptr_typedef = (if Flags.isSet(Flags.OMC_RELOCATABLE_FUNCTIONS) then (if isPrototype then '(*<%fn_name_typedef%>)' else fn_name_impl) else fn_name)