-
Notifications
You must be signed in to change notification settings - Fork 51
/
slang_rs_reflection.cpp
2112 lines (1787 loc) · 71.9 KB
/
slang_rs_reflection.cpp
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
/*
* Copyright 2010-2014, The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "slang_rs_reflection.h"
#include <sys/stat.h>
#include <cstdarg>
#include <cctype>
#include <algorithm>
#include <sstream>
#include <string>
#include <utility>
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/StringExtras.h"
#include "os_sep.h"
#include "slang_rs_context.h"
#include "slang_rs_export_var.h"
#include "slang_rs_export_foreach.h"
#include "slang_rs_export_func.h"
#include "slang_rs_reflect_utils.h"
#include "slang_version.h"
#include "slang_utils.h"
#define RS_SCRIPT_CLASS_NAME_PREFIX "ScriptC_"
#define RS_SCRIPT_CLASS_SUPER_CLASS_NAME "ScriptC"
#define RS_TYPE_CLASS_SUPER_CLASS_NAME ".Script.FieldBase"
#define RS_TYPE_ITEM_CLASS_NAME "Item"
#define RS_TYPE_ITEM_SIZEOF_LEGACY "Item.sizeof"
#define RS_TYPE_ITEM_SIZEOF_CURRENT "mElement.getBytesSize()"
#define RS_TYPE_ITEM_BUFFER_NAME "mItemArray"
#define RS_TYPE_ITEM_BUFFER_PACKER_NAME "mIOBuffer"
#define RS_TYPE_ELEMENT_REF_NAME "mElementCache"
#define RS_EXPORT_VAR_INDEX_PREFIX "mExportVarIdx_"
#define RS_EXPORT_VAR_PREFIX "mExportVar_"
#define RS_EXPORT_VAR_ELEM_PREFIX "mExportVarElem_"
#define RS_EXPORT_VAR_DIM_PREFIX "mExportVarDim_"
#define RS_EXPORT_VAR_CONST_PREFIX "const_"
#define RS_ELEM_PREFIX "__"
#define RS_FP_PREFIX "__rs_fp_"
#define RS_RESOURCE_NAME "__rs_resource_name"
#define RS_EXPORT_FUNC_INDEX_PREFIX "mExportFuncIdx_"
#define RS_EXPORT_FOREACH_INDEX_PREFIX "mExportForEachIdx_"
#define RS_EXPORT_VAR_ALLOCATION_PREFIX "mAlloction_"
#define RS_EXPORT_VAR_DATA_STORAGE_PREFIX "mData_"
namespace slang {
class RSReflectionJavaElementBuilder {
public:
RSReflectionJavaElementBuilder(const char *ElementBuilderName,
const RSExportRecordType *ERT,
const char *RenderScriptVar,
GeneratedFile *Out, const RSContext *RSContext,
RSReflectionJava *Reflection);
void generate();
private:
void genAddElement(const RSExportType *ET, const std::string &VarName,
unsigned ArraySize);
void genAddStatementStart();
void genAddStatementEnd(const std::string &VarName, unsigned ArraySize);
void genAddPadding(int PaddingSize);
// TODO Will remove later due to field name information is not necessary for
// C-reflect-to-Java
std::string createPaddingField() {
return mPaddingPrefix + llvm::itostr(mPaddingFieldIndex++);
}
const char *mElementBuilderName;
const RSExportRecordType *mERT;
const char *mRenderScriptVar;
GeneratedFile *mOut;
std::string mPaddingPrefix;
int mPaddingFieldIndex;
const RSContext *mRSContext;
RSReflectionJava *mReflection;
};
static const char *GetMatrixTypeName(const RSExportMatrixType *EMT) {
static const char *MatrixTypeJavaNameMap[] = {/* 2x2 */ "Matrix2f",
/* 3x3 */ "Matrix3f",
/* 4x4 */ "Matrix4f",
};
unsigned Dim = EMT->getDim();
if ((Dim - 2) < (sizeof(MatrixTypeJavaNameMap) / sizeof(const char *)))
return MatrixTypeJavaNameMap[EMT->getDim() - 2];
slangAssert(false && "GetMatrixTypeName : Unsupported matrix dimension");
return NULL;
}
static const char *GetVectorAccessor(unsigned Index) {
static const char *VectorAccessorMap[] = {/* 0 */ "x",
/* 1 */ "y",
/* 2 */ "z",
/* 3 */ "w",
};
slangAssert((Index < (sizeof(VectorAccessorMap) / sizeof(const char *))) &&
"Out-of-bound index to access vector member");
return VectorAccessorMap[Index];
}
static const char *GetPackerAPIName(const RSExportPrimitiveType *EPT) {
static const char *PrimitiveTypePackerAPINameMap[] = {
"", // DataTypeFloat16
"addF32", // DataTypeFloat32
"addF64", // DataTypeFloat64
"addI8", // DataTypeSigned8
"addI16", // DataTypeSigned16
"addI32", // DataTypeSigned32
"addI64", // DataTypeSigned64
"addU8", // DataTypeUnsigned8
"addU16", // DataTypeUnsigned16
"addU32", // DataTypeUnsigned32
"addU64", // DataTypeUnsigned64
"addBoolean", // DataTypeBoolean
"addU16", // DataTypeUnsigned565
"addU16", // DataTypeUnsigned5551
"addU16", // DataTypeUnsigned4444
"addMatrix", // DataTypeRSMatrix2x2
"addMatrix", // DataTypeRSMatrix3x3
"addMatrix", // DataTypeRSMatrix4x4
"addObj", // DataTypeRSElement
"addObj", // DataTypeRSType
"addObj", // DataTypeRSAllocation
"addObj", // DataTypeRSSampler
"addObj", // DataTypeRSScript
"addObj", // DataTypeRSMesh
"addObj", // DataTypeRSPath
"addObj", // DataTypeRSProgramFragment
"addObj", // DataTypeRSProgramVertex
"addObj", // DataTypeRSProgramRaster
"addObj", // DataTypeRSProgramStore
"addObj", // DataTypeRSFont
};
unsigned TypeId = EPT->getType();
if (TypeId < (sizeof(PrimitiveTypePackerAPINameMap) / sizeof(const char *)))
return PrimitiveTypePackerAPINameMap[EPT->getType()];
slangAssert(false && "GetPackerAPIName : Unknown primitive data type");
return NULL;
}
static std::string GetTypeName(const RSExportType *ET, bool Brackets = true) {
switch (ET->getClass()) {
case RSExportType::ExportClassPrimitive: {
return RSExportPrimitiveType::getRSReflectionType(
static_cast<const RSExportPrimitiveType *>(ET))->java_name;
}
case RSExportType::ExportClassPointer: {
const RSExportType *PointeeType =
static_cast<const RSExportPointerType *>(ET)->getPointeeType();
if (PointeeType->getClass() != RSExportType::ExportClassRecord)
return "Allocation";
else
return PointeeType->getElementName();
}
case RSExportType::ExportClassVector: {
const RSExportVectorType *EVT = static_cast<const RSExportVectorType *>(ET);
std::stringstream VecName;
VecName << EVT->getRSReflectionType(EVT)->rs_java_vector_prefix
<< EVT->getNumElement();
return VecName.str();
}
case RSExportType::ExportClassMatrix: {
return GetMatrixTypeName(static_cast<const RSExportMatrixType *>(ET));
}
case RSExportType::ExportClassConstantArray: {
const RSExportConstantArrayType *CAT =
static_cast<const RSExportConstantArrayType *>(ET);
std::string ElementTypeName = GetTypeName(CAT->getElementType());
if (Brackets) {
ElementTypeName.append("[]");
}
return ElementTypeName;
}
case RSExportType::ExportClassRecord: {
return ET->getElementName() + "." RS_TYPE_ITEM_CLASS_NAME;
}
default: { slangAssert(false && "Unknown class of type"); }
}
return "";
}
static const char *GetTypeNullValue(const RSExportType *ET) {
switch (ET->getClass()) {
case RSExportType::ExportClassPrimitive: {
const RSExportPrimitiveType *EPT =
static_cast<const RSExportPrimitiveType *>(ET);
if (EPT->isRSObjectType())
return "null";
else if (EPT->getType() == DataTypeBoolean)
return "false";
else
return "0";
break;
}
case RSExportType::ExportClassPointer:
case RSExportType::ExportClassVector:
case RSExportType::ExportClassMatrix:
case RSExportType::ExportClassConstantArray:
case RSExportType::ExportClassRecord: {
return "null";
break;
}
default: { slangAssert(false && "Unknown class of type"); }
}
return "";
}
static std::string GetBuiltinElementConstruct(const RSExportType *ET) {
if (ET->getClass() == RSExportType::ExportClassPrimitive) {
return std::string("Element.") + ET->getElementName();
} else if (ET->getClass() == RSExportType::ExportClassVector) {
const RSExportVectorType *EVT = static_cast<const RSExportVectorType *>(ET);
if (EVT->getType() == DataTypeFloat32) {
if (EVT->getNumElement() == 2) {
return "Element.F32_2";
} else if (EVT->getNumElement() == 3) {
return "Element.F32_3";
} else if (EVT->getNumElement() == 4) {
return "Element.F32_4";
} else {
slangAssert(false && "Vectors should be size 2, 3, 4");
}
} else if (EVT->getType() == DataTypeUnsigned8) {
if (EVT->getNumElement() == 4)
return "Element.U8_4";
}
} else if (ET->getClass() == RSExportType::ExportClassMatrix) {
const RSExportMatrixType *EMT = static_cast<const RSExportMatrixType *>(ET);
switch (EMT->getDim()) {
case 2:
return "Element.MATRIX_2X2";
case 3:
return "Element.MATRIX_3X3";
case 4:
return "Element.MATRIX_4X4";
default:
slangAssert(false && "Unsupported dimension of matrix");
}
}
// RSExportType::ExportClassPointer can't be generated in a struct.
return "";
}
/********************** Methods to generate script class **********************/
RSReflectionJava::RSReflectionJava(const RSContext *Context,
std::vector<std::string> *GeneratedFileNames,
const std::string &OutputBaseDirectory,
const std::string &RSSourceFileName,
const std::string &BitCodeFileName,
bool EmbedBitcodeInJava)
: mRSContext(Context), mPackageName(Context->getReflectJavaPackageName()),
mRSPackageName(Context->getRSPackageName()),
mOutputBaseDirectory(OutputBaseDirectory),
mRSSourceFileName(RSSourceFileName), mBitCodeFileName(BitCodeFileName),
mResourceId(RSSlangReflectUtils::JavaClassNameFromRSFileName(
mBitCodeFileName.c_str())),
mScriptClassName(RS_SCRIPT_CLASS_NAME_PREFIX +
RSSlangReflectUtils::JavaClassNameFromRSFileName(
mRSSourceFileName.c_str())),
mEmbedBitcodeInJava(EmbedBitcodeInJava), mNextExportVarSlot(0),
mNextExportFuncSlot(0), mNextExportForEachSlot(0), mLastError(""),
mGeneratedFileNames(GeneratedFileNames), mFieldIndex(0) {
slangAssert(mGeneratedFileNames && "Must supply GeneratedFileNames");
slangAssert(!mPackageName.empty() && mPackageName != "-");
mOutputDirectory = RSSlangReflectUtils::ComputePackagedPath(
OutputBaseDirectory.c_str(), mPackageName.c_str()) +
OS_PATH_SEPARATOR_STR;
// mElement.getBytesSize only exists on JB+
if (mRSContext->getTargetAPI() >= SLANG_JB_TARGET_API) {
mItemSizeof = RS_TYPE_ITEM_SIZEOF_CURRENT;
} else {
mItemSizeof = RS_TYPE_ITEM_SIZEOF_LEGACY;
}
}
bool RSReflectionJava::genScriptClass(const std::string &ClassName,
std::string &ErrorMsg) {
if (!startClass(AM_Public, false, ClassName, RS_SCRIPT_CLASS_SUPER_CLASS_NAME,
ErrorMsg))
return false;
genScriptClassConstructor();
// Reflect export variable
for (RSContext::const_export_var_iterator I = mRSContext->export_vars_begin(),
E = mRSContext->export_vars_end();
I != E; I++)
genExportVariable(*I);
// Reflect export for each functions (only available on ICS+)
if (mRSContext->getTargetAPI() >= SLANG_ICS_TARGET_API) {
for (RSContext::const_export_foreach_iterator
I = mRSContext->export_foreach_begin(),
E = mRSContext->export_foreach_end();
I != E; I++)
genExportForEach(*I);
}
// Reflect export function
for (RSContext::const_export_func_iterator
I = mRSContext->export_funcs_begin(),
E = mRSContext->export_funcs_end();
I != E; I++)
genExportFunction(*I);
endClass();
return true;
}
void RSReflectionJava::genScriptClassConstructor() {
std::string className(RSSlangReflectUtils::JavaBitcodeClassNameFromRSFileName(
mRSSourceFileName.c_str()));
// Provide a simple way to reference this object.
mOut.indent() << "private static final String " RS_RESOURCE_NAME " = \""
<< getResourceId() << "\";\n";
// Generate a simple constructor with only a single parameter (the rest
// can be inferred from information we already have).
mOut.indent() << "// Constructor\n";
startFunction(AM_Public, false, NULL, getClassName(), 1, "RenderScript",
"rs");
if (getEmbedBitcodeInJava()) {
// Call new single argument Java-only constructor
mOut.indent() << "super(rs,\n";
mOut.indent() << " " << RS_RESOURCE_NAME ",\n";
mOut.indent() << " " << className << ".getBitCode32(),\n";
mOut.indent() << " " << className << ".getBitCode64());\n";
} else {
// Call alternate constructor with required parameters.
// Look up the proper raw bitcode resource id via the context.
mOut.indent() << "this(rs,\n";
mOut.indent() << " rs.getApplicationContext().getResources(),\n";
mOut.indent() << " rs.getApplicationContext().getResources()."
"getIdentifier(\n";
mOut.indent() << " " RS_RESOURCE_NAME ", \"raw\",\n";
mOut.indent()
<< " rs.getApplicationContext().getPackageName()));\n";
endFunction();
// Alternate constructor (legacy) with 3 original parameters.
startFunction(AM_Public, false, NULL, getClassName(), 3, "RenderScript",
"rs", "Resources", "resources", "int", "id");
// Call constructor of super class
mOut.indent() << "super(rs, resources, id);\n";
}
// If an exported variable has initial value, reflect it
for (RSContext::const_export_var_iterator I = mRSContext->export_vars_begin(),
E = mRSContext->export_vars_end();
I != E; I++) {
const RSExportVar *EV = *I;
if (!EV->getInit().isUninit()) {
genInitExportVariable(EV->getType(), EV->getName(), EV->getInit());
} else if (EV->getArraySize()) {
// Always create an initial zero-init array object.
mOut.indent() << RS_EXPORT_VAR_PREFIX << EV->getName() << " = new "
<< GetTypeName(EV->getType(), false) << "["
<< EV->getArraySize() << "];\n";
size_t NumInits = EV->getNumInits();
const RSExportConstantArrayType *ECAT =
static_cast<const RSExportConstantArrayType *>(EV->getType());
const RSExportType *ET = ECAT->getElementType();
for (size_t i = 0; i < NumInits; i++) {
std::stringstream Name;
Name << EV->getName() << "[" << i << "]";
genInitExportVariable(ET, Name.str(), EV->getInitArray(i));
}
}
if (mRSContext->getTargetAPI() >= SLANG_JB_TARGET_API) {
genTypeInstance(EV->getType());
}
genFieldPackerInstance(EV->getType());
}
for (RSContext::const_export_foreach_iterator
I = mRSContext->export_foreach_begin(),
E = mRSContext->export_foreach_end();
I != E; I++) {
const RSExportForEach *EF = *I;
const RSExportForEach::InTypeVec &InTypes = EF->getInTypes();
for (RSExportForEach::InTypeIter BI = InTypes.begin(), EI = InTypes.end();
BI != EI; BI++) {
if (*BI != NULL) {
genTypeInstanceFromPointer(*BI);
}
}
const RSExportType *OET = EF->getOutType();
if (OET) {
genTypeInstanceFromPointer(OET);
}
}
endFunction();
for (std::set<std::string>::iterator I = mTypesToCheck.begin(),
E = mTypesToCheck.end();
I != E; I++) {
mOut.indent() << "private Element " RS_ELEM_PREFIX << *I << ";\n";
}
for (std::set<std::string>::iterator I = mFieldPackerTypes.begin(),
E = mFieldPackerTypes.end();
I != E; I++) {
mOut.indent() << "private FieldPacker " RS_FP_PREFIX << *I << ";\n";
}
}
void RSReflectionJava::genInitBoolExportVariable(const std::string &VarName,
const clang::APValue &Val) {
slangAssert(!Val.isUninit() && "Not a valid initializer");
slangAssert((Val.getKind() == clang::APValue::Int) &&
"Bool type has wrong initial APValue");
mOut.indent() << RS_EXPORT_VAR_PREFIX << VarName << " = ";
mOut << ((Val.getInt().getSExtValue() == 0) ? "false" : "true") << ";\n";
}
void
RSReflectionJava::genInitPrimitiveExportVariable(const std::string &VarName,
const clang::APValue &Val) {
slangAssert(!Val.isUninit() && "Not a valid initializer");
mOut.indent() << RS_EXPORT_VAR_PREFIX << VarName << " = ";
genInitValue(Val, false);
mOut << ";\n";
}
void RSReflectionJava::genInitExportVariable(const RSExportType *ET,
const std::string &VarName,
const clang::APValue &Val) {
slangAssert(!Val.isUninit() && "Not a valid initializer");
switch (ET->getClass()) {
case RSExportType::ExportClassPrimitive: {
const RSExportPrimitiveType *EPT =
static_cast<const RSExportPrimitiveType *>(ET);
if (EPT->getType() == DataTypeBoolean) {
genInitBoolExportVariable(VarName, Val);
} else {
genInitPrimitiveExportVariable(VarName, Val);
}
break;
}
case RSExportType::ExportClassPointer: {
if (!Val.isInt() || Val.getInt().getSExtValue() != 0)
std::cout << "Initializer which is non-NULL to pointer type variable "
"will be ignored\n";
break;
}
case RSExportType::ExportClassVector: {
const RSExportVectorType *EVT = static_cast<const RSExportVectorType *>(ET);
switch (Val.getKind()) {
case clang::APValue::Int:
case clang::APValue::Float: {
for (unsigned i = 0; i < EVT->getNumElement(); i++) {
std::string Name = VarName + "." + GetVectorAccessor(i);
genInitPrimitiveExportVariable(Name, Val);
}
break;
}
case clang::APValue::Vector: {
std::stringstream VecName;
VecName << EVT->getRSReflectionType(EVT)->rs_java_vector_prefix
<< EVT->getNumElement();
mOut.indent() << RS_EXPORT_VAR_PREFIX << VarName << " = new "
<< VecName.str() << "();\n";
unsigned NumElements = std::min(
static_cast<unsigned>(EVT->getNumElement()), Val.getVectorLength());
for (unsigned i = 0; i < NumElements; i++) {
const clang::APValue &ElementVal = Val.getVectorElt(i);
std::string Name = VarName + "." + GetVectorAccessor(i);
genInitPrimitiveExportVariable(Name, ElementVal);
}
break;
}
case clang::APValue::MemberPointer:
case clang::APValue::Uninitialized:
case clang::APValue::ComplexInt:
case clang::APValue::ComplexFloat:
case clang::APValue::LValue:
case clang::APValue::Array:
case clang::APValue::Struct:
case clang::APValue::Union:
case clang::APValue::AddrLabelDiff: {
slangAssert(false && "Unexpected type of value of initializer.");
}
}
break;
}
// TODO(zonr): Resolving initializer of a record (and matrix) type variable
// is complex. It cannot obtain by just simply evaluating the initializer
// expression.
case RSExportType::ExportClassMatrix:
case RSExportType::ExportClassConstantArray:
case RSExportType::ExportClassRecord: {
#if 0
unsigned InitIndex = 0;
const RSExportRecordType *ERT =
static_cast<const RSExportRecordType*>(ET);
slangAssert((Val.getKind() == clang::APValue::Vector) &&
"Unexpected type of initializer for record type variable");
mOut.indent() << RS_EXPORT_VAR_PREFIX << VarName
<< " = new " << ERT->getElementName()
<< "." RS_TYPE_ITEM_CLASS_NAME"();\n";
for (RSExportRecordType::const_field_iterator I = ERT->fields_begin(),
E = ERT->fields_end();
I != E;
I++) {
const RSExportRecordType::Field *F = *I;
std::string FieldName = VarName + "." + F->getName();
if (InitIndex > Val.getVectorLength())
break;
genInitPrimitiveExportVariable(FieldName,
Val.getVectorElt(InitIndex++));
}
#endif
slangAssert(false && "Unsupported initializer for record/matrix/constant "
"array type variable currently");
break;
}
default: { slangAssert(false && "Unknown class of type"); }
}
}
void RSReflectionJava::genExportVariable(const RSExportVar *EV) {
const RSExportType *ET = EV->getType();
mOut.indent() << "private final static int " << RS_EXPORT_VAR_INDEX_PREFIX
<< EV->getName() << " = " << getNextExportVarSlot() << ";\n";
switch (ET->getClass()) {
case RSExportType::ExportClassPrimitive: {
genPrimitiveTypeExportVariable(EV);
break;
}
case RSExportType::ExportClassPointer: {
genPointerTypeExportVariable(EV);
break;
}
case RSExportType::ExportClassVector: {
genVectorTypeExportVariable(EV);
break;
}
case RSExportType::ExportClassMatrix: {
genMatrixTypeExportVariable(EV);
break;
}
case RSExportType::ExportClassConstantArray: {
genConstantArrayTypeExportVariable(EV);
break;
}
case RSExportType::ExportClassRecord: {
genRecordTypeExportVariable(EV);
break;
}
default: { slangAssert(false && "Unknown class of type"); }
}
}
void RSReflectionJava::genExportFunction(const RSExportFunc *EF) {
mOut.indent() << "private final static int " << RS_EXPORT_FUNC_INDEX_PREFIX
<< EF->getName() << " = " << getNextExportFuncSlot() << ";\n";
// invoke_*()
ArgTy Args;
if (EF->hasParam()) {
for (RSExportFunc::const_param_iterator I = EF->params_begin(),
E = EF->params_end();
I != E; I++) {
Args.push_back(
std::make_pair(GetTypeName((*I)->getType()), (*I)->getName()));
}
}
startFunction(AM_Public, false, "void",
"invoke_" + EF->getName(/*Mangle=*/false),
// We are using un-mangled name since Java
// supports method overloading.
Args);
if (!EF->hasParam()) {
mOut.indent() << "invoke(" << RS_EXPORT_FUNC_INDEX_PREFIX << EF->getName()
<< ");\n";
} else {
const RSExportRecordType *ERT = EF->getParamPacketType();
std::string FieldPackerName = EF->getName() + "_fp";
if (genCreateFieldPacker(ERT, FieldPackerName.c_str()))
genPackVarOfType(ERT, NULL, FieldPackerName.c_str());
mOut.indent() << "invoke(" << RS_EXPORT_FUNC_INDEX_PREFIX << EF->getName()
<< ", " << FieldPackerName << ");\n";
}
endFunction();
}
void RSReflectionJava::genPairwiseDimCheck(std::string name0,
std::string name1) {
mOut.indent() << "// Verify dimensions\n";
mOut.indent() << "t0 = " << name0 << ".getType();\n";
mOut.indent() << "t1 = " << name1 << ".getType();\n";
mOut.indent() << "if ((t0.getCount() != t1.getCount()) ||\n";
mOut.indent() << " (t0.getX() != t1.getX()) ||\n";
mOut.indent() << " (t0.getY() != t1.getY()) ||\n";
mOut.indent() << " (t0.getZ() != t1.getZ()) ||\n";
mOut.indent() << " (t0.hasFaces() != t1.hasFaces()) ||\n";
mOut.indent() << " (t0.hasMipmaps() != t1.hasMipmaps())) {\n";
mOut.indent() << " throw new RSRuntimeException(\"Dimension mismatch "
<< "between parameters " << name0 << " and " << name1
<< "!\");\n";
mOut.indent() << "}\n\n";
}
void RSReflectionJava::genExportForEach(const RSExportForEach *EF) {
if (EF->isDummyRoot()) {
// Skip reflection for dummy root() kernels. Note that we have to
// advance the next slot number for ForEach, however.
mOut.indent() << "//private final static int "
<< RS_EXPORT_FOREACH_INDEX_PREFIX << EF->getName() << " = "
<< getNextExportForEachSlot() << ";\n";
return;
}
mOut.indent() << "private final static int " << RS_EXPORT_FOREACH_INDEX_PREFIX
<< EF->getName() << " = " << getNextExportForEachSlot()
<< ";\n";
// forEach_*()
ArgTy Args;
slangAssert(EF->getNumParameters() > 0 || EF->hasReturn());
const RSExportForEach::InVec &Ins = EF->getIns();
const RSExportForEach::InTypeVec &InTypes = EF->getInTypes();
const RSExportType *OET = EF->getOutType();
if (Ins.size() == 1) {
Args.push_back(std::make_pair("Allocation", "ain"));
} else if (Ins.size() > 1) {
for (RSExportForEach::InIter BI = Ins.begin(), EI = Ins.end(); BI != EI;
BI++) {
Args.push_back(std::make_pair("Allocation",
"ain_" + (*BI)->getName().str()));
}
}
if (EF->hasOut() || EF->hasReturn())
Args.push_back(std::make_pair("Allocation", "aout"));
const RSExportRecordType *ERT = EF->getParamPacketType();
if (ERT) {
for (RSExportForEach::const_param_iterator I = EF->params_begin(),
E = EF->params_end();
I != E; I++) {
Args.push_back(
std::make_pair(GetTypeName((*I)->getType()), (*I)->getName()));
}
}
if (mRSContext->getTargetAPI() >= SLANG_JB_MR1_TARGET_API) {
startFunction(AM_Public, false, "Script.KernelID",
"getKernelID_" + EF->getName(), 0);
// TODO: add element checking
mOut.indent() << "return createKernelID(" << RS_EXPORT_FOREACH_INDEX_PREFIX
<< EF->getName() << ", " << EF->getSignatureMetadata()
<< ", null, null);\n";
endFunction();
}
if (mRSContext->getTargetAPI() >= SLANG_JB_MR2_TARGET_API) {
startFunction(AM_Public, false, "void", "forEach_" + EF->getName(), Args);
mOut.indent() << "forEach_" << EF->getName();
mOut << "(";
if (Ins.size() == 1) {
mOut << "ain, ";
} else if (Ins.size() > 1) {
for (RSExportForEach::InIter BI = Ins.begin(), EI = Ins.end(); BI != EI;
BI++) {
mOut << "ain_" << (*BI)->getName().str() << ", ";
}
}
if (EF->hasOut() || EF->hasReturn()) {
mOut << "aout, ";
}
if (EF->hasUsrData()) {
mOut << Args.back().second << ", ";
}
// No clipped bounds to pass in.
mOut << "null);\n";
endFunction();
// Add the clipped kernel parameters to the Args list.
Args.push_back(std::make_pair("Script.LaunchOptions", "sc"));
}
startFunction(AM_Public, false, "void", "forEach_" + EF->getName(), Args);
if (InTypes.size() == 1) {
if (InTypes.front() != NULL) {
genTypeCheck(InTypes.front(), "ain");
}
} else if (InTypes.size() > 1) {
size_t Index = 0;
for (RSExportForEach::InTypeIter BI = InTypes.begin(), EI = InTypes.end();
BI != EI; BI++, ++Index) {
if (*BI != NULL) {
genTypeCheck(*BI, ("ain_" + Ins[Index]->getName()).str().c_str());
}
}
}
if (OET) {
genTypeCheck(OET, "aout");
}
if (Ins.size() == 1 && (EF->hasOut() || EF->hasReturn())) {
mOut.indent() << "Type t0, t1;";
genPairwiseDimCheck("ain", "aout");
} else if (Ins.size() > 1) {
mOut.indent() << "Type t0, t1;";
std::string In0Name = "ain_" + Ins[0]->getName().str();
for (size_t index = 1; index < Ins.size(); ++index) {
genPairwiseDimCheck(In0Name, "ain_" + Ins[index]->getName().str());
}
if (EF->hasOut() || EF->hasReturn()) {
genPairwiseDimCheck(In0Name, "aout");
}
}
std::string FieldPackerName = EF->getName() + "_fp";
if (ERT) {
if (genCreateFieldPacker(ERT, FieldPackerName.c_str())) {
genPackVarOfType(ERT, NULL, FieldPackerName.c_str());
}
}
mOut.indent() << "forEach(" << RS_EXPORT_FOREACH_INDEX_PREFIX
<< EF->getName();
if (Ins.size() == 1) {
mOut << ", ain";
} else if (Ins.size() > 1) {
mOut << ", new Allocation[]{ain_" << Ins[0]->getName().str();
for (size_t index = 1; index < Ins.size(); ++index) {
mOut << ", ain_" << Ins[index]->getName().str();
}
mOut << "}";
} else {
mOut << ", (Allocation) null";
}
if (EF->hasOut() || EF->hasReturn())
mOut << ", aout";
else
mOut << ", null";
if (EF->hasUsrData())
mOut << ", " << FieldPackerName;
else
mOut << ", null";
if (mRSContext->getTargetAPI() >= SLANG_JB_MR2_TARGET_API) {
mOut << ", sc);\n";
} else {
mOut << ");\n";
}
endFunction();
}
void RSReflectionJava::genTypeInstanceFromPointer(const RSExportType *ET) {
if (ET->getClass() == RSExportType::ExportClassPointer) {
// For pointer parameters to original forEach kernels.
const RSExportPointerType *EPT =
static_cast<const RSExportPointerType *>(ET);
genTypeInstance(EPT->getPointeeType());
} else {
// For handling pass-by-value kernel parameters.
genTypeInstance(ET);
}
}
void RSReflectionJava::genTypeInstance(const RSExportType *ET) {
switch (ET->getClass()) {
case RSExportType::ExportClassPrimitive:
case RSExportType::ExportClassVector:
case RSExportType::ExportClassConstantArray: {
std::string TypeName = ET->getElementName();
if (addTypeNameForElement(TypeName)) {
mOut.indent() << RS_ELEM_PREFIX << TypeName << " = Element." << TypeName
<< "(rs);\n";
}
break;
}
case RSExportType::ExportClassRecord: {
std::string ClassName = ET->getElementName();
if (addTypeNameForElement(ClassName)) {
mOut.indent() << RS_ELEM_PREFIX << ClassName << " = " << ClassName
<< ".createElement(rs);\n";
}
break;
}
default:
break;
}
}
void RSReflectionJava::genFieldPackerInstance(const RSExportType *ET) {
switch (ET->getClass()) {
case RSExportType::ExportClassPrimitive:
case RSExportType::ExportClassVector:
case RSExportType::ExportClassConstantArray:
case RSExportType::ExportClassRecord: {
std::string TypeName = ET->getElementName();
addTypeNameForFieldPacker(TypeName);
break;
}
default:
break;
}
}
void RSReflectionJava::genTypeCheck(const RSExportType *ET,
const char *VarName) {
mOut.indent() << "// check " << VarName << "\n";
if (ET->getClass() == RSExportType::ExportClassPointer) {
const RSExportPointerType *EPT =
static_cast<const RSExportPointerType *>(ET);
ET = EPT->getPointeeType();
}
std::string TypeName;
switch (ET->getClass()) {
case RSExportType::ExportClassPrimitive:
case RSExportType::ExportClassVector:
case RSExportType::ExportClassRecord: {
TypeName = ET->getElementName();
break;
}
default:
break;
}
if (!TypeName.empty()) {
mOut.indent() << "if (!" << VarName
<< ".getType().getElement().isCompatible(" RS_ELEM_PREFIX
<< TypeName << ")) {\n";
mOut.indent() << " throw new RSRuntimeException(\"Type mismatch with "
<< TypeName << "!\");\n";
mOut.indent() << "}\n";
}
}
void RSReflectionJava::genPrimitiveTypeExportVariable(const RSExportVar *EV) {
slangAssert(
(EV->getType()->getClass() == RSExportType::ExportClassPrimitive) &&
"Variable should be type of primitive here");
const RSExportPrimitiveType *EPT =
static_cast<const RSExportPrimitiveType *>(EV->getType());
std::string TypeName = GetTypeName(EPT);
std::string VarName = EV->getName();
genPrivateExportVariable(TypeName, EV->getName());
if (EV->isConst()) {
mOut.indent() << "public final static " << TypeName
<< " " RS_EXPORT_VAR_CONST_PREFIX << VarName << " = ";
const clang::APValue &Val = EV->getInit();
genInitValue(Val, EPT->getType() == DataTypeBoolean);
mOut << ";\n";
} else {
// set_*()
// This must remain synchronized, since multiple Dalvik threads may
// be calling setters.
startFunction(AM_PublicSynchronized, false, "void", "set_" + VarName, 1,
TypeName.c_str(), "v");
if ((EPT->getSize() < 4) || EV->isUnsigned()) {
// We create/cache a per-type FieldPacker. This allows us to reuse the
// validation logic (for catching negative inputs from Dalvik, as well
// as inputs that are too large to be represented in the unsigned type).
// Sub-integer types are also handled specially here, so that we don't
// overwrite bytes accidentally.
std::string ElemName = EPT->getElementName();
std::string FPName;
FPName = RS_FP_PREFIX + ElemName;
mOut.indent() << "if (" << FPName << "!= null) {\n";
mOut.increaseIndent();
mOut.indent() << FPName << ".reset();\n";
mOut.decreaseIndent();
mOut.indent() << "} else {\n";
mOut.increaseIndent();
mOut.indent() << FPName << " = new FieldPacker(" << EPT->getSize()
<< ");\n";
mOut.decreaseIndent();
mOut.indent() << "}\n";
genPackVarOfType(EPT, "v", FPName.c_str());
mOut.indent() << "setVar(" << RS_EXPORT_VAR_INDEX_PREFIX << VarName
<< ", " << FPName << ");\n";
} else {
mOut.indent() << "setVar(" << RS_EXPORT_VAR_INDEX_PREFIX << VarName
<< ", v);\n";
}
// Dalvik update comes last, since the input may be invalid (and hence
// throw an exception).
mOut.indent() << RS_EXPORT_VAR_PREFIX << VarName << " = v;\n";
endFunction();
}
genGetExportVariable(TypeName, VarName);
genGetFieldID(VarName);
}
void RSReflectionJava::genInitValue(const clang::APValue &Val, bool asBool) {
switch (Val.getKind()) {