/
CodegenCFunctions.tpl
6716 lines (6159 loc) · 274 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.*;
/* 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 <%name%>(threadData_t*,modelica_metatype);
void (*omc_assert)(threadData_t*,FILE_INFO info,const char *msg,...) __attribute__((noreturn)) = omc_assert_function;
void (*omc_assert_warning)(FILE_INFO info,const char *msg,...) = omc_assert_warning_function;
void (*omc_terminate)(FILE_INFO info,const char *msg,...) = omc_terminate_function;
void (*omc_throw)(threadData_t*) __attribute__ ((noreturn)) = omc_throw_function;
#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), '<%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 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."
::=
let &preLit = buffer ""
let literalsRes = literals |> literal hasindex i0 fromindex 0 => literalExpConst(literal,i0,&preLit) ; separator="\n";empty
<<
#include "<%filePrefix%>.h"
<% preLit %>
<% /* Note: The literals may not be part of the header due to separate compilation */
literalsRes
%>
#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%>
>>
%>
<% if mainFunction then
<<
void (*omc_assert)(threadData_t*,FILE_INFO info,const char *msg,...) __attribute__((noreturn)) = omc_assert_function;
void (*omc_assert_warning)(FILE_INFO info,const char *msg,...) = omc_assert_warning_function;
void (*omc_terminate)(FILE_INFO info,const char *msg,...) = omc_terminate_function;
void (*omc_throw)(threadData_t*) __attribute__ ((noreturn)) = omc_throw_function;
>> %>
<%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 <%stringReplace(filePrefix,".","_")%>__H
#define <%stringReplace(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 ""
<<
# Makefile generated by OpenModelica
# Dynamic loading uses -O0 by default
SIM_OR_DYNLOAD_OPT_LEVEL=-O0
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"%>
CFLAGS= -I"<%makefileParams.omhome%>/include/omc/c" <%makefileParams.includes ; separator=" "%> $(DEBUG_FLAGS) <%makefileParams.cflags%>
LDFLAGS= -L"<%makefileParams.omhome%>/lib/<%getTriple()%>/omc" -Wl,-rpath,'<%makefileParams.omhome%>/lib/<%getTriple()%>/omc' <%ParModelicaExpLibs%> <%makefileParams.ldflags%> <%makefileParams.runtimelibs%>
PERL=perl
MAINFILE=<%name%>.c
.PHONY: <%name%>
<%name%>: $(MAINFILE) <%name%>.h <%name%>_records.c
<%\t%> $(CC) $(CFLAGS) -c -o <%name%>.o $(MAINFILE)
<%\t%> $(CC) $(CFLAGS) -c -o <%name%>_records.o <%name%>_records.c
<%\t%> $(LINK) -o <%name%>$(DLLEXT) <%name%>.o <%name%>_records.o <%libsStr%> $(CFLAGS) $(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"
::=
if includes then
<<
#ifdef __cplusplus
extern "C" {
#endif
<% (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 <%stringReplace(filePrefix,".","_")%>__H
#define <%stringReplace(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)%>')
<<
<% match visibility case PUBLIC() then "DLLExport" %>
<%fname%> omc_<%fname%>(threadData_t *threadData<%funArgsStr%>); /* record head */
<%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 RECORD_DECL_FULL(__) then
<<
<%recordDefinition(dotPath(defPath),
underscorePath(defPath),
(variables |> VARIABLE(__) => '"_<%crefStr(name)%>"' ;separator=","),
listLength(variables))%>
>>
case RECORD_DECL_DEF(__) then
<<
<%recordDefinition(dotPath(path),
underscorePath(path),
(fieldNames |> name => '"<%name%>"' ;separator=","),
listLength(fieldNames))%>
>>
end recordDeclaration;
template recordDeclarationHeader(RecordDeclaration recDecl)
"Generates structs for a record declaration."
::=
match recDecl
case r as RECORD_DECL_FULL(__) then
<<
<% match aliasName
case SOME(str) then 'typedef <%str%> <%r.name%>;'
else <<
typedef struct <%r.name%>_s {
<%r.variables |> var as VARIABLE(__) => '<%varType(var)%> _<%crefStr(var.name)%>;' ;separator="\n"%>
} <%r.name%>;
>> %>
typedef base_array_t <%name%>_array;
<%recordDefinitionHeader(dotPath(defPath),
underscorePath(defPath),
listLength(variables))%>
>>
case RECORD_DECL_DEF(__) then
<<
<%recordDefinitionHeader(dotPath(path),
underscorePath(path),
listLength(fieldNames))%>
>>
end recordDeclarationHeader;
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*) 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 isSimulation then "" else boxvar)
if isSimulation 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 prototype = functionPrototype(fname, fargs, outVars, boxed, visibility, isSimulation)
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 isSimulation 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)
"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 {} then "void"
case var::_ then (match var
case VARIABLE(__) then if boxed then varTypeBoxed(var) else varType(var)
case FUNCTION_PTR(__) then "modelica_fnptr"))
let boxPtrStr = if boxed then "boxptr" else "omc"
if outVars then
let outargs = List.rest(outVars) |> var => ", " + (match var
case var as VARIABLE(__) then '<%if boxed then varTypeBoxed(var) else varType(var)%> *out<%funArgName(var)%>'
case FUNCTION_PTR(__) then 'modelica_fnptr *out<%funArgName(var)%>')
'<%static%><%outarg%> <%boxPtrStr%>_<%fname%>(threadData_t *threadData<%fargsStr%><%outargs%>)'
else
'<%static%>void <%boxPtrStr%>_<%fname%>(threadData_t *threadData<%fargsStr%>)'
end functionPrototype;
template functionHeaderKernelFunctionInterface(String fname, list<Variable> fargs, list<Variable> outVars)
"Generates function header for a ParModelica Kernel function interface."
::=
'<%functionHeaderKernelFunctionInterfacePrototype(fname, fargs, outVars)%>;'
end functionHeaderKernelFunctionInterface;
template functionHeaderKernelFunctionInterfacePrototype(String fname, list<Variable> fargs, list<Variable> outVars)
"Generates function header for a ParModelica Kernel function interface."
::=
let fargsStr = 'threadData_t *threadData'
let &fargsStr += if fargs then ", " + (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(), 'functionHeaderKernelFunctionInterfacePrototype failed')
end functionHeaderKernelFunctionInterfacePrototype;
template funArgName(Variable var)
::=
let &auxFunction = buffer ""
match var
case VARIABLE(__) then contextCref(name,contextFunction,&auxFunction)
case FUNCTION_PTR(__) then '_' + name
end funArgName;
template funArgDefinition(Variable var)
::=
let &auxFunction = buffer ""
match var
case VARIABLE(__) then ('<%varType(var)%> <%contextCref(name,contextFunction,&auxFunction)%>' + (if var.instDims then " = {0}"))
case FUNCTION_PTR(__) then 'modelica_fnptr _<%name%>'
end funArgDefinition;
template funArgDefinitionKernelFunctionInterface(Variable var)
::=
let &auxFunction = buffer ""
match var
case VARIABLE(__) then
'<%varType(var)%> <%funArgName(var)%>'
else error(sourceInfo(), 'funArgDefinitionKernelFunctionInterface : unsupported function argument type')
end funArgDefinitionKernelFunctionInterface;
template tupleOutfunArgDefinitionKernelFunctionInterface(Variable var)
::=
let &auxFunction = buffer ""
match var
case VARIABLE(__) then
'<%varType(var)%> *out<%funArgName(var)%>'
else error(sourceInfo(), 'tupleOutfunArgDefinitionKernelFunctionInterface : unsupported function argument type')
end tupleOutfunArgDefinitionKernelFunctionInterface;
template funArgDefinitionKernelFunctionBody(Variable var)
"Generates code to initialize variables.
Does not return anything: just appends declarations to buffers."
::=
let &auxFunction = buffer ""
match var
//function args will have nill instdims even if they are arrays. handled here
case var as VARIABLE(ty=T_ARRAY(__), parallelism = PARGLOBAL(__)) then
let varName = '<%contextCref(var.name,contextParallelFunction,&auxFunction)%>'
'__global modelica_<%expTypeShort(var.ty)%>* data_<%varName%>,<%\n%> __global modelica_integer* info_<%varName%>'
case var as VARIABLE(ty=T_ARRAY(__), parallelism = PARLOCAL(__)) then
let varName = '<%contextCref(var.name,contextParallelFunction,&auxFunction)%>'
'__local modelica_<%expTypeShort(var.ty)%>* data_<%varName%>,<%\n%> __local modelica_integer* info_<%varName%>'
case var as VARIABLE(__) then
let varName = '<%contextCref(var.name,contextParallelFunction,&auxFunction)%>'
if instDims then
(match parallelism
case PARGLOBAL(__) then
'__global modelica_<%expTypeShort(var.ty)%>* data_<%varName%>,<%\n%> __global modelica_integer* info_<%varName%>'
case PARLOCAL(__) then
'__local modelica_<%expTypeShort(var.ty)%>* data_<%varName%>,<%\n%> __local modelica_integer* info_<%varName%>'
)
else
'modelica_<%expTypeShort(var.ty)%> <%varName%>'
else '#error Unknown variable type in as function argument funArgDefinitionKernelFunctionBody<%\n%>'
end funArgDefinitionKernelFunctionBody;
template funArgDefinitionKernelFunctionBody2(Variable var, Text &parArgList /*BUFPA*/)
"Generates code to initialize variables.
Does not return anything: just appends declarations to buffers."
::=
let &auxFunction = buffer ""
match var
//function args will have nill instdims even if they are arrays. handled here
case var as VARIABLE(ty=T_ARRAY(__)) then
let varName = '<%contextCref(var.name,contextParallelFunction,&auxFunction)%>'
let &parArgList += ',<%\n%> __global modelica_<%expTypeShort(var.ty)%>* data_<%varName%>,'
let &parArgList += '<%\n%> __global modelica_integer* info_<%varName%>'
""
case var as VARIABLE(__) then
let varName = '<%contextCref(var.name,contextParallelFunction,&auxFunction)%>'
if instDims then
let &parArgList += ',<%\n%> __global modelica_<%expTypeShort(var.ty)%>* data_<%varName%>,'
let &parArgList += '<%\n%> __global modelica_integer* info_<%varName%>'
" "
else
let &parArgList += ',<%\n%> modelica_<%expTypeShort(var.ty)%> <%varName%>'
""
else let &parArgList += ' #error Unknown variable type in as function argument funArgDefinitionKernelFunctionBody2<%\n%>' ""
end funArgDefinitionKernelFunctionBody2;
template parFunArgDefinitionFromLooptupleVar(tuple<DAE.ComponentRef,builtin.SourceInfo> tupleVar)
::=
match tupleVar
case tupleVar as ((cref as CREF_IDENT(identType = T_ARRAY(__)),_)) then
let varName = contextArrayCref(cref,contextParallelFunction)
match cref.identType
case identType as T_ARRAY(ty = T_INTEGER(__)) then
'__global modelica_integer* data_<%varName%>,<%\n%>__global modelica_integer* info_<%varName%>'
case identType as T_ARRAY(ty = T_REAL(__)) then
'__global modelica_real* data_<%varName%>,<%\n%>__global modelica_integer* info_<%varName%>'
else 'Template error in parFunArgDefinitionFromLooptupleVar'
case tupleVar as ((cref as CREF_IDENT(__),_)) then
let varName = contextArrayCref(cref,contextParallelFunction)
match cref.identType
case identType as T_INTEGER(__) then
'modelica_integer <%varName%>'
case identType as T_REAL(__) then
'modelica_real <%varName%>'
else 'Tempalte error in parFunArgDefinitionFromLooptupleVar'
end parFunArgDefinitionFromLooptupleVar;
template reconstructKernelArraysFromLooptupleVars(tuple<DAE.ComponentRef,builtin.SourceInfo> tupleVar, Text &reconstructedArrs)
"reconstructs modelica arrays in the kernels."
::=
match tupleVar
case tupleVar as ((cref as CREF_IDENT(identType = T_ARRAY(__)),_)) then
let varName = contextArrayCref(cref,contextParallelFunction)
match cref.identType
case identType as T_ARRAY(ty = T_INTEGER(__)) then
let &reconstructedArrs += 'integer_array <%varName%>; <%\n%>'
let &reconstructedArrs += '<%varName%>.data = data_<%varName%>; <%\n%>'
let &reconstructedArrs += '<%varName%>.ndims = info_<%varName%>[0]; <%\n%>'
let &reconstructedArrs += '<%varName%>.dim_size = info_<%varName%> + 1; <%\n%>'
""
case identType as T_ARRAY(ty = T_REAL(__)) then
let &reconstructedArrs += 'real_array <%varName%>; <%\n%>'
let &reconstructedArrs += '<%varName%>.data = data_<%varName%>; <%\n%>'
let &reconstructedArrs += '<%varName%>.ndims = info_<%varName%>[0]; <%\n%>'
let &reconstructedArrs += '<%varName%>.dim_size = info_<%varName%> + 1; <%\n%>'
""
else let &reconstructedArrs += '#wiered variable in kerenl reconstruction of arrays<%\n%>' ""
end reconstructKernelArraysFromLooptupleVars;
template reconstructKernelArrays(Variable var, Text &reconstructedArrs)
"reconstructs modelica arrays in the kernels."
::=
let &auxFunction = buffer ""
match var
//function args will have nill instdims even if they are arrays. handled here
case var as VARIABLE(ty=T_ARRAY(__),parallelism=PARGLOBAL(__)) then
let varName = '<%contextCref(var.name,contextParallelFunction,&auxFunction)%>'
let &reconstructedArrs += '<%expTypeShort(var.ty)%>_array <%varName%>; <%\n%>'
let &reconstructedArrs += '<%varName%>.data = data_<%varName%>; <%\n%>'
let &reconstructedArrs += '<%varName%>.ndims = info_<%varName%>[0]; <%\n%>'
let &reconstructedArrs += '<%varName%>.dim_size = info_<%varName%> + 1; <%\n%>'
""
case var as VARIABLE(ty=T_ARRAY(__),parallelism=PARLOCAL(__)) then
let varName = '<%contextCref(var.name,contextParallelFunction,&auxFunction)%>'
let &reconstructedArrs += 'local_<%expTypeShort(var.ty)%>_array <%varName%>; <%\n%>'
let &reconstructedArrs += '<%varName%>.data = data_<%varName%>; <%\n%>'
let &reconstructedArrs += '<%varName%>.ndims = info_<%varName%>[0]; <%\n%>'
let &reconstructedArrs += '<%varName%>.dim_size = info_<%varName%> + 1; <%\n%>'
""
case var as VARIABLE(__) then
let varName = '<%contextCref(var.name,contextParallelFunction,&auxFunction)%>'
if instDims then
let &reconstructedArrs += '<%expTypeShort(var.ty)%>_array <%varName%>; <%\n%>'
let &reconstructedArrs += '<%varName%>.data = data_<%varName%>; <%\n%>'
let &reconstructedArrs += '<%varName%>.ndims = info_<%varName%>[0]; <%\n%>'
let &reconstructedArrs += '<%varName%>.dim_size = info_<%varName%> + 1; <%\n%>'
" "
else
""
else let &reconstructedArrs += '#wiered variable in kerenl reconstruction of arrays<%\n%>' ""
end reconstructKernelArrays;
template funArgBoxedDefinition(Variable var)
"A definition for a boxed variable is always of type modelica_metatype,
unless it's a function pointer"
::=
let &auxFunction = buffer ""
match var
case VARIABLE(__) then 'modelica_metatype <%contextCref(name,contextFunction,&auxFunction)%>'
case FUNCTION_PTR(__) then 'modelica_fnptr _<%name%>'
end funArgBoxedDefinition;
template extFunDef(Function fn)
"Generates function header for an external function."
::=
match fn
case func as EXTERNAL_FUNCTION(__) then
let fn_name = extFunctionName(extName, language)
let fargsStr = extFunDefArgs(extArgs, language)
let fargsStrEscaped = '<%escapeCComments(fargsStr)%>'
let includesStr = includes |> i => i ;separator=", "
/*
* adrpo:
* only declare the external function definition IF THERE WERE NO INCLUDES!
* i did not put includesStr string in the comment below as it might include
* entire files
*/
if includes then
<<
/*
* The function has annotation(Include=...>)
* the external function definition should be present
* in one of these files and have this prototype:
* extern <%extReturnType(extReturn)%> <%fn_name%>(<%fargsStrEscaped%>);
*/
>>
else
<<
extern <%extReturnType(extReturn)%> <%fn_name%>(<%fargsStr%>);
>>
end match
end extFunDef;
template extFunDefDynamic(Function fn)
"Generates function header for an external function."
::=
match fn
case func as EXTERNAL_FUNCTION(__) then
let fn_name = extFunctionName(extName, language)
let fargsStr = extFunDefArgs(extArgs, language)
<<
typedef <%extReturnType(extReturn)%> (*ptrT_<%fn_name%>)(<%fargsStr%>);
extern ptrT_<%fn_name%> ptr_<%fn_name%>;
>>
end extFunDefDynamic;
/* public */ template extFunctionName(String name, String language) "used in Compiler/Template/CodegenFMU.tpl"
::=
match language
case "C" then '<%name%>'
case "FORTRAN 77" then '<%name%>_'
else error(sourceInfo(), 'Unsupport external language: <%language%>')
end extFunctionName;
template extFunDefArgs(list<SimExtArg> args, String language)
::=
match language
case "C" then (args |> arg => extFunDefArg(arg) ;separator=", ")
case "FORTRAN 77" then (args |> arg => extFunDefArgF77(arg) ;separator=", ")
else error(sourceInfo(), 'Unsupport external language: <%language%>')
end extFunDefArgs;
template extReturnType(SimExtArg extArg)
"Generates return type for external function."
::=
match extArg
case ex as SIMEXTARG(__) then extType(type_,true /*Treat this as an input (pass by value)*/,false)
case SIMNOEXTARG(__) then "void"
case SIMEXTARGEXP(__) then error(sourceInfo(), 'Expression types are unsupported as return arguments <%printExpStr(exp)%>')
else error(sourceInfo(), "Unsupported return argument")
end extReturnType;
template extType(Type type, Boolean isInput, Boolean isArray)
"Generates type for external function argument or return value."
::=
let s = match type
case T_INTEGER(__) then "int"
case T_REAL(__) then "double"
case T_STRING(__) then "const char*"
case T_BOOL(__) then "int"
case T_ENUMERATION(__) then "int"
case T_ARRAY(__) then extType(ty,isInput,true)
case T_COMPLEX(complexClassType=EXTERNAL_OBJ(__))
then "void *"
case T_COMPLEX(complexClassType=RECORD(path=rname))
then '<%underscorePath(rname)%>'
case T_METATYPE(__)
case T_METABOXED(__)
then "modelica_metatype"
case T_FUNCTION_REFERENCE_VAR(__)
then "modelica_fnptr"
else error(sourceInfo(), 'Unknown external C type <%unparseType(type)%>')
match type case T_ARRAY(__) then s else if isInput then (if isArray then '<%match s case "const char*" then "" else "const "%><%s%>*' else s) else '<%s%>*'
end extType;
template extTypeF77(Type type, Boolean isReference)
"Generates type for external function argument or return value for F77."
::=
let s = match type
case T_INTEGER(__) then "int"
case T_REAL(__) then "double"
case T_STRING(__) then "char"
case T_BOOL(__) then "int"
case T_ENUMERATION(__) then "int"
case T_ARRAY(__) then extTypeF77(ty, true)
case T_COMPLEX(complexClassType=EXTERNAL_OBJ(__))
then "void*"
case T_COMPLEX(complexClassType=RECORD(path=rname))
then '<%underscorePath(rname)%>'
case T_METATYPE(__) case T_METABOXED(__) then "void*"
else error(sourceInfo(), 'Unknown external F77 type <%unparseType(type)%>')
match type case T_ARRAY(__) then s else if isReference then '<%s%>*' else s
end extTypeF77;
template extFunDefArg(SimExtArg extArg)
"Generates the definition of an external function argument.
Assume that language is C for now."
::=
let &auxFunction = buffer ""
match extArg
case SIMEXTARG(cref=c, isInput=ii, isArray=ia, type_=t) then
let name = contextCref(c,contextFunction,&auxFunction)
let typeStr = extType(t,ii,ia)
<<
<%typeStr%> /*<%name%>*/
>>
case SIMEXTARGEXP(__) then
let typeStr = extType(type_,true,false)
<<
<%typeStr%>
>>
case SIMEXTARGSIZE(cref=c) then
<<
size_t
>>
end extFunDefArg;
template extFunDefArgF77(SimExtArg extArg)
::=
let &auxFunction = buffer ""
match extArg
case SIMEXTARG(cref=c, isInput = isInput, type_=t) then
let name = contextCref(c,contextFunction,&auxFunction)
let typeStr = '<%extTypeF77(t,true)%>'
'<%typeStr%> /*<%name%>*/'
case SIMEXTARGEXP(__) then '<%extTypeF77(type_,true)%>'
/* adpro: 2011-06-23
* DO NOT USE CONST HERE as sometimes is used with size(A, 1)
* sometimes with n in Modelica.Math.Matrices.Lapack and you
* get conflicting external definitions in the same Model_function.h
* file
*/
case SIMEXTARGSIZE(__) then 'int *'
end extFunDefArgF77;
template functionName(Function fn, Boolean dotPath)
::=
match fn
case FUNCTION(__)
case EXTERNAL_FUNCTION(__)
case RECORD_CONSTRUCTOR(__) then if dotPath then dotPath(name) else underscorePath(name)
end functionName;
template functionBodies(list<Function> functions, Boolean isSimulation)
"Generates the body for a set of functions."
::=
(functions |> fn => functionBody(fn, false, isSimulation) ;separator="\n")
end functionBodies;
template functionBodiesParModelica(list<Function> functions)
"Generates the body for a set of functions."
::=
(functions |> fn => functionBodyParModelica(fn, false) ;separator="\n")
end functionBodiesParModelica;
template functionBody(Function fn, Boolean inFunc, Boolean isSimulation)
"Generates the body for a function."
::=
match fn
case fn as FUNCTION(__) then functionBodyRegularFunction(fn, inFunc, isSimulation)
case fn as KERNEL_FUNCTION(__) then functionBodyKernelFunctionInterface(fn, inFunc)
case fn as EXTERNAL_FUNCTION(__) then functionBodyExternalFunction(fn, inFunc, isSimulation)
case fn as RECORD_CONSTRUCTOR(__) then functionBodyRecordConstructor(fn, isSimulation)
end functionBody;
template functionBodyParModelica(Function fn, Boolean inFunc)
"Generates the body for a function."
::=
match fn
case fn as FUNCTION(__) then extractParforBodies(fn, inFunc)
case fn as KERNEL_FUNCTION(__) then functionBodyKernelFunction(fn, inFunc)
case fn as PARALLEL_FUNCTION(__) then functionBodyParallelFunction(fn, inFunc)
end functionBodyParModelica;
template extractParforBodies(Function fn, Boolean inFunc)
"Generates the body for a Modelica/MetaModelica function."
::=
match fn
case FUNCTION(__) then
let()= System.tmpTickResetIndex(0,1) /* Boxed array indices */
let &varDecls = buffer ""
let &auxFunction = buffer ""
let bodyPart = extractParFors(body, &varDecls, &auxFunction)
<<
<%auxFunction%>
<%bodyPart%>
>>
end extractParforBodies;
template functionBodyRegularFunction(Function fn, Boolean inFunc, Boolean isSimulation)
"Generates the body for a Modelica/MetaModelica function."
::=
match fn
case FUNCTION(__) then
let()= codegenResetTryThrowIndex()
let()= System.tmpTickReset(1)
let()= System.tmpTickResetIndex(0,1) /* Boxed array indices */
let fname = underscorePath(name)
let &varDecls = buffer ""
let &varInits = buffer ""
let &varFrees = buffer ""
let &auxFunction = buffer ""
let restoreJmpbuf = (if statementsContainReturn(body) then
(if statementsContainTryBlock(body) then
let &varDecls += 'jmp_buf *old_mmc_jumper = threadData->mmc_jumper;<%\n%>'
'threadData->mmc_jumper = old_mmc_jumper;<%\n%>'))
let _ = (variableDeclarations |> var hasindex i1 fromindex 1 =>
varInit(var, "", &varDecls, &varInits, &varFrees, &auxFunction) ; empty /* increase the counter! */
)
let bodyPart = funStatement(body, &varDecls, &auxFunction)
let outVarAssign = (List.restOrEmpty(outVars) |> var => varOutput(var))
let freeConstructedExternalObjects = (variableDeclarations |> var as VARIABLE(ty=T_COMPLEX(complexClassType=EXTERNAL_OBJ(path=path_ext))) => 'omc_<%underscorePath(path_ext)%>_destructor(threadData,<%contextCref(var.name,contextFunction,&auxFunction)%>);'; separator = "\n")
/* Needs to be done last as it messes with the tmp ticks :) */
let &varDecls += addRootsTempArray()
let boxedFn = if not funcHasParallelInOutArrays(fn) then functionBodyBoxed(fn, isSimulation) else ""
<<
<%auxFunction%>
<% match visibility case PUBLIC(__) then "DLLExport" %>
<%functionPrototype(fname, functionArguments, outVars, false, visibility, isSimulation)%>
{
<%varDecls%>
<% if boolNot(isSimulation) then 'MMC_SO();<%\n%>'%>_tailrecursive: OMC_LABEL_UNUSED
<%varInits%>
<%bodyPart%>
_return: OMC_LABEL_UNUSED
<%outVarAssign%><%restoreJmpbuf%>
<%if acceptParModelicaGrammar() then
'/* Free GPU/OpenCL CPU memory */<%\n%><%varFrees%>'%>
<%freeConstructedExternalObjects%>
<%match outVars
case {} then 'return;'
case v::_ then 'return <%funArgName(v)%>;'
%>
}
<% if inFunc then generateInFunc(fname,functionArguments,outVars) %>
<%boxedFn%>
>>
end functionBodyRegularFunction;