-
Notifications
You must be signed in to change notification settings - Fork 1
/
grid_codegen_MPI.js
executable file
·1676 lines (1177 loc) · 54.8 KB
/
grid_codegen_MPI.js
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
// At the end see how/if we can parameterize existing code generation
// to only add MPI related constructs when/if needed, otherwise
// fall back to simple code generation.
//TODO: Add free() functionality from grid_codegen_C.js
//MPI: MPI-related global variables
var MPI_Vars;
//MPI: Includes information about if there is at least one global
// grid in a step of a function
// Format FuncHasMPIstep[function_id][step_id]
// CAUTION: main function is in FuncHasMPIstep[2]
var FuncHasMPIstep;
//MPI:
// Used for declaring startX. Scope is per function. This is
// initialized to blank at the start of EACH function.
var Index_start_decl;
//MPI:
var Index_end_per_dim;
//MPI: Returns 0 if current function includes a global grid in one
// of its steps.
function checkFuncHasMPIstep(m, f) {
var found = 0;
var fO = m.allFuncs[f];
for (var s = 0; s < fO.allSteps.length; s++) {
if (FuncHasMPIstep[f][s] == 1) {
found = 1;
break;
}
}
return found;
}
//----------------------------------------------------------------------------
//MPI:
// Detects if there are any Global or Global and Distributed
// grids in any of the functions of the program.
// If there are, then we need to initiate MPI and declare the
// appropriate helping variables.
// Also, initializes FuncHasMPIstep (see declaration for details).
// Returns 1 or 0 if MPI is needed or not, respectively.
//----------------------------------------------------------------------------
function generateMPIinitCode() {
var doMPIinit = 0;
var mO = CurModObj;
for (var f = mO.FuncStartID; f < mO.allFuncs.length; f++) {
var fO = mO.allFuncs[f];
FuncHasMPIstep[f] = new Array();
for (var s = 0; s < fO.allSteps.length; s++) {
for (var g = 0; g < fO.allSteps[s].allGridIds.length; g++) {
var gID = fO.allSteps[s].allGridIds[g];
var gO = fO.allGrids[gID];
if (gO.isGlobal == true) {
doMPIinit = 1;
FuncHasMPIstep[f][s] = 1;
break; // Once a global grid found, break for cur step.
} else {
FuncHasMPIstep[f][s] = 0;
// Continue checking until all grids are finished
// or a global grid is found.
}
}
}
}
if (doMPIinit) {
MPI_Vars = "int Tag = 1;\n" +
"MPI_Status Stat;\n" +
"int Num_ranks;\n\n";
}// else
// alert("MPI needed = " + doMPIinit);
return doMPIinit;
}
//----------------------------------------------------------------------------
//MPI:
// Save the MPI string generated for the program
// parallel: save parallel version if 1. Serial if 0.
// show: To be passed in showCstr to alert(code) if 1.
// Else, just to return the code string to caller.
//----------------------------------------------------------------------------
function saveMPICstr(parallel, show) {
// Get the JSON string
//Regenerate code every time, otherwise may save old one if updated
TypesAllFuncs = new Array();
NamesAllFuncs = new Array();
var str = encodeURIComponent(showMPICstr(1, parallel, show));
//createAPI(0); //API:
//TODO: Is SoA by default (hence '1' as first argument)
download2SaveFortran(str, CurProgObj.fileName);
}
//----------------------------------------------------------------------------
// Show the MPI C string generated for the program
// strOfArr: Use structures of arrays (SoA) if 1. Arrays of structures (AoS)
// if 0.
// show: Show code in JS (using alert) if 1. Just return code string if 0.
//----------------------------------------------------------------------------
function showMPICstr(strOfArr, parallel, show) {
Soa = strOfArr;
ShowParallel = parallel;
/*
// If parallel code generation selected first we need to analyze.
if (ShowParallel) {
var mO = CurModObj; // TODO: Generalize for multiple modules.
var fO = mO.allFuncs[getFuncIdByName(mO, "Main")];
analyzeParallelismAll(fO, 0);
}
*/
TypesAllFuncs = new Array();
NamesAllFuncs = new Array();
FuncHasMPIstep = new Array(); //MPI:
var code = getMPIstr();
if (show) {
alert(code);
} else {
return code;
}
}
//----------------------------------------------------------------------------
// Returns C for the current step in current funtion that the
// user is currently working on
//----------------------------------------------------------------------------
function getMPIstr() {
var mO = CurModObj;
// First, generate code for all functions, including 'main()'
// Will be elements of the func_code array.
var func_code = new Array(); // Used to store code for EACH function
var initMPI = generateMPIinitCode(); //MPI
// Variable to store all include statements needed.
var inclStmts = "#include <stdio.h>\n" +
"#include <stdlib.h>\n";
//MPI:
if (initMPI) inclStmts += "#include <mpi.h>\n";
/*
if (ShowParallel) {
inclStmts += "#include <omp.h>\n";
}
*/
TypeStr = ""; // Used to store TYPEs (i.e., structures).
Func_prototypes = new Array();
// A single string that contains all function code.
var func_code_all = "";
// TODO: Be careful with global variables. If not initialized every time,
// they'll hold the value, until exiting program!
GID_function = 0;
for (var f = mO.FuncStartID; f < mO.allFuncs.length; f++) {
/*
if (ShowParallel && !funcContainsParStep(mO, f) && !FuncHasSerVer[f])
CalledFromSer = 1;
*/
func_code[f] = getMPIstr4Func(mO, f);
/*
if (ShowParallel)
CalledFromSer = 0;
*/
//Note: Be careful where TypesAllFuncs starts != mO.allFuncs[start]
func_code_all += TypesAllFuncs[f - mO.FuncStartID] + " " +
func_code[f];
/*
// If we are in ShowParallel, we may need a serial only version (in
// case of a function that contains (even a single) parallel step(s).
//
if (ShowParallel && FuncHasSerVer[f]) {
// We need to change:
// (a) Header - append "_ser".
// (b) Remove all OpenMP pragma directives (single lines in C).
CalledFromSer = 1;
var altSerFunc = func_code[f]; //getCstr4Func(mO, f);
altSerFunc = altSerFunc.replace("(", "_ser(");
// Regex: From the start of a line match as less as possible
// before finding "#pragma omp" (this includes tabs), then match
// as less as possible until finding a newline. Do this for EACH
// line of the string (m specifier).
altSerFunc = altSerFunc.replace(/^.*?#pragma omp.*\n?/mg, "");
func_code_all += TypesAllFuncs[f-mO.FuncStartID] + " " + altSerFunc;
CalledFromSer = 0;
}
*/
}
// Generate code for main method.
var main_call = "int main(int argc, char *argv[]) {\n";
//TODO:C: Use startup arguments grid as *argv[]. Add more flexibility.
main_call += addIndentation(0) + "char *" +
var2C(CurModObj.allFuncs[DefMainFuncInd].allGrids[1].caption)+"[4];\n";
main_call += addIndentation(0) + "int " +
var2C(CurModObj.allFuncs[DefMainFuncInd].allGrids[0].caption) + ";\n";
// If generating parallel implementation, setting nested parallelism off
// by default.
// TODO: This may be an option for the auto-tuner.
/*
if (ShowParallel) {
main_call += addIndentation(0) + "omp_set_nested(0);\n";
}
*/
//MPI: Init MPI if MPI program
// Can be called at most one per MPI program.
if (initMPI) {
main_call += addIndentation(0) + "MPI_Init(&argc,&argv);\n" +
addIndentation(0) +
"MPI_Comm_size(MPI_COMM_WORLD, &Num_ranks);\n"
}
main_call += addIndentation(0) +
var2C(CurModObj.allFuncs[DefMainFuncInd].allGrids[0].caption) +
" = " + var2C(DefMainFuncName) +
"(" + var2C(CurModObj.allFuncs[DefMainFuncInd].allGrids[1].caption) +
");\n";
//MPI: Finalize MPI if MPI program
if (initMPI) {
main_call += addIndentation(0) + "MPI_Finalize();\n";
}
main_call += "}\n";
// Check if any math functions have been called in the program, so as to
// add the math library in the include statements.
if (InclMath) {
inclStmts += "#include <math.h>\n\n";
} else {
inclStmts += "\n";
}
// Construct function prototypes
var func_protos = "";
for (var i = mO.FuncStartID; i < mO.allFuncs.length; i++) {
func_protos += TypesAllFuncs[i - mO.FuncStartID] + " " +
Func_prototypes[i - mO.FuncStartID];
/*
// If we are in ShowParallel, and we have a serial only version (in
// case of a function that contains (even a single) parallel step(s).
// we will need its prototype, too.
if (ShowParallel && FuncHasSerVer[i]) {
func_protos += TypesAllFuncs[i - mO.FuncStartID] + " " +
Func_prototypes[i - mO.FuncStartID].replace("(",
"_ser(");
}
*/
}
func_protos += "\n\n";
// Final generated code will contain the TYPEs code, the library functions
// code (e.g., for read/write CSV), the functions' code (that contains
// all functions, including ft_Main), and the PROGRAM "int main" that calls
// Main function and subsequently any other functions.
// MPI: Added MPI_Vars
var returnedCode = inclStmts + MPI_Vars + TypeStr + func_protos +
func_code_all + "\n" + main_call;
returnedCode = returnedCode.replace(/UNIQUEIND/g, "int"); //TT
return returnedCode;
}
function getMPIstr4Func(mO, f) {
var fO = mO.allFuncs[f];
// This is the GID_function id of current function corresponding to
// TypesAllFuncs and NamesAllFuncs.
var gID_f = 0;
// Initialize current step numbering for current function to zero.
CurStep = 0;
// Initialize GridsInFunc.
GridsInFunc = new Array();
Loop_var_per_dim = new Array();
Index_start_per_dim = new Array(); //MPI:
Index_end_per_dim = new Array();
if (var2C(fO.funcCallExpr.str) == "ft_Main") {
// Add an INTEGER as main's return value (TypesAllFuncs[0])
TypesAllFuncs.push("int");
//gID_f = 1; //NEXT one
GID_function = 1; //NEXT one
} else {
for (var i = 0; i < TypesAllFuncs.length; i++) {
if (NamesAllFuncs[i] == var2C(fO.funcCallExpr.str)) {
//alert("FOUND in i=" + i + "Callee="+NamesAllFuncs[i] +
//"type="+TypesAllFuncs[i]);
//TODO: (check) Add a dummy type entry for function
//return value. Will be updated later
//(TypesAllFuncs[gID])
TypesAllFuncs.push(TypesAllFuncs[i]);
gID_f = i; //Set, so it can be used to assign the
//required type to temp return value.
}
}
}
// Used for recording functions once (and then recording
// their types and names to be used in other places of
// code generation.
// Initialize to blank at the start of each new function
Func_decl = "";
// See their declaration (global scope) for details on below:
Row_col_decl = "";
Index_start_decl = ""; //MPI:
Index_end_decl = "";
Grids_new_decl = "";
TitleDefs_decl = "";
// Create function header (function type plus name). Arguments to be
// added in subsequent steps.
// TODO:C: Commented out.
var func_head = /*getDataTypeString_C(fO.allGrids[0],null) + " " +*/
var2C(fO.funcCallExpr.str) + "(";
// In func_vars we declare the type and name of any grids that were
// passed as parameters in the current function for which we are
// generating code.
var func_vars = "";
var func_val_init = "";
var arr_dynValues = new Array();
// Add argument list to function header. To do that, go through ALL
// grids in the function and add thos who are incoming args.
for (var g = 0; g < fO.allGrids.length; g++) {
var gO = fO.allGrids[g];
// TODO: If a grid with specific indices e.g. array[3][1] treat as
// passed by value!
if (gO.inArgNum >= 0) { // This grid is an incoming arg
if (gO.numDims > 1 && gO.typesInDim != -1) {
if (gO.inArgNum > 0) func_head += ", "; // arg separator
func_head += getDataTypeString_C(gO) + " ";
if (!Soa) func_head += " *";
//TODO: CAUTION: This is for the case of TYPE variable
// passed using its name (i.e., no specific element).
func_head += "typvar_" + gO.caption;
} else {
if (gO.numDims >= 1) {
if (gO.inArgNum > 0) func_head += ", "; // arg separator
func_head += getDataTypeString_C(gO) + " ";
func_head += "*" + var2C(gO.caption);
// Grid caption as arg name
} else {
// Ensure has not been implicitly declared via a
// dynamically sized non-scalar grid (see below).
if (func_head.indexOf(var2C(gO.caption))==-1){
if (gO.inArgNum > 0) func_head += ", "; // arg separator
func_head += getDataTypeString_C(gO) + " ";
func_head += var2C(gO.caption);
}
// else do not declare at all.
}
}
if (gO.numDims >=1) {
// Given we dynamically allocate all non-scalar grids, we
// need to pass dimensions that are variables (the constant
// dimensions are auto-generated as numbers in resulting
// code). They are also needed to be used in loops (in
// Fortran we could get this info using SIZE(), but in C
// there is nothing similar).
var dynVals = ", ";
for (var i = 0; i < gO.dimActSize.length; i++) {
if (gO.dimDynSize[i] != null) {
// The second check takes care of scalars that may have
// been passed as parameters (i.e., explicitly), while
// the first is for implicit passing (scalar grids used
// for dynamic size of non-scalar grids).
if(arr_dynValues.indexOf(var2C(gO.dimDynSize[i]))==-1 &&
func_head.indexOf(var2C(gO.dimDynSize[i]))==-1) {
arr_dynValues.push(var2C(gO.dimDynSize[i]));
dynVals += "int "+var2C(gO.dimDynSize[i]) + ",";
}
}
}
if (dynVals != ", ") {
func_head += dynVals.replace(/,+$/, "");;
}
} else { //KK:FUN
// For scalar-grids, we have to copy the src value into a temp
// variable called fun_<src_var_name>
// TODO: Can fuse with earlier similar loop for function
// header.
func_vars += addIndentation(0) + getDataTypeString_C(gO,
null) + " fun_" + gO.caption + ";\n";
func_val_init += addIndentation(0) + "fun_" + gO.caption +
" = " + var2C(gO.caption) + ";\n";
}
}
}
func_head += ")";
Func_prototypes.push(func_head + ";\n");
func_head += " {\n";
// At this point we have completed in func_head the function header
// that contains the type of function, the function name, and its
// arguments contained in parentheses.
//MPI: If current function has been found to include at least an
// MPI step, then we need to define a variable indicating
// each rank's id.
var funcID = getFuncIdByName(mO, fO.funcCallExpr.str);
if (checkFuncHasMPIstep(mO, funcID)) {
func_vars += addIndentation(0) + "int myRank;\n" +
addIndentation(0) +
"MPI_Comm_rank(MPI_COMM_WORLD,&myRank);\n";
}
// Used for declaration of the ret value declaration within the func.
// This is always in position 0 in fO.allGrids[].
func_vars += addIndentation(0) + getDataTypeString_C(fO.allGrids[0],
null) + " " + var2C(fO.allGrids[0].caption) + ";\n";
// STEP: Code for each step in the function
//
var step_code = "";
//
var stepStart = 1; // Note: Function prototype at step 0.
//
for (var s = stepStart; s < fO.allSteps.length; s++) {
step_code += getMPIstr4Step(fO, fO.allSteps[s], mO); //MPI
}
// Construct the final function string that contains:
// a) the function header (type + name + arguments).
// b) arguments' declaration (type + name).
// c) temp scalar variables (to keep 'pass by value' semantics for
// scalar arguments).
// d) row, col, indX (loop indices) - no redefinition across steps.
// e) end0, end1, etc. (loop end variables) - no redefinition across steps
// f) title definitions.
// g) new grid declarations (i.e., not passed as arguments).
// h) Initialization of scalar variables that store scalar function
// arguments (fun_<scalar_arg_name>).
// i) computation code for all steps of this function.
// j) return value assignment to function name
// k) end function statement
var function_string = func_head;
function_string += func_vars + //KK:FUN //MPI: Added Index_start_decl
Row_col_decl + Index_start_decl + Index_end_decl + TitleDefs_decl +
Grids_new_decl +
func_val_init + step_code;
// If no return statement added (e.g., when "void"), we return 1 (since
// ALL Grid Language functions need a return type).
//if (function_string.indexOf("return") == -1) {
// function_string += addIndentation(0) + "return 1;\n";
//}
function_string += "}\n\n";
return function_string;
}
function getMPIstr4Step(fO, sO, mO) {
var grids = "";
var titleDefs = "";
Struct_el_decl = "";
// Used to keep track of which DO loops are parallel, so we
// can close them appropriately in the reverse order.
var stepOmpDoStack = new Array();
// Increase step ID (within a function- across functions this is
// re-initialized to zero)
CurStep++;
var allocatablesOfStep = "";
var funcID = getFuncIdByName(mO, fO.funcCallExpr.str);
// Go through all grids in the step and declare as needed fields.
for (var g = 0; g < sO.allGridIds.length; g++) {
var gId = sO.allGridIds[g];
var gO = fO.allGrids[gId];
if ((gO.inArgNum < 0) && (!gO.isRetVal)) {
// If grid has been already declared within THIS function,
// do not re-declare
if (!gridDeclaredInFunc(gId)) {
var newgrid = createTypeString_C(gO);
// Get the declaration of current grid
var isAllocGrid = 0;
// Get what is inside the parentheses (i.e., the dimensions).
// Can be null if it is a scalar grid.
var dimensions = newgrid.match(/\[(.+)\]/);
if (dimensions != null) {
// Check all dims. If EVEN one dynamic is found, we need
// to address the array as a 1D dynamically allocated.
// dimActSize length always has length equal to the
// dimensions, even if their value is not the one
// used (but rather a dynamic size if applicable).
// TODO:C: Doesn't cover STRUCTS with dynamic num
// of elements.
newgrid = newgrid.replace(dimensions[0], "");
var split_dims = dimensions[1].replace(/ /g, "");
split_dims = split_dims.split("][");
for (var k = 0; k < split_dims.length; k++) {
// If dimension is not a number, this means we may be
// using
// a variable as a dimension.
if (isNaN(split_dims[k])) {
// Only exception if we have a TYPE declared which
// is NOT allocatable.
// TODO: If we decide to allow tables of structs
// later this will need to be reconsidered.
if (split_dims[k].indexOf("TYP_") == -1 &&
split_dims[k].indexOf("DIMENSION") == -1) {
isAllocGrid = 1;
//split_dims[k] = var2C(split_dims[k]);
}
}
}
// C pointer to be malloc'd
// ...and do actual allocation by calling "malloc".
var tmp_type;
if(gO.numDims > 1 && gO.typesInDim != -1)
tmp_type = findTypeVarType_C(gO,1);
else
tmp_type = getDataTypeString_C(gO, null);
var tmp_dim_alloc = "";
for(var i = 0; i < split_dims.length - 1; i++)
tmp_dim_alloc += split_dims[i] + "*";
tmp_dim_alloc += split_dims[split_dims.length - 1];
var gridNam;
if(gO.typesInDim == -1)
gridNam = var2C(gO.caption);
else
gridNam = "typvar_" + gO.caption;
//MPI:
//if (!checkFuncHasMPIstep(mO, funcID)) {
if (!(gO.isGlobal && gO.isDistributed)) {
allocatablesOfStep += addIndentation(0) +
gridNam + " = " +
"(" + tmp_type + " *)malloc(sizeof(" +
tmp_type + ")*" + tmp_dim_alloc + ");\n";
} else {
allocatablesOfStep += addIndentation(0) +
gridNam + " = " +
"(" + tmp_type + " *)malloc(sizeof(" +
tmp_type + ")*(" + tmp_dim_alloc +
"/numRanks)" +
");\n";
}
}
// Commenting
if(gO.comment != null)
grids += addIndentation(0) + "// " + gO.comment + "\n";
grids += addIndentation(0) + newgrid;
// Push into list of grids that have been declared (in the
// context of the current function being parsed).
GridsInFunc.push(gId);
}
}
// STEP: Get var defs for titles.
// Get titleDefs (e.g., var _d3Tab1,_d3Tab2...).
var titleDefTmp = getTitleDefsOfGrid(gO);
if (titleDefTmp != "") {
// Remove "var " and trailing ';' (e.g., _d3Tab1,_d3Tab2...)
// and prepend the grid name before the title, to discern
// for the cases when a (same) title is used for different
// grids that corresponds to different values.
titleDefTmp = titleDefTmp.replace("var ", "");
//titleDefTmp = titleDefTmp.replace(";", "");
titleDefTmp = titleDefTmp.replace(/_/g, gO.caption + "_");
titleDefTmp = "int " + titleDefTmp;
// If it has been declared already, do not re-declare.
if (TitleDefs_decl.indexOf(titleDefTmp) == -1) {
TitleDefs_decl += addIndentation(0) + titleDefTmp;
}
}
}
// STEP: Create C for loops (a loop for each index var)
// Note: rangeExpr.exprArr[] contains root range expressions
//
var rangeExpr = sO.boxExprs[CodeBoxId.Range];
var loop_close = "";
var forstr = "";
// In non-parallel the above variable stores all loops,
// in parallel code generation it only stores paral/ble ones.
var forstr2 = "";
// Used in parallel code generation to store non-parallelizable loops
var collapsed_loop_vars = "";
// Used in parallel code generation, to store all loop variables,
// so that no endv assignments between collapsed DO loops.
var private_vars = "";
// Used in parallel code generation to store loop-private variables
// (e.g., LET variables).
// Used for indentation purposes (adding extra, when needed - when we have
// foreach loop over one or more dimensions, otherwise it is zero).
var index_extra_indent = 0;
// if there are index variables
//
if (rangeExpr && rangeExpr.exprArr && rangeExpr.isForeach()) {
var num_index_vars = rangeExpr.exprArr.length;
index_extra_indent = num_index_vars;
var collapse = 0;
// Defines whether we are using collapse in current step's loop.
var collapse_int;
// Used for altering collapse value within the loop, but we keep
// the original, too, in collapse_int.
if (ShowParallel) {
// If there are more than one par/ble dimensions in Pragma_str we
// will use COLLAPSE(X), where X is the number of dimensions
// (parallel DO LOOPS).
// TODO: Later as part of auto-tuning, we will test all possible
// combinations of collapsing loops.
collapse = Pragma_str[funcID][CurStep].split(' ').length - 1;
}
collapse_int = collapse;
var forStrArr = new Array(); // REORDER
for (var iv = 0; iv < num_index_vars; iv++) {
// STEP: get code for foreach loop
//
var rexpr = rangeExpr.exprArr[iv];
assert(rexpr.gO, "Range expr must have a gO");
// TODO: FIX FIX FIX
var ivar = var2C(rexpr.labelExpr.str);
//MPI: Will only be used later if grid Global + Distr. + Ext. dim
var startv = var2C(rexpr.exprArr[RangeFields.Start].str);
// Define the value of literal 'end'
// var endv = var2C(DefEndName + rexpr.selDim);
//MPI: Bug fix (for generality for MPI)
var endv = var2C(rexpr.exprArr[RangeFields.End].str);
//TODO: Why did I change the below to the above?
//var endv = expr2Cstring(rexpr.exprArr[RangeFields.End]);
// IMPORTANT NOTE: semasiology is SAVE if assignment
// is at the time of declaration. Saved between function calls.
// That's why here we separate declaration and initialization.
// We do not allow re-declaration of the same start/end variable
// across steps.
if (Index_start_per_dim.indexOf(endv) == -1) {
Index_start_decl += addIndentation(0) + "int " +
startv + ";\n";
Index_start_per_dim.push(startv);
}
if (Index_end_per_dim.indexOf(endv) == -1) {
Index_end_decl += addIndentation(0) + "int " +
endv + ";\n";
Index_end_per_dim.push(endv);
}
// Pick the end value based on whether the size of the dim is
// variable (dynamically allocated) or not.
//
var actendval = rexpr.gO.dimActSize[rexpr.selDim];
var dynendval = rexpr.gO.dimDynSize[rexpr.selDim];
//MPI:
var endval;
if (dynendval == null) {
if (rexpr.gO.isGlobal && rexpr.gO.isDistributed &&
rexpr.gO.dimIsExtended[iv]) {
endval = actendval + "/numRanks";
} else {
endval = actendval;
}
} else {
endval = var2C(dynendval);
}
//var endval = (dynendval) ? var2C(dynendval)
// : actendval;
// In parallel code generation, if loop is parallel, we append the
// endval to the collapsed loop vars, else we declare it normally
// at its normal position (whereas collapsed loop vars appear
// BEFORE the OMP PARALLEL DO COLLAPSED(X) directive).
if (ShowParallel) {
if (Pragma_str[funcID][CurStep].indexOf(ivar) != -1) {
collapsed_loop_vars += addIndentation(0) + endv +
" = " + endval +
"-1;\n";
} else {
forstr2 += addIndentation(iv) + endv + " = " + endval +
"-1;\n";
}
} else {
//MPI:
if (rexpr.gO.isGlobal && rexpr.gO.isDistributed &&
rexpr.gO.dimIsExtended[iv])
forstr += addIndentation(iv) + startv + " = 0;\n";
forstr += addIndentation(iv) + endv + " = " + endval +
"-1;\n";
}
if (Loop_var_per_dim.indexOf(ivar) == -1) {
// Adding the names of index variables to the declarations
// string if it has NOT been declared for this dimension in
// THIS function and push it in the array denoting it has
// been now declared.
Row_col_decl += addIndentation(0) + "int " + ivar +
";\n";
Loop_var_per_dim.push(ivar);
}
// Step: Start/End/Step expressions
var start = expr2Cstring(rexpr.exprArr[RangeFields.Start]);
var end = expr2Cstring(rexpr.exprArr[RangeFields.End]);
var step = expr2Cstring(rexpr.exprArr[RangeFields.Step]);
if (ShowParallel) {
// ShowParallel check is implied 0 if collapse is > 0
// (safely delete check).
// If loop is parallel over ivar:
if (Pragma_str[funcID][CurStep].indexOf(ivar) != -1) {
if (collapse_int != 0) {
forstr += addIndentation(0) +
"#pragma omp parallel for collapse(" + collapse +
")\n";
collapse_int = 0;
// So that only first parallelizable dimension is
// written (with collapse thereby incorporating all
// parallelizable dimensions).
}
// TODO: This will be needed when we allow multiple
// combinations in auto-tuner.
// Here maintain a stack of OMP DO loops, so we can
// close accordingly.
//stepOmpDoStack.push("!$OMP END PARALLEL DO\n");
//forstr +="for (" + ivar + " = " +
// start + "; " + ivar + " <= " + end + "; " +
// ivar + " += " + step + ") {\n";
forStrArr.push(new Array(ivar, start, end, step));
} else {
// Normal (non-parallel) DO loop:
// TODO: Will be needed in allowing multiple combinations
// of collapsing/non-collapsing in auto-tuner.
//stepOmpDoStack.push("");
forstr2 += addIndentation(iv) + "for (" + ivar + " = " +
start + "; " + ivar + " <= " + end + "; " +
ivar + " += " + step + ") {\n";
}
} else { // Non-parallelized version: all DO loops, normal code:
//forstr += addIndentation(iv) + "for (" + ivar + " = " +
// start + "; " + ivar + " <= " + end + "; " +
// ivar + " += " + step + ") {\n";
forStrArr.push(new Array(ivar, start, end, step));
}
}
// TODO: CAUTION: For (ShowParallel == 1, parallelizable step) and
// (ShowParallel == 0), we do it in forstr variable.
// For both, the assumption is that an index variable CANNOT
// be allowed to be used as a boundary variable in ANOTHER loop, or step