/
CodegenCppHpcom.tpl
1644 lines (1465 loc) · 66.3 KB
/
CodegenCppHpcom.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 template-extensions for transforming Modelica code into parallel hpcom-code.
//
// There are one root template intended to be called from the code generator:
// translateModel. These template 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 CodegenCppHpcom
import interface SimCodeTV;
import CodegenUtil.*;
import CodegenCpp.*; //unqualified import, no need the CodegenC is optional when calling a template; or mandatory when the same named template exists in this package (name hiding)
template translateModel(SimCode simCode) ::=
match simCode
case SIMCODE(modelInfo = MODELINFO(__), makefileParams= MAKEFILE_PARAMS(__)) then
let target = simulationCodeTarget()
let()= textFile((if Flags.isSet(Flags.HPCOM_ANALYZATION_MODE) then simulationMainFileAnalyzation(simCode) else simulationMainFile(simCode)), 'OMCpp<%fileNamePrefix%>Main.cpp')
let()= textFile(simulationHeaderFile(simCode, Util.isSome(hpcOmMemory)), 'OMCpp<%fileNamePrefix%>.h')
let()= textFile(simulationCppFile(simCode,Util.isSome(hpcOmMemory)), 'OMCpp<%fileNamePrefix%>.cpp')
let()= textFile(simulationFunctionsHeaderFile(simCode,modelInfo.functions,literals,false), 'OMCpp<%fileNamePrefix%>Functions.h')
let()= textFile(simulationFunctionsFile(simCode, modelInfo.functions,literals,externalFunctionIncludes,false), 'OMCpp<%fileNamePrefix%>Functions.cpp')
let()= textFile(simulationTypesHeaderFile(simCode,modelInfo.functions,literals), 'OMCpp<%fileNamePrefix%>Types.h')
let()= textFile(simulationMakefile(target,simCode), '<%fileNamePrefix%>.makefile')
let()= textFile(simulationInitHeaderFile(simCode), 'OMCpp<%fileNamePrefix%>Initialize.h')
let()= textFile(simulationInitCppFile(simCode,Util.isSome(hpcOmMemory)),'OMCpp<%fileNamePrefix%>Initialize.cpp')
let()= textFile(simulationJacobianHeaderFile(simCode), 'OMCpp<%fileNamePrefix%>Jacobian.h')
let()= textFile(simulationJacobianCppFile(simCode,Util.isSome(hpcOmMemory)),'OMCpp<%fileNamePrefix%>Jacobian.cpp')
let()= textFile(simulationStateSelectionCppFile(simCode,Util.isSome(hpcOmMemory)), 'OMCpp<%fileNamePrefix%>StateSelection.cpp')
let()= textFile(simulationStateSelectionHeaderFile(simCode),'OMCpp<%fileNamePrefix%>StateSelection.h')
let()= textFile(simulationExtensionHeaderFile(simCode),'OMCpp<%fileNamePrefix%>Extension.h')
let()= textFile(simulationExtensionCppFile(simCode),'OMCpp<%fileNamePrefix%>Extension.cpp')
let()= textFile(simulationWriteOutputHeaderFile(simCode),'OMCpp<%fileNamePrefix%>WriteOutput.h')
let()= textFile(simulationWriteOutputCppFile(simCode,Util.isSome(hpcOmMemory)),'OMCpp<%fileNamePrefix%>WriteOutput.cpp')
let()= textFile(simulationFactoryFile(simCode),'OMCpp<%fileNamePrefix%>FactoryExport.cpp')
let()= textFile(simulationMainRunScript(simCode), '<%fileNamePrefix%><%simulationMainRunScriptSuffix(simCode)%>')
let jac = (jacobianMatrixes |> (mat, _,_, _, _, _,_) =>
(mat |> (eqs,_,_) => algloopfiles(eqs,simCode,contextAlgloopJacobian,Util.isSome(hpcOmMemory)) ;separator="")
;separator="")
let alg = algloopfiles(listAppend(allEquations,initialEquations),simCode,contextAlgloop,Util.isSome(hpcOmMemory))
let()= textFile(algloopMainfile(listAppend(allEquations,initialEquations),simCode,contextAlgloop), 'OMCpp<%fileNamePrefix%>AlgLoopMain.cpp')
let()= textFile(calcHelperMainfile(simCode), 'OMCpp<%fileNamePrefix%>CalcHelperMain.cpp')
""
// empty result of the top-level template .., only side effects
end translateModel;
template Update(SimCode simCode, Boolean useFlatArrayNotation)
::=
match simCode
case SIMCODE(__) then
<<
<%update(allEquations,whenClauses,simCode,contextOther,useFlatArrayNotation)%>
>>
end Update;
// HEADER
template simulationHeaderFile(SimCode simCode, Boolean useFlatArrayNotation)
"Generates code for header file for simulation target."
::=
match simCode
case SIMCODE(__) then
<<
<%generateHeaderIncludeString(simCode)%>
#ifdef ANALYZATION_MODE
#include <boost/shared_ptr.hpp>
#include <boost/weak_ptr.hpp>
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <string>
#include <vector>
#include <map>
using std::string;
using std::vector;
using std::map;
#include <SimCoreFactory/Policies/FactoryConfig.h>
#include <SimController/ISimController.h>
#include <System/IMixedSystem.h>
#include <boost/numeric/ublas/matrix_sparse.hpp>
typedef uBlas::compressed_matrix<double, uBlas::column_major, 0, uBlas::unbounded_array<int>, uBlas::unbounded_array<double> > SparseMatrix;
#endif
<%generateHpcomSpecificIncludes(simCode)%>
<%generateClassDeclarationCode(simCode, useFlatArrayNotation)%>
#ifdef MEASURE_PAPI
#include <papi.h>
#define NUM_EVENTS 1
#endif
>>
end simulationHeaderFile;
template generateClassDeclarationCode(SimCode simCode, Boolean useFlatArrayNotation)
"Generates class declarations."
::=
match simCode
case SIMCODE(modelInfo = MODELINFO(__)) then
let addHpcomFunctionHeaders = getAddHpcomFunctionHeaders(hpcOmSchedule)
let addHpcomVarHeaders = getAddHpcomVarHeaders(hpcOmSchedule)
let addHpcomArrayHeaders = getAddHpcomVarArrays(hpcOmMemory)
<<
class <%lastIdentOfPath(modelInfo.name)%>: public IContinuous, public IEvent, public ITime, public ISystemProperties <%if Flags.isSet(Flags.WRITE_TO_BUFFER) then ', public IReduceDAE'%>, public SystemDefaultImplementation
{
<%generatefriendAlgloops(listAppend(allEquations,initialEquations),simCode)%>
public:
<%lastIdentOfPath(modelInfo.name)%>(IGlobalSettings* globalSettings,boost::shared_ptr<IAlgLoopSolverFactory> nonlinsolverfactor,boost::shared_ptr<ISimData>);
virtual ~<%lastIdentOfPath(modelInfo.name)%>();
<%generateMethodDeclarationCode(simCode)%>
virtual bool getCondition(unsigned int index);
virtual void initPreVars(unordered_map<string,unsigned int>&,unordered_map<string,unsigned int>&);
protected:
//Methods:
<%addHpcomFunctionHeaders%>
bool isConsistent();
//Called to handle all events occured at same time
bool handleSystemEvents( bool* events);
//Saves all variables before an event is handled, is needed for the pre, edge and change operator
void saveAll();
void getJacobian(SparseMatrix& matrix);
//Variables:
#ifdef __GNUC__
#define VARARRAY_ALIGN_PRE
#define VARARRAY_ALIGN_POST __attribute__((aligned(0x40)))
#else
#define VARARRAY_ALIGN_PRE __declspec(align(64))
#define VARARRAY_ALIGN_POST
#endif
<%addHpcomArrayHeaders%>
<%addHpcomVarHeaders%>
EventHandling _event_handling;
/* <%CodegenCpp.MemberVariable(modelInfo,useFlatArrayNotation)%> */
<%MemberVariable(modelInfo, hpcOmMemory,useFlatArrayNotation,false)%>
<%conditionvariable(zeroCrossings,simCode)%>
Functions* _functions;
boost::shared_ptr<IAlgLoopSolverFactory>
_algLoopSolverFactory; ///< Factory that provides an appropriate solver
<%generateAlgloopsolverVariables(listAppend(allEquations,initialEquations),simCode)%>
boost::shared_ptr<ISimData> _simData;
<%generateEquationMemberFuncDecls(allEquations)%>
/*! Equations Array. pointers to all the equation functions listed above stored in this
array. It is used to randomly access and evaluate a single equation by index.
*/
typedef void (<%lastIdentOfPath(modelInfo.name)%>::*EquFuncPtr)();
boost::array< EquFuncPtr, <%listLength(allEquations)%> > equations_array;
void initialize_equations_array();
};
>>
end generateClassDeclarationCode;
template getAddHpcomStructHeaders(Option<Schedule> hpcOmScheduleOpt)
::=
let type = getConfigString(HPCOM_CODE)
match hpcOmScheduleOpt
case SOME(hpcOmSchedule as TASKDEPSCHEDULE(__)) then
match type
case ("openmp") then
<<
>>
case ("tbb") then
<<
struct VoidBody {
boost::function<void(void)> void_function;
VoidBody(boost::function<void(void)> void_function) : void_function(void_function) { }
void operator()( tbb::flow::continue_msg ) const
{
void_function();
}
};
>>
else ""
else ""
end getAddHpcomStructHeaders;
template getAddHpcomFunctionHeaders(Option<Schedule> hpcOmScheduleOpt)
::=
let type = getConfigString(HPCOM_CODE)
match hpcOmScheduleOpt
case SOME(hpcOmSchedule as LEVELSCHEDULE(__)) then
match type
case ("mixed") then
<<
void evaluateThreadFunc0();
>>
else ""
case SOME(hpcOmSchedule as THREADSCHEDULE(__)) then
let locks = hpcOmSchedule.lockIdc |> idx => function_HPCOM_createLock(idx, "lock", type); separator="\n"
match type
case ("openmp") then
<<
>>
else
let headers = arrayList(hpcOmSchedule.threadTasks) |> tt hasindex i0 fromindex 0 => generateThreadFunctionHeaderDecl(i0); separator="\n"
<<
<%headers%>
>>
case SOME(hpcOmSchedule as TASKDEPSCHEDULE(__)) then
match type
case ("openmp") then
<<
>>
case ("tbb") then
let voidfuncs = hpcOmSchedule.tasks |> task => getAddHpcomFuncHeadersTaskDep(task); separator="\n"
<<
<%getAddHpcomStructHeaders(hpcOmScheduleOpt)%>
<%voidfuncs%>
>>
else ""
else ""
end getAddHpcomFunctionHeaders;
template getAddHpcomVarArrays(Option<MemoryMap> optHpcomMemoryMap)
::=
match optHpcomMemoryMap
case(SOME(hpcomMemoryMap)) then
match hpcomMemoryMap
case(MEMORYMAP_ARRAY(__)) then
<<
<%if intGt(floatArraySize,0) then 'VARARRAY_ALIGN_PRE double varArray1[<%floatArraySize%>] VARARRAY_ALIGN_POST ; //float variables'%>
>>
else ''
end match
else ''
end match
end getAddHpcomVarArrays;
template getAddHpcomVarHeaders(Option<Schedule> hpcOmScheduleOpt)
::=
let type = getConfigString(HPCOM_CODE)
match hpcOmScheduleOpt
case SOME(hpcOmSchedule as LEVELSCHEDULE(__)) then
match type
case ("mixed") then
<<
<%generateThreadHeaderDecl(0, "pthreads")%>
<%function_HPCOM_createLock("startEvaluateLock","","pthreads")%>
<%function_HPCOM_createLock("finishedEvaluateLock","","pthreads")%>
bool finished;
UPDATETYPE command;
>>
else ""
case SOME(hpcOmSchedule as THREADSCHEDULE(__)) then
let locks = hpcOmSchedule.lockIdc |> idx => function_HPCOM_createLock(idx, "lock", type); separator="\n"
let threadDecl = arrayList(hpcOmSchedule.threadTasks) |> tt hasindex i0 fromindex 0 => generateThreadHeaderDecl(i0, type); separator="\n"
match type
case ("openmp") then
<<
<%locks%>
<%threadDecl%>
>>
else
let thLocks = arrayList(hpcOmSchedule.threadTasks) |> tt hasindex i0 fromindex 0 => function_HPCOM_createLock(i0, "th_lock", type); separator="\n"
let thLocks1 = arrayList(hpcOmSchedule.threadTasks) |> tt hasindex i0 fromindex 0 => function_HPCOM_createLock(i0, "th_lock1", type); separator="\n"
<<
bool terminateThreads;
UPDATETYPE command;
<%locks%>
<%thLocks%>
<%thLocks1%>
<%threadDecl%>
>>
case SOME(hpcOmSchedule as TASKDEPSCHEDULE(__)) then
match type
case ("openmp") then
<<
>>
case ("tbb") then
<<
tbb::flow::graph tbb_graph;
>>
else ""
else ""
end getAddHpcomVarHeaders;
template getAddHpcomFuncHeadersTaskDep(tuple<Task,list<Integer>> taskIn)
::=
match taskIn
case ((task as CALCTASK(__),parents)) then
<<
void task_func_<%task.index%>();
>>
end getAddHpcomFuncHeadersTaskDep;
template generateHpcomSpecificIncludes(SimCode simCode)
::=
let type = getConfigString(HPCOM_CODE)
match type
case ("openmp") then
<<
#include <omp.h>
>>
case ("mixed") then
<<
#define NUM_EVENTS 1
#include <boost/thread/mutex.hpp>
#include <boost/thread.hpp>
>>
case ("pthreads_spin") then
<<
#include <boost/smart_ptr/detail/spinlock.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread.hpp>
>>
case ("tbb") then
<<
#include <tbb/tbb.h>
#include <tbb/flow_graph.h>
#include <boost/function.hpp>
#include <boost/bind.hpp>
>>
else
<<
#include <boost/thread/mutex.hpp>
#include <boost/thread.hpp>
>>
end generateHpcomSpecificIncludes;
template generateThreadHeaderDecl(Integer threadIdx, String iType)
::=
match iType
case ("openmp") then
<<
>>
else
<<
boost::thread* evaluateThread<%threadIdx%>;
>>
end generateThreadHeaderDecl;
template generateThreadFunctionHeaderDecl(Integer threadIdx)
::=
<<
void evaluateThreadFunc<%threadIdx%>();
>>
end generateThreadFunctionHeaderDecl;
template MemberVariable(ModelInfo modelInfo, Option<MemoryMap> hpcOmMemory, Boolean useFlatArrayNotation, Boolean createConstructorDeclaration)
"Define membervariable in simulation file."
::=
match modelInfo
case MODELINFO(vars=SIMVARS(__)) then
<<
<%vars.algVars |> var =>
MemberVariableDefine2(var, "algebraics", hpcOmMemory,useFlatArrayNotation, createConstructorDeclaration)
;separator="\n"%>
<%vars.discreteAlgVars |> var =>
MemberVariableDefine2(var, "algebraics", hpcOmMemory,useFlatArrayNotation, createConstructorDeclaration)
;separator="\n"%>
<%vars.paramVars |> var =>
MemberVariableDefine2(var, "parameters", hpcOmMemory,useFlatArrayNotation, createConstructorDeclaration)
;separator="\n"%>
<%vars.aliasVars |> var =>
MemberVariableDefine2(var, "aliasVars", hpcOmMemory,useFlatArrayNotation, createConstructorDeclaration)
;separator="\n"%>
<%vars.intAlgVars |> var =>
MemberVariableDefine("int", var, "intVariables.algebraics",hpcOmMemory,useFlatArrayNotation, createConstructorDeclaration)
;separator="\n"%>
<%vars.intParamVars |> var =>
MemberVariableDefine("int", var, "intVariables.parameters",hpcOmMemory,useFlatArrayNotation, createConstructorDeclaration)
;separator="\n"%>
<%vars.intAliasVars |> var =>
MemberVariableDefine("int", var, "intVariables.AliasVars",hpcOmMemory,useFlatArrayNotation, createConstructorDeclaration)
;separator="\n"%>
<%vars.boolAlgVars |> var =>
MemberVariableDefine("bool",var, "boolVariables.algebraics",hpcOmMemory,useFlatArrayNotation, createConstructorDeclaration)
;separator="\n"%>
<%vars.boolParamVars |> var =>
MemberVariableDefine("bool",var, "boolVariables.parameters",hpcOmMemory,useFlatArrayNotation, createConstructorDeclaration)
;separator="\n"%>
<%vars.boolAliasVars |> var =>
MemberVariableDefine("bool ",var, "boolVariables.AliasVars",hpcOmMemory,useFlatArrayNotation, createConstructorDeclaration)
;separator="\n"%>
<%vars.stringAlgVars |> var =>
MemberVariableDefine("string",var, "stringVariables.algebraics",hpcOmMemory,useFlatArrayNotation, createConstructorDeclaration)
;separator="\n"%>
<%vars.stringParamVars |> var =>
MemberVariableDefine("string",var, "stringVariables.parameters",hpcOmMemory,useFlatArrayNotation, createConstructorDeclaration)
;separator="\n"%>
<%vars.stringAliasVars |> var =>
MemberVariableDefine("string",var, "stringVariables.AliasVars",hpcOmMemory,useFlatArrayNotation, createConstructorDeclaration)
;separator="\n"%>
<%vars.constVars |> var =>
MemberVariableDefine2(var, "constvariables", hpcOmMemory,useFlatArrayNotation, createConstructorDeclaration)
;separator="\n"%>
<%vars.intConstVars |> var =>
MemberVariableDefine("const int", var, "intConstvariables",hpcOmMemory,useFlatArrayNotation, createConstructorDeclaration)
;separator="\n"%>
<%vars.boolConstVars |> var =>
MemberVariableDefine("const bool", var, "boolConstvariables",hpcOmMemory,useFlatArrayNotation, createConstructorDeclaration)
;separator="\n"%>
<%vars.stringConstVars |> var =>
MemberVariableDefine("const string",var, "stringConstvariables",hpcOmMemory,useFlatArrayNotation, createConstructorDeclaration)
;separator="\n"%>
<%vars.extObjVars |> var =>
MemberVariableDefine("void*",var, "extObjVars",hpcOmMemory, useFlatArrayNotation, createConstructorDeclaration)
;separator="\n"%>
>>
end MemberVariable;
template MemberVariableDefine(String type,SimVar simVar, String arrayName, Option<MemoryMap> hpcOmMemoryOpt, Boolean useFlatArrayNotation, Boolean createConstructorDeclaration)
::=
match simVar
case SIMVAR(numArrayElement={},arrayCref=NONE(),name=CREF_IDENT(subscriptLst=_::_)) then ''
case SIMVAR(name=varName,numArrayElement={},arrayCref=NONE()) then
match(hpcOmMemoryOpt)
case SOME(hpcOmMemory) then
<<
// case 2 MemberVariableDefine
<%MemberVariableDefine3(HpcOmMemory.getPositionMappingByArrayName(hpcOmMemory,varName), simVar, useFlatArrayNotation, createConstructorDeclaration)%>
>>
else
<<
<%if createConstructorDeclaration then '' else '<%variableType(simVar.type_)%> <%cref(simVar.name,useFlatArrayNotation)%>; //no cacheMap defined'%>
>>
end match
case v as SIMVAR(name=CREF_IDENT(__),arrayCref=SOME(_),numArrayElement=num) then
let &dims = buffer "" /*BUFD*/
let arrayName = arraycref2(name,dims)
<<
multi_array<<%variableType(type_)%>,<%dims%>> <%arrayName%>;
>>
case v as SIMVAR(name=CREF_QUAL(__),arrayCref=SOME(arrayCrefLocal),numArrayElement=num,type_=varType) then
let &dims = buffer "" /*BUFD*/
let arrayName = arraycref2(name,dims)
match(hpcOmMemoryOpt)
case SOME(hpcOmMemory) then
let varDeclarations = HpcOmMemory.expandCref(arrayCrefLocal,num) |> crefLocal => MemberVariableDefine4(HpcOmMemory.getPositionMappingByArrayName(hpcOmMemory,crefLocal), crefLocal, varType, useFlatArrayNotation, createConstructorDeclaration); separator="\n"
<<
// case 3 MemberVariableDefine <%num%> * <%dims%> [<%listLength(HpcOmMemory.expandCref(arrayCrefLocal,num))%>]
<%varDeclarations%>
>>
else
<<
<%if createConstructorDeclaration then '' else 'multi_array<<%variableType(v.type_)%>,<%dims%>> <%arrayName%>; //no cacheMap defined' %>
>>
end match
case SIMVAR(numArrayElement=_::_) then
let& dims = buffer "" /*BUFD*/
let varName = arraycref2(name,dims)
let varType = variableType(type_)
match dims
case "0" then if createConstructorDeclaration then '' else '<%varType%> <%varName%>;'
else ''
end match
end MemberVariableDefine;
template MemberVariableDefine2(SimVar simVar, String arrayName, Option<MemoryMap> hpcOmMemoryOpt, Boolean useFlatArrayNotation, Boolean createConstructorDeclaration)
::=
match simVar
case SIMVAR(numArrayElement={},arrayCref=NONE(),name=CREF_IDENT(subscriptLst=_::_)) then ''
case SIMVAR(name=varName,numArrayElement={},arrayCref=NONE()) then
match(hpcOmMemoryOpt)
case SOME(hpcOmMemory) then
<<
<%if createConstructorDeclaration then '' else MemberVariableDefine3(HpcOmMemory.getPositionMappingByArrayName(hpcOmMemory,varName), simVar, useFlatArrayNotation, createConstructorDeclaration)%>
>>
else
<<
<%if createConstructorDeclaration then '' else '<%variableType(simVar.type_)%> <%cref(simVar.name,useFlatArrayNotation)%>; //no cacheMap defined'%>
>>
end match
case v as SIMVAR(name=CREF_IDENT(__),arrayCref=SOME(arrayCrefLocal),numArrayElement=num,type_=varType) then
let &dims = buffer "" /*BUFD*/
let arrayName = arraycref2(name,dims)
match(hpcOmMemoryOpt)
case SOME(hpcOmMemory) then
let varDeclarations = HpcOmMemory.expandCref(arrayCrefLocal,num) |> crefLocal => MemberVariableDefine4(HpcOmMemory.getPositionMappingByArrayName(hpcOmMemory,crefLocal), crefLocal, varType, useFlatArrayNotation, createConstructorDeclaration); separator="\n"
<<
// case 2 MemberVariableDefine2
<%varDeclarations%>
>>
else
<<
<%if createConstructorDeclaration then '' else 'multi_array<<%variableType(v.type_)%>,<%dims%>> <%arrayName%>; //no cacheMap defined' %>
>>
end match
case v as SIMVAR(name=CREF_QUAL(__),arrayCref=SOME(arrayCrefLocal),numArrayElement=num,type_=varType) then
let &dims = buffer "" /*BUFD*/
let arrayName = arraycref2(name,dims)
match(hpcOmMemoryOpt)
case SOME(hpcOmMemory) then
let varDeclarations = HpcOmMemory.expandCref(name,num) |> crefLocal => MemberVariableDefine4(HpcOmMemory.getPositionMappingByArrayName(hpcOmMemory,crefLocal), crefLocal, varType, useFlatArrayNotation, createConstructorDeclaration); separator="\n"
<<
// case 3 MemberVariableDefine2 dims:<%dims%>
<%varDeclarations%>
>>
else
<<
<%if createConstructorDeclaration then '' else 'multi_array<<%variableType(v.type_)%>,<%dims%>> <%arrayName%>; //no cacheMap defined' %>
>>
end match
/*special case for varibales that marked as array but are not arrays */
case SIMVAR(numArrayElement=_::_) then
let& dims = buffer "" /*BUFD*/
let varName = arraycref2(name,dims)
let varType = variableType(type_)
match dims
case "0" then (if createConstructorDeclaration then '' else '<%varType%> <%varName%>;')
else ''
end match
end MemberVariableDefine2;
template MemberVariableDefine3(Option<tuple<Integer,Integer>> optVarArrayAssignment, SimVar simVar, Boolean useFlatArrayNotation, Boolean createConstructorDeclaration)
::=
match optVarArrayAssignment
case SOME((varIdx, arrayIdx))
then
match simVar
case SIMVAR(__) then
<<
<%if createConstructorDeclaration then ',<%cref(name, useFlatArrayNotation)%>(varArray<%arrayIdx%>[<%varIdx%>])'
else '<%variableType(type_)%>& <%cref(name, useFlatArrayNotation)%>;// = varArray<%arrayIdx%>[<%varIdx%>]' %>
>>
end match
else
match simVar
case SIMVAR(__) then
<<
<%if createConstructorDeclaration then '' else '<%variableType(type_)%> <%cref(name, useFlatArrayNotation)%>; //not optimized' %>
>>
end match
end match
end MemberVariableDefine3;
template MemberVariableDefine4(Option<tuple<Integer,Integer>> optVarArrayAssignment, DAE.ComponentRef varName, DAE.Type type_, Boolean useFlatArrayNotation, Boolean createConstructorDeclaration)
::=
match optVarArrayAssignment
case SOME((varIdx, arrayIdx)) then
<<
<%if createConstructorDeclaration then ',<%cref(varName,useFlatArrayNotation)%>(varArray<%arrayIdx%>[<%varIdx%>])'
else '<%variableType(type_)%>& <%cref(varName,useFlatArrayNotation)%>;// = varArray<%arrayIdx%>[<%varIdx%>];' %>
>>
else
<<
<%if createConstructorDeclaration then '' else '<%variableType(type_)%> <%cref(varName,useFlatArrayNotation)%>;'%>
>>
end match
end MemberVariableDefine4;
// CODE
template simulationCppFile(SimCode simCode, Boolean useFlatArrayNotation)
"Generates code for main cpp file for simulation target."
::=
match simCode
case SIMCODE(modelInfo = MODELINFO(__)) then
let hpcomConstructorExtension = getHpcomConstructorExtension(hpcOmSchedule, lastIdentOfPath(modelInfo.name))
let hpcomDestructorExtension = getHpcomDestructorExtension(hpcOmSchedule)
let memoryExtension = MemberVariableAssign(modelInfo, hpcOmMemory, useFlatArrayNotation)
let className = lastIdentOfPath(modelInfo.name)
<<
#include "Modelica.h"
#include "ModelicaDefine.h"
#include "OMCpp<%fileNamePrefix%>.h"
#include "OMCpp<%fileNamePrefix%>Functions.h"
/* Constructor */
<%className%>::<%className%>(IGlobalSettings* globalSettings,boost::shared_ptr<IAlgLoopSolverFactory> nonlinsolverfactory,boost::shared_ptr<ISimData> simData)
:SystemDefaultImplementation(globalSettings)
,_algLoopSolverFactory(nonlinsolverfactory)
,_simData(simData)
<%MemberVariable(modelInfo, hpcOmMemory,useFlatArrayNotation,true)%>
<%simulationInitFile(simCode, useFlatArrayNotation)%>
{
//I don't know why this line is necessary if we link statically, but without it a segfault occurs
_global_settings = globalSettings;
//Number of equations
<%dimension1(simCode)%>
_dimZeroFunc= <%zerocrosslength(simCode)%>;
_dimTimeEvent = <%timeeventlength(simCode)%>;
//Number of residues
<%if Flags.isSet(Flags.WRITE_TO_BUFFER) then
<<
_dimResidues=<%numResidues(allEquations)%>;
>>
%>
//DAE's are not supported yet, Index reduction is enabled
_dimAE = 0; // algebraic equations
//Initialize the state vector
SystemDefaultImplementation::initialize();
//Instantiate auxiliary object for event handling functionality
_event_handling.getCondition = boost::bind(&<%className%>::getCondition, this, _1);
<%arrayReindex(modelInfo,useFlatArrayNotation)%>
//Initialize array elements
<%initializeArrayElements(simCode,useFlatArrayNotation)%>
_functions = new Functions(_simTime);
/*Initialize the equations array. Point to each equation function*/
initialize_equations_array();
<%hpcomConstructorExtension%>
}
<%lastIdentOfPath(modelInfo.name)%>::~<%lastIdentOfPath(modelInfo.name)%>()
{
if(_functions != NULL)
delete _functions;
<%hpcomDestructorExtension%>
}
<%InitializeEquationsArray(allEquations, className)%>
<%Update(simCode,useFlatArrayNotation)%>
<%DefaultImplementationCode(simCode,useFlatArrayNotation)%>
<%checkForDiscreteEvents(discreteModelVars,simCode,useFlatArrayNotation)%>
<%giveZeroFunc1(zeroCrossings,simCode,useFlatArrayNotation)%>
<%setConditions(simCode)%>
<%geConditions(simCode)%>
<%isConsistent(simCode)%>
<%generateStepCompleted(listAppend(allEquations,initialEquations),simCode,useFlatArrayNotation)%>
<%generatehandleTimeEvent(timeEvents, simCode)%>
<%generateDimTimeEvent(listAppend(allEquations,initialEquations),simCode)%>
<%generateTimeEvent(timeEvents, simCode, false)%>
<%isODE(simCode)%>
<%DimZeroFunc(simCode)%>
<%getCondition(zeroCrossings,whenClauses,simCode,useFlatArrayNotation)%>
<%handleSystemEvents(zeroCrossings,whenClauses,simCode)%>
<%saveall(modelInfo,simCode,useFlatArrayNotation)%>
<%initPrevars(modelInfo,simCode,useFlatArrayNotation)%>
<%savediscreteVars(modelInfo,simCode,useFlatArrayNotation)%>
<%LabeledDAE(modelInfo.labels,simCode,useFlatArrayNotation)%>
<%giveVariables(modelInfo,useFlatArrayNotation)%>
>>
end simulationCppFile;
template getHpcomConstructorExtension(Option<Schedule> hpcOmScheduleOpt, String modelNamePrefixStr)
::=
let type = getConfigString(HPCOM_CODE)
match hpcOmScheduleOpt
case SOME(hpcOmSchedule as LEVELSCHEDULE(__)) then
match type
case ("mixed") then
<<
command = IContinuous::UNDEF_UPDATE;
finished = false;
<%function_HPCOM_initializeLock("startEvaluateLock","","pthreads")%>
<%function_HPCOM_initializeLock("finishedEvaluateLock","","pthreads")%>
<%function_HPCOM_assignLock("startEvaluateLock","","pthreads")%>
<%function_HPCOM_assignLock("finishedEvaluateLock","","pthreads")%>
>>
else ""
case SOME(hpcOmSchedule as THREADSCHEDULE(__)) then
let initlocks = hpcOmSchedule.lockIdc |> idx => function_HPCOM_initializeLock(idx, "lock", type); separator="\n"
let assignLocks = hpcOmSchedule.lockIdc |> idx => function_HPCOM_assignLock(idx, "lock", type); separator="\n"
let threadFuncs = arrayList(hpcOmSchedule.threadTasks) |> tt hasindex i0 fromindex 0 => generateThread(i0, type, modelNamePrefixStr,"evaluateThreadFunc"); separator="\n"
match type
case ("openmp") then
<<
<%threadFuncs%>
<%initlocks%>
<%assignLocks%>
>>
else
let threadLocksInit = arrayList(hpcOmSchedule.threadTasks) |> tt hasindex i0 fromindex 0 => function_HPCOM_initializeLock(i0, "th_lock", type); separator="\n"
let threadLocksInit1 = arrayList(hpcOmSchedule.threadTasks) |> tt hasindex i0 fromindex 0 => function_HPCOM_initializeLock(i0, "th_lock1", type); separator="\n"
let threadAssignLocks = arrayList(hpcOmSchedule.threadTasks) |> tt hasindex i0 fromindex 0 => function_HPCOM_assignLock(i0, "th_lock", type); separator="\n"
let threadAssignLocks1 = arrayList(hpcOmSchedule.threadTasks) |> tt hasindex i0 fromindex 0 => function_HPCOM_assignLock(i0, "th_lock1", type); separator="\n"
<<
terminateThreads = false;
command = IContinuous::UNDEF_UPDATE;
<%initlocks%>
<%threadLocksInit%>
<%threadLocksInit1%>
<%assignLocks%>
<%threadAssignLocks%>
<%threadAssignLocks1%>
<%threadFuncs%>
>>
else ""
end getHpcomConstructorExtension;
template MemberVariableAssign(ModelInfo modelInfo, Option<MemoryMap> hpcOmMemory, Boolean useFlatArrayNotation)
"Define membervariable in simulation file."
::=
match modelInfo
case MODELINFO(vars=SIMVARS(__)) then
<<
<%vars.algVars |> var =>
MemberVariableAssign2(var, "algebraics", hpcOmMemory, useFlatArrayNotation)
;separator="\n"%>
<%vars.discreteAlgVars |> var =>
MemberVariableAssign2(var, "algebraics", hpcOmMemory, useFlatArrayNotation)
;separator="\n"%>
<%vars.paramVars |> var =>
MemberVariableAssign2(var, "parameters", hpcOmMemory, useFlatArrayNotation)
;separator="\n"%>
<%vars.aliasVars |> var =>
MemberVariableAssign2(var, "aliasVars", hpcOmMemory, useFlatArrayNotation)
;separator="\n"%>
>>
end MemberVariableAssign;
template MemberVariableAssign2(SimVar simVar, String arrayName, Option<MemoryMap> hpcOmMemoryOpt, Boolean useFlatArrayNotation)
::=
match simVar
case SIMVAR(numArrayElement={},arrayCref=NONE(),name=varName) then
match(hpcOmMemoryOpt)
case SOME(hpcOmMemory) then
<<
<%MemberVariableAssign3(HpcOmMemory.getPositionMappingByArrayName(hpcOmMemory,varName), simVar, useFlatArrayNotation)%>
>>
end match
end MemberVariableAssign2;
template MemberVariableAssign3(Option<tuple<Integer,Integer>> optVarArrayAssignment, SimVar simVar, Boolean useFlatArrayNotation)
::=
match optVarArrayAssignment
case SOME((varIdx, arrayIdx))
then
match simVar
case SIMVAR(__) then
<<
,<%cref(name,useFlatArrayNotation)%> (varArray<%arrayIdx%>[<%varIdx%>])
>>
end match
end match
end MemberVariableAssign3;
template getHpcomDestructorExtension(Option<Schedule> hpcOmScheduleOpt)
::=
let type = getConfigString(HPCOM_CODE)
match hpcOmScheduleOpt
case SOME(hpcOmSchedule as LEVELSCHEDULE(__)) then
match type
case ("mixed") then
<<
finished = true;
<%function_HPCOM_releaseLock("startEvaluateLock","","pthreads")%>
<%function_HPCOM_assignLock("finishedEvaluateLock","","pthreads")%>
<%function_HPCOM_destroyLock("startEvaluateLock","","pthreads")%>
<%function_HPCOM_destroyLock("finishedEvaluateLock","","pthreads")%>
>>
else ""
case SOME(hpcOmSchedule as THREADSCHEDULE(__)) then
let destroylocks = hpcOmSchedule.lockIdc |> idx => function_HPCOM_destroyLock(idx, "lock", type); separator="\n"
let destroyThreads = arrayList(hpcOmSchedule.threadTasks) |> tt hasindex i0 fromindex 0 => function_HPCOM_destroyThread(i0, type); separator="\n"
match type
case ("openmp") then
<<
<%destroylocks%>
>>
else
let joinThreads = arrayList(hpcOmSchedule.threadTasks) |> tt hasindex i0 fromindex 0 => function_HPCOM_joinThread(i0, type); separator="\n"
let threadReleaseLocks = arrayList(hpcOmSchedule.threadTasks) |> tt hasindex i0 fromindex 0 => function_HPCOM_releaseLock(i0, "th_lock", type); separator="\n"
<<
terminateThreads = true;
<%threadReleaseLocks%>
<%joinThreads%>
<%destroylocks%>
<%destroyThreads%>
>>
else ""
end getHpcomDestructorExtension;
template update( list<SimEqSystem> allEquationsPlusWhen,list<SimWhenClause> whenClauses, SimCode simCode, Context context, Boolean useFlatArrayNotation)
::=
let &varDecls = buffer "" /*BUFD*/
match simCode
case SIMCODE(modelInfo = MODELINFO(__)) then
let parCode = update2(allEquationsPlusWhen, odeEquations, modelInfo.name, whenClauses, simCode, hpcOmSchedule, context, lastIdentOfPath(modelInfo.name), useFlatArrayNotation)
<<
<%equationFunctions(allEquations,whenClauses,simCode,contextSimulationDiscrete,useFlatArrayNotation)%>
<%createEvaluateAll(allEquations,whenClauses,simCode,contextOther,useFlatArrayNotation)%>
<%createEvaluateZeroFuncs(equationsForZeroCrossings,simCode,contextOther) %>
<%createEvaluateConditions(simCode, allEquationsPlusWhen, whenClauses, modelInfo.name, context, useFlatArrayNotation)%>
<%parCode%>
>>
end update;
template createEvaluateConditions(SimCode simCode, list<SimEqSystem> allEquationsPlusWhen, list<SimWhenClause> whenClauses, Absyn.Path name, Context context, Boolean useFlatArrayNotation)
::=
match simCode
case SIMCODE(__) then
let &varDecls = buffer "" /*BUFD*/
let eqs = equationsForConditions |> eq => equation_function_call(eq,contextSimulationNonDiscrete,&varDecls, simCode); separator="\n"
let reinit = (whenClauses |> when hasindex i0 => genreinits(when, &varDecls,i0,simCode,context,useFlatArrayNotation) ;separator="\n";empty)
<<
bool <%lastIdentOfPath(name)%>::evaluateConditions(const UPDATETYPE command)
{
bool state_var_reinitialized = false;
//length: <%listLength(equationsForConditions)%>
<%eqs%>
<%reinit%>
return state_var_reinitialized;
}
>>
end createEvaluateConditions;
template update2(list<SimEqSystem> allEquationsPlusWhen, list<list<SimEqSystem>> odeEquations, Absyn.Path name, list<SimWhenClause> whenClauses, SimCode simCode, Option<Schedule> hpcOmScheduleOpt, Context context, String modelNamePrefixStr, Boolean useFlatArrayNotation)
::=
let &varDecls = buffer "" /*BUFD*/
/* let all_equations = (allEquationsPlusWhen |> eqs => (eqs |> eq =>
equation_(eq, contextSimulationDiscrete, &varDecls /*BUFC*/,simCode))
;separator="\n") */
/* let reinit = (whenClauses |> when hasindex i0 => genreinits(when, &varDecls,i0,simCode,context)
;separator="\n";empty) */
let type = getConfigString(HPCOM_CODE)
match hpcOmScheduleOpt
case SOME(hpcOmSchedule as EMPTYSCHEDULE(__)) then
<<
<%CodegenCpp.createEvaluate(odeEquations, whenClauses, simCode, context)%>
>>
case SOME(hpcOmSchedule as LEVELSCHEDULE(__)) then
let odeEqs = hpcOmSchedule.tasksOfLevels |> tasks => function_HPCOM_Level(allEquationsPlusWhen, tasks, type, &varDecls, simCode, useFlatArrayNotation); separator="\n"
match type
case ("mixed") then
<<
static bool state_var_reinitialized = false;
static bool firstRun = true;
void <%lastIdentOfPath(name)%>::evaluateThreadFunc0()
{
//if (omp_get_dynamic())
// omp_set_dynamic(0);
<%varDecls%>
#pragma omp parallel num_threads(<%intSub(getConfigInt(NUM_PROC),1)%>)
{
while(!finished)
{
#ifdef MEASURE_PAPI
int event[NUM_EVENTS] = {PAPI_L2_TCM};
long long values[NUM_EVENTS];
#endif
#pragma omp master
{
<%function_HPCOM_assignLock("startEvaluateLock","","pthreads")%>
#ifdef MEASURE_PAPI
/* Start counting events */
if (PAPI_start_counters(event, NUM_EVENTS) != PAPI_OK) {
fprintf(stderr, "PAPI_start_counters - FAILED\n");
exit(1);
}
#endif
}
#pragma omp barrier
if(finished)
{
<%function_HPCOM_releaseLock("finishedEvaluateLock","","pthreads")%>
break;
}
<%odeEqs%>
#pragma omp barrier
#pragma omp master
{
#ifdef MEASURE_PAPI
/* Read the counters */
if (PAPI_read_counters(values, NUM_EVENTS) != PAPI_OK) {
fprintf(stderr, "PAPI_read_counters - FAILED\n");
exit(1);
}
std::cerr << "L2 Cache misses: " << values[0] << std::endl;
/* Stop counting events */
if (PAPI_stop_counters(values, NUM_EVENTS) != PAPI_OK) {
fprintf(stderr, "PAPI_stoped_counters - FAILED\n");
exit(1);
}
#endif
<%function_HPCOM_releaseLock("finishedEvaluateLock","","pthreads")%>
}
}
}
}
void <%lastIdentOfPath(name)%>::evaluateODE(const UPDATETYPE command)
{
if(firstRun)
{
firstRun = false;
<%generateThread(0, "pthreads", modelNamePrefixStr, "evaluateThreadFunc")%>
}
this->command = command;
<%function_HPCOM_releaseLock("startEvaluateLock","","pthreads")%>
<%function_HPCOM_assignLock("finishedEvaluateLock","","pthreads")%>
}
>>
case ("openmp") then
<<
void <%lastIdentOfPath(name)%>::evaluateODE(const UPDATETYPE command)
{
#ifdef MEASURE_PAPI
int event[NUM_EVENTS] = {PAPI_L2_TCM};
long long values[NUM_EVENTS];
/* Start counting events */
if (PAPI_start_counters(event, NUM_EVENTS) != PAPI_OK) {
fprintf(stderr, "PAPI_start_counters - FAILED\n");
exit(1);
}
#endif
#pragma omp parallel num_threads(<%getConfigInt(NUM_PROC)%>)
{
<%odeEqs%>
}
#ifdef MEASURE_PAPI
/* Read the counters */
if (PAPI_read_counters(values, NUM_EVENTS) != PAPI_OK) {
fprintf(stderr, "PAPI_read_counters - FAILED\n");
exit(1);
}
std::cerr << "L2 Cache misses: " << values[0] << std::endl;
/* Stop counting events */
if (PAPI_stop_counters(values, NUM_EVENTS) != PAPI_OK) {
fprintf(stderr, "PAPI_stoped_counters - FAILED\n");
exit(1);
}
#endif
}
>>
else ""
case SOME(hpcOmSchedule as THREADSCHEDULE(__)) then
match type
case ("openmp") then
let taskEqs = function_HPCOM_Thread(allEquationsPlusWhen,hpcOmSchedule.threadTasks, type, &varDecls, simCode, useFlatArrayNotation); separator="\n"
<<
//using type: <%type%>
void <%lastIdentOfPath(name)%>::evaluateODE(const UPDATETYPE command)
{
omp_set_dynamic(0);
<%&varDecls%>
<%taskEqs%>
}
>>
else
let threadFuncs = arrayList(hpcOmSchedule.threadTasks) |> tt hasindex i0 fromindex 0 => generateThreadFunc(allEquationsPlusWhen, hpcOmSchedule.threadTasks, type, i0, modelNamePrefixStr, &varDecls, simCode, useFlatArrayNotation); separator="\n"
let threadAssignLocks1 = arrayList(hpcOmSchedule.threadTasks) |> tt hasindex i0 fromindex 0 => function_HPCOM_assignLock(i0, "th_lock1", type); separator="\n"
let threadReleaseLocks = arrayList(hpcOmSchedule.threadTasks) |> tt hasindex i0 fromindex 0 => function_HPCOM_releaseLock(i0, "th_lock", type); separator="\n"
<<
<%threadFuncs%>
//using type: <%type%>
void <%lastIdentOfPath(name)%>::evaluateODE(const UPDATETYPE command)
{
this->command = command;
<%threadReleaseLocks%>
<%threadAssignLocks1%>