slang_rs_reflection.cpp revision 3a38b7489d016b07e5b95a1e04ccfe9064b3438f
1 2/* 3 * Copyright 2010-2014, The Android Open Source Project 4 * 5 * Licensed under the Apache License, Version 2.0 (the "License"); 6 * you may not use this file except in compliance with the License. 7 * You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 18#include "slang_rs_reflection.h" 19 20#include <sys/stat.h> 21 22#include <cstdarg> 23#include <cctype> 24 25#include <algorithm> 26#include <sstream> 27#include <string> 28#include <utility> 29 30#include "llvm/ADT/APFloat.h" 31#include "llvm/ADT/StringExtras.h" 32 33#include "os_sep.h" 34#include "slang_rs_context.h" 35#include "slang_rs_export_var.h" 36#include "slang_rs_export_foreach.h" 37#include "slang_rs_export_func.h" 38#include "slang_rs_reflect_utils.h" 39#include "slang_version.h" 40#include "slang_utils.h" 41 42#define RS_SCRIPT_CLASS_NAME_PREFIX "ScriptC_" 43#define RS_SCRIPT_CLASS_SUPER_CLASS_NAME "ScriptC" 44 45#define RS_TYPE_CLASS_SUPER_CLASS_NAME ".Script.FieldBase" 46 47#define RS_TYPE_ITEM_CLASS_NAME "Item" 48 49#define RS_TYPE_ITEM_SIZEOF_LEGACY "Item.sizeof" 50#define RS_TYPE_ITEM_SIZEOF_CURRENT "mElement.getBytesSize()" 51 52#define RS_TYPE_ITEM_BUFFER_NAME "mItemArray" 53#define RS_TYPE_ITEM_BUFFER_PACKER_NAME "mIOBuffer" 54#define RS_TYPE_ELEMENT_REF_NAME "mElementCache" 55 56#define RS_EXPORT_VAR_INDEX_PREFIX "mExportVarIdx_" 57#define RS_EXPORT_VAR_PREFIX "mExportVar_" 58#define RS_EXPORT_VAR_ELEM_PREFIX "mExportVarElem_" 59#define RS_EXPORT_VAR_DIM_PREFIX "mExportVarDim_" 60#define RS_EXPORT_VAR_CONST_PREFIX "const_" 61 62#define RS_ELEM_PREFIX "__" 63 64#define RS_FP_PREFIX "__rs_fp_" 65 66#define RS_RESOURCE_NAME "__rs_resource_name" 67 68#define RS_EXPORT_FUNC_INDEX_PREFIX "mExportFuncIdx_" 69#define RS_EXPORT_FOREACH_INDEX_PREFIX "mExportForEachIdx_" 70 71#define RS_EXPORT_VAR_ALLOCATION_PREFIX "mAlloction_" 72#define RS_EXPORT_VAR_DATA_STORAGE_PREFIX "mData_" 73 74namespace slang { 75 76class RSReflectionJavaElementBuilder { 77public: 78 RSReflectionJavaElementBuilder(const char *ElementBuilderName, 79 const RSExportRecordType *ERT, 80 const char *RenderScriptVar, 81 GeneratedFile *Out, const RSContext *RSContext, 82 RSReflectionJava *Reflection); 83 void generate(); 84 85private: 86 void genAddElement(const RSExportType *ET, const std::string &VarName, 87 unsigned ArraySize); 88 void genAddStatementStart(); 89 void genAddStatementEnd(const std::string &VarName, unsigned ArraySize); 90 void genAddPadding(int PaddingSize); 91 // TODO Will remove later due to field name information is not necessary for 92 // C-reflect-to-Java 93 std::string createPaddingField() { 94 return mPaddingPrefix + llvm::itostr(mPaddingFieldIndex++); 95 } 96 97 const char *mElementBuilderName; 98 const RSExportRecordType *mERT; 99 const char *mRenderScriptVar; 100 GeneratedFile *mOut; 101 std::string mPaddingPrefix; 102 int mPaddingFieldIndex; 103 const RSContext *mRSContext; 104 RSReflectionJava *mReflection; 105}; 106 107static const char *GetMatrixTypeName(const RSExportMatrixType *EMT) { 108 static const char *MatrixTypeJavaNameMap[] = {/* 2x2 */ "Matrix2f", 109 /* 3x3 */ "Matrix3f", 110 /* 4x4 */ "Matrix4f", 111 }; 112 unsigned Dim = EMT->getDim(); 113 114 if ((Dim - 2) < (sizeof(MatrixTypeJavaNameMap) / sizeof(const char *))) 115 return MatrixTypeJavaNameMap[EMT->getDim() - 2]; 116 117 slangAssert(false && "GetMatrixTypeName : Unsupported matrix dimension"); 118 return NULL; 119} 120 121static const char *GetVectorAccessor(unsigned Index) { 122 static const char *VectorAccessorMap[] = {/* 0 */ "x", 123 /* 1 */ "y", 124 /* 2 */ "z", 125 /* 3 */ "w", 126 }; 127 128 slangAssert((Index < (sizeof(VectorAccessorMap) / sizeof(const char *))) && 129 "Out-of-bound index to access vector member"); 130 131 return VectorAccessorMap[Index]; 132} 133 134static const char *GetPackerAPIName(const RSExportPrimitiveType *EPT) { 135 static const char *PrimitiveTypePackerAPINameMap[] = { 136 "", // DataTypeFloat16 137 "addF32", // DataTypeFloat32 138 "addF64", // DataTypeFloat64 139 "addI8", // DataTypeSigned8 140 "addI16", // DataTypeSigned16 141 "addI32", // DataTypeSigned32 142 "addI64", // DataTypeSigned64 143 "addU8", // DataTypeUnsigned8 144 "addU16", // DataTypeUnsigned16 145 "addU32", // DataTypeUnsigned32 146 "addU64", // DataTypeUnsigned64 147 "addBoolean", // DataTypeBoolean 148 "addU16", // DataTypeUnsigned565 149 "addU16", // DataTypeUnsigned5551 150 "addU16", // DataTypeUnsigned4444 151 "addMatrix", // DataTypeRSMatrix2x2 152 "addMatrix", // DataTypeRSMatrix3x3 153 "addMatrix", // DataTypeRSMatrix4x4 154 "addObj", // DataTypeRSElement 155 "addObj", // DataTypeRSType 156 "addObj", // DataTypeRSAllocation 157 "addObj", // DataTypeRSSampler 158 "addObj", // DataTypeRSScript 159 "addObj", // DataTypeRSMesh 160 "addObj", // DataTypeRSPath 161 "addObj", // DataTypeRSProgramFragment 162 "addObj", // DataTypeRSProgramVertex 163 "addObj", // DataTypeRSProgramRaster 164 "addObj", // DataTypeRSProgramStore 165 "addObj", // DataTypeRSFont 166 }; 167 unsigned TypeId = EPT->getType(); 168 169 if (TypeId < (sizeof(PrimitiveTypePackerAPINameMap) / sizeof(const char *))) 170 return PrimitiveTypePackerAPINameMap[EPT->getType()]; 171 172 slangAssert(false && "GetPackerAPIName : Unknown primitive data type"); 173 return NULL; 174} 175 176static std::string GetTypeName(const RSExportType *ET, bool Brackets = true) { 177 switch (ET->getClass()) { 178 case RSExportType::ExportClassPrimitive: { 179 return RSExportPrimitiveType::getRSReflectionType( 180 static_cast<const RSExportPrimitiveType *>(ET))->java_name; 181 } 182 case RSExportType::ExportClassPointer: { 183 const RSExportType *PointeeType = 184 static_cast<const RSExportPointerType *>(ET)->getPointeeType(); 185 186 if (PointeeType->getClass() != RSExportType::ExportClassRecord) 187 return "Allocation"; 188 else 189 return PointeeType->getElementName(); 190 } 191 case RSExportType::ExportClassVector: { 192 const RSExportVectorType *EVT = static_cast<const RSExportVectorType *>(ET); 193 std::stringstream VecName; 194 VecName << EVT->getRSReflectionType(EVT)->rs_java_vector_prefix 195 << EVT->getNumElement(); 196 return VecName.str(); 197 } 198 case RSExportType::ExportClassMatrix: { 199 return GetMatrixTypeName(static_cast<const RSExportMatrixType *>(ET)); 200 } 201 case RSExportType::ExportClassConstantArray: { 202 const RSExportConstantArrayType *CAT = 203 static_cast<const RSExportConstantArrayType *>(ET); 204 std::string ElementTypeName = GetTypeName(CAT->getElementType()); 205 if (Brackets) { 206 ElementTypeName.append("[]"); 207 } 208 return ElementTypeName; 209 } 210 case RSExportType::ExportClassRecord: { 211 return ET->getElementName() + "." RS_TYPE_ITEM_CLASS_NAME; 212 } 213 default: { slangAssert(false && "Unknown class of type"); } 214 } 215 216 return ""; 217} 218 219static const char *GetTypeNullValue(const RSExportType *ET) { 220 switch (ET->getClass()) { 221 case RSExportType::ExportClassPrimitive: { 222 const RSExportPrimitiveType *EPT = 223 static_cast<const RSExportPrimitiveType *>(ET); 224 if (EPT->isRSObjectType()) 225 return "null"; 226 else if (EPT->getType() == DataTypeBoolean) 227 return "false"; 228 else 229 return "0"; 230 break; 231 } 232 case RSExportType::ExportClassPointer: 233 case RSExportType::ExportClassVector: 234 case RSExportType::ExportClassMatrix: 235 case RSExportType::ExportClassConstantArray: 236 case RSExportType::ExportClassRecord: { 237 return "null"; 238 break; 239 } 240 default: { slangAssert(false && "Unknown class of type"); } 241 } 242 return ""; 243} 244 245static std::string GetBuiltinElementConstruct(const RSExportType *ET) { 246 if (ET->getClass() == RSExportType::ExportClassPrimitive) { 247 return std::string("Element.") + ET->getElementName(); 248 } else if (ET->getClass() == RSExportType::ExportClassVector) { 249 const RSExportVectorType *EVT = static_cast<const RSExportVectorType *>(ET); 250 if (EVT->getType() == DataTypeFloat32) { 251 if (EVT->getNumElement() == 2) { 252 return "Element.F32_2"; 253 } else if (EVT->getNumElement() == 3) { 254 return "Element.F32_3"; 255 } else if (EVT->getNumElement() == 4) { 256 return "Element.F32_4"; 257 } else { 258 slangAssert(false && "Vectors should be size 2, 3, 4"); 259 } 260 } else if (EVT->getType() == DataTypeUnsigned8) { 261 if (EVT->getNumElement() == 4) 262 return "Element.U8_4"; 263 } 264 } else if (ET->getClass() == RSExportType::ExportClassMatrix) { 265 const RSExportMatrixType *EMT = static_cast<const RSExportMatrixType *>(ET); 266 switch (EMT->getDim()) { 267 case 2: 268 return "Element.MATRIX_2X2"; 269 case 3: 270 return "Element.MATRIX_3X3"; 271 case 4: 272 return "Element.MATRIX_4X4"; 273 default: 274 slangAssert(false && "Unsupported dimension of matrix"); 275 } 276 } 277 // RSExportType::ExportClassPointer can't be generated in a struct. 278 279 return ""; 280} 281 282/********************** Methods to generate script class **********************/ 283RSReflectionJava::RSReflectionJava(const RSContext *Context, 284 std::vector<std::string> *GeneratedFileNames, 285 const std::string &OutputBaseDirectory, 286 const std::string &RSSourceFileName, 287 const std::string &BitCodeFileName, 288 bool EmbedBitcodeInJava) 289 : mRSContext(Context), mPackageName(Context->getReflectJavaPackageName()), 290 mRSPackageName(Context->getRSPackageName()), 291 mOutputBaseDirectory(OutputBaseDirectory), 292 mRSSourceFileName(RSSourceFileName), mBitCodeFileName(BitCodeFileName), 293 mResourceId(RSSlangReflectUtils::JavaClassNameFromRSFileName( 294 mBitCodeFileName.c_str())), 295 mScriptClassName(RS_SCRIPT_CLASS_NAME_PREFIX + 296 RSSlangReflectUtils::JavaClassNameFromRSFileName( 297 mRSSourceFileName.c_str())), 298 mEmbedBitcodeInJava(EmbedBitcodeInJava), mNextExportVarSlot(0), 299 mNextExportFuncSlot(0), mNextExportForEachSlot(0), mLastError(""), 300 mGeneratedFileNames(GeneratedFileNames), mFieldIndex(0) { 301 slangAssert(mGeneratedFileNames && "Must supply GeneratedFileNames"); 302 slangAssert(!mPackageName.empty() && mPackageName != "-"); 303 304 mOutputDirectory = RSSlangReflectUtils::ComputePackagedPath( 305 OutputBaseDirectory.c_str(), mPackageName.c_str()) + 306 OS_PATH_SEPARATOR_STR; 307 308 // mElement.getBytesSize only exists on JB+ 309 if (mRSContext->getTargetAPI() >= SLANG_JB_TARGET_API) { 310 mItemSizeof = RS_TYPE_ITEM_SIZEOF_CURRENT; 311 } else { 312 mItemSizeof = RS_TYPE_ITEM_SIZEOF_LEGACY; 313 } 314} 315 316bool RSReflectionJava::genScriptClass(const std::string &ClassName, 317 std::string &ErrorMsg) { 318 if (!startClass(AM_Public, false, ClassName, RS_SCRIPT_CLASS_SUPER_CLASS_NAME, 319 ErrorMsg)) 320 return false; 321 322 genScriptClassConstructor(); 323 324 // Reflect export variable 325 for (RSContext::const_export_var_iterator I = mRSContext->export_vars_begin(), 326 E = mRSContext->export_vars_end(); 327 I != E; I++) 328 genExportVariable(*I); 329 330 // Reflect export for each functions (only available on ICS+) 331 if (mRSContext->getTargetAPI() >= SLANG_ICS_TARGET_API) { 332 for (RSContext::const_export_foreach_iterator 333 I = mRSContext->export_foreach_begin(), 334 E = mRSContext->export_foreach_end(); 335 I != E; I++) 336 genExportForEach(*I); 337 } 338 339 // Reflect export function 340 for (RSContext::const_export_func_iterator 341 I = mRSContext->export_funcs_begin(), 342 E = mRSContext->export_funcs_end(); 343 I != E; I++) 344 genExportFunction(*I); 345 346 endClass(); 347 348 return true; 349} 350 351void RSReflectionJava::genScriptClassConstructor() { 352 std::string className(RSSlangReflectUtils::JavaBitcodeClassNameFromRSFileName( 353 mRSSourceFileName.c_str())); 354 // Provide a simple way to reference this object. 355 mOut.indent() << "private static final String " RS_RESOURCE_NAME " = \"" 356 << getResourceId() << "\";\n"; 357 358 // Generate a simple constructor with only a single parameter (the rest 359 // can be inferred from information we already have). 360 mOut.indent() << "// Constructor\n"; 361 startFunction(AM_Public, false, NULL, getClassName(), 1, "RenderScript", 362 "rs"); 363 364 if (getEmbedBitcodeInJava()) { 365 // Call new single argument Java-only constructor 366 mOut.indent() << "super(rs,\n"; 367 mOut.indent() << " " << RS_RESOURCE_NAME ",\n"; 368 mOut.indent() << " " << className << ".getBitCode32(),\n"; 369 // TODO(srhines): Replace the extra BitCode32 with Bitcode64 here! 370 // mOut.indent() << " " << className << ".getBitCode64());\n"; 371 mOut.indent() << " " << className << ".getBitCode32());\n"; 372 } else { 373 // Call alternate constructor with required parameters. 374 // Look up the proper raw bitcode resource id via the context. 375 mOut.indent() << "this(rs,\n"; 376 mOut.indent() << " rs.getApplicationContext().getResources(),\n"; 377 mOut.indent() << " rs.getApplicationContext().getResources()." 378 "getIdentifier(\n"; 379 mOut.indent() << " " RS_RESOURCE_NAME ", \"raw\",\n"; 380 mOut.indent() 381 << " rs.getApplicationContext().getPackageName()));\n"; 382 endFunction(); 383 384 // Alternate constructor (legacy) with 3 original parameters. 385 startFunction(AM_Public, false, NULL, getClassName(), 3, "RenderScript", 386 "rs", "Resources", "resources", "int", "id"); 387 // Call constructor of super class 388 mOut.indent() << "super(rs, resources, id);\n"; 389 } 390 391 // If an exported variable has initial value, reflect it 392 393 for (RSContext::const_export_var_iterator I = mRSContext->export_vars_begin(), 394 E = mRSContext->export_vars_end(); 395 I != E; I++) { 396 const RSExportVar *EV = *I; 397 if (!EV->getInit().isUninit()) { 398 genInitExportVariable(EV->getType(), EV->getName(), EV->getInit()); 399 } else if (EV->getArraySize()) { 400 // Always create an initial zero-init array object. 401 mOut.indent() << RS_EXPORT_VAR_PREFIX << EV->getName() << " = new " 402 << GetTypeName(EV->getType(), false) << "[" 403 << EV->getArraySize() << "];\n"; 404 size_t NumInits = EV->getNumInits(); 405 const RSExportConstantArrayType *ECAT = 406 static_cast<const RSExportConstantArrayType *>(EV->getType()); 407 const RSExportType *ET = ECAT->getElementType(); 408 for (size_t i = 0; i < NumInits; i++) { 409 std::stringstream Name; 410 Name << EV->getName() << "[" << i << "]"; 411 genInitExportVariable(ET, Name.str(), EV->getInitArray(i)); 412 } 413 } 414 if (mRSContext->getTargetAPI() >= SLANG_JB_TARGET_API) { 415 genTypeInstance(EV->getType()); 416 } 417 genFieldPackerInstance(EV->getType()); 418 } 419 420 for (RSContext::const_export_foreach_iterator 421 I = mRSContext->export_foreach_begin(), 422 E = mRSContext->export_foreach_end(); 423 I != E; I++) { 424 const RSExportForEach *EF = *I; 425 426 const RSExportType *IET = EF->getInType(); 427 if (IET) { 428 genTypeInstanceFromPointer(IET); 429 } 430 const RSExportType *OET = EF->getOutType(); 431 if (OET) { 432 genTypeInstanceFromPointer(OET); 433 } 434 } 435 436 endFunction(); 437 438 for (std::set<std::string>::iterator I = mTypesToCheck.begin(), 439 E = mTypesToCheck.end(); 440 I != E; I++) { 441 mOut.indent() << "private Element " RS_ELEM_PREFIX << *I << ";\n"; 442 } 443 444 for (std::set<std::string>::iterator I = mFieldPackerTypes.begin(), 445 E = mFieldPackerTypes.end(); 446 I != E; I++) { 447 mOut.indent() << "private FieldPacker " RS_FP_PREFIX << *I << ";\n"; 448 } 449} 450 451void RSReflectionJava::genInitBoolExportVariable(const std::string &VarName, 452 const clang::APValue &Val) { 453 slangAssert(!Val.isUninit() && "Not a valid initializer"); 454 slangAssert((Val.getKind() == clang::APValue::Int) && 455 "Bool type has wrong initial APValue"); 456 457 mOut.indent() << RS_EXPORT_VAR_PREFIX << VarName << " = "; 458 459 mOut << ((Val.getInt().getSExtValue() == 0) ? "false" : "true") << ";\n"; 460} 461 462void 463RSReflectionJava::genInitPrimitiveExportVariable(const std::string &VarName, 464 const clang::APValue &Val) { 465 slangAssert(!Val.isUninit() && "Not a valid initializer"); 466 467 mOut.indent() << RS_EXPORT_VAR_PREFIX << VarName << " = "; 468 genInitValue(Val, false); 469 mOut << ";\n"; 470} 471 472void RSReflectionJava::genInitExportVariable(const RSExportType *ET, 473 const std::string &VarName, 474 const clang::APValue &Val) { 475 slangAssert(!Val.isUninit() && "Not a valid initializer"); 476 477 switch (ET->getClass()) { 478 case RSExportType::ExportClassPrimitive: { 479 const RSExportPrimitiveType *EPT = 480 static_cast<const RSExportPrimitiveType *>(ET); 481 if (EPT->getType() == DataTypeBoolean) { 482 genInitBoolExportVariable(VarName, Val); 483 } else { 484 genInitPrimitiveExportVariable(VarName, Val); 485 } 486 break; 487 } 488 case RSExportType::ExportClassPointer: { 489 if (!Val.isInt() || Val.getInt().getSExtValue() != 0) 490 std::cout << "Initializer which is non-NULL to pointer type variable " 491 "will be ignored\n"; 492 break; 493 } 494 case RSExportType::ExportClassVector: { 495 const RSExportVectorType *EVT = static_cast<const RSExportVectorType *>(ET); 496 switch (Val.getKind()) { 497 case clang::APValue::Int: 498 case clang::APValue::Float: { 499 for (unsigned i = 0; i < EVT->getNumElement(); i++) { 500 std::string Name = VarName + "." + GetVectorAccessor(i); 501 genInitPrimitiveExportVariable(Name, Val); 502 } 503 break; 504 } 505 case clang::APValue::Vector: { 506 std::stringstream VecName; 507 VecName << EVT->getRSReflectionType(EVT)->rs_java_vector_prefix 508 << EVT->getNumElement(); 509 mOut.indent() << RS_EXPORT_VAR_PREFIX << VarName << " = new " 510 << VecName.str() << "();\n"; 511 512 unsigned NumElements = std::min( 513 static_cast<unsigned>(EVT->getNumElement()), Val.getVectorLength()); 514 for (unsigned i = 0; i < NumElements; i++) { 515 const clang::APValue &ElementVal = Val.getVectorElt(i); 516 std::string Name = VarName + "." + GetVectorAccessor(i); 517 genInitPrimitiveExportVariable(Name, ElementVal); 518 } 519 break; 520 } 521 case clang::APValue::MemberPointer: 522 case clang::APValue::Uninitialized: 523 case clang::APValue::ComplexInt: 524 case clang::APValue::ComplexFloat: 525 case clang::APValue::LValue: 526 case clang::APValue::Array: 527 case clang::APValue::Struct: 528 case clang::APValue::Union: 529 case clang::APValue::AddrLabelDiff: { 530 slangAssert(false && "Unexpected type of value of initializer."); 531 } 532 } 533 break; 534 } 535 // TODO(zonr): Resolving initializer of a record (and matrix) type variable 536 // is complex. It cannot obtain by just simply evaluating the initializer 537 // expression. 538 case RSExportType::ExportClassMatrix: 539 case RSExportType::ExportClassConstantArray: 540 case RSExportType::ExportClassRecord: { 541#if 0 542 unsigned InitIndex = 0; 543 const RSExportRecordType *ERT = 544 static_cast<const RSExportRecordType*>(ET); 545 546 slangAssert((Val.getKind() == clang::APValue::Vector) && 547 "Unexpected type of initializer for record type variable"); 548 549 mOut.indent() << RS_EXPORT_VAR_PREFIX << VarName 550 << " = new " << ERT->getElementName() 551 << "." RS_TYPE_ITEM_CLASS_NAME"();\n"; 552 553 for (RSExportRecordType::const_field_iterator I = ERT->fields_begin(), 554 E = ERT->fields_end(); 555 I != E; 556 I++) { 557 const RSExportRecordType::Field *F = *I; 558 std::string FieldName = VarName + "." + F->getName(); 559 560 if (InitIndex > Val.getVectorLength()) 561 break; 562 563 genInitPrimitiveExportVariable(FieldName, 564 Val.getVectorElt(InitIndex++)); 565 } 566#endif 567 slangAssert(false && "Unsupported initializer for record/matrix/constant " 568 "array type variable currently"); 569 break; 570 } 571 default: { slangAssert(false && "Unknown class of type"); } 572 } 573} 574 575void RSReflectionJava::genExportVariable(const RSExportVar *EV) { 576 const RSExportType *ET = EV->getType(); 577 578 mOut.indent() << "private final static int " << RS_EXPORT_VAR_INDEX_PREFIX 579 << EV->getName() << " = " << getNextExportVarSlot() << ";\n"; 580 581 switch (ET->getClass()) { 582 case RSExportType::ExportClassPrimitive: { 583 genPrimitiveTypeExportVariable(EV); 584 break; 585 } 586 case RSExportType::ExportClassPointer: { 587 genPointerTypeExportVariable(EV); 588 break; 589 } 590 case RSExportType::ExportClassVector: { 591 genVectorTypeExportVariable(EV); 592 break; 593 } 594 case RSExportType::ExportClassMatrix: { 595 genMatrixTypeExportVariable(EV); 596 break; 597 } 598 case RSExportType::ExportClassConstantArray: { 599 genConstantArrayTypeExportVariable(EV); 600 break; 601 } 602 case RSExportType::ExportClassRecord: { 603 genRecordTypeExportVariable(EV); 604 break; 605 } 606 default: { slangAssert(false && "Unknown class of type"); } 607 } 608} 609 610void RSReflectionJava::genExportFunction(const RSExportFunc *EF) { 611 mOut.indent() << "private final static int " << RS_EXPORT_FUNC_INDEX_PREFIX 612 << EF->getName() << " = " << getNextExportFuncSlot() << ";\n"; 613 614 // invoke_*() 615 ArgTy Args; 616 617 if (EF->hasParam()) { 618 for (RSExportFunc::const_param_iterator I = EF->params_begin(), 619 E = EF->params_end(); 620 I != E; I++) { 621 Args.push_back( 622 std::make_pair(GetTypeName((*I)->getType()), (*I)->getName())); 623 } 624 } 625 626 startFunction(AM_Public, false, "void", 627 "invoke_" + EF->getName(/*Mangle=*/false), 628 // We are using un-mangled name since Java 629 // supports method overloading. 630 Args); 631 632 if (!EF->hasParam()) { 633 mOut.indent() << "invoke(" << RS_EXPORT_FUNC_INDEX_PREFIX << EF->getName() 634 << ");\n"; 635 } else { 636 const RSExportRecordType *ERT = EF->getParamPacketType(); 637 std::string FieldPackerName = EF->getName() + "_fp"; 638 639 if (genCreateFieldPacker(ERT, FieldPackerName.c_str())) 640 genPackVarOfType(ERT, NULL, FieldPackerName.c_str()); 641 642 mOut.indent() << "invoke(" << RS_EXPORT_FUNC_INDEX_PREFIX << EF->getName() 643 << ", " << FieldPackerName << ");\n"; 644 } 645 646 endFunction(); 647} 648 649void RSReflectionJava::genExportForEach(const RSExportForEach *EF) { 650 if (EF->isDummyRoot()) { 651 // Skip reflection for dummy root() kernels. Note that we have to 652 // advance the next slot number for ForEach, however. 653 mOut.indent() << "//private final static int " 654 << RS_EXPORT_FOREACH_INDEX_PREFIX << EF->getName() << " = " 655 << getNextExportForEachSlot() << ";\n"; 656 return; 657 } 658 659 mOut.indent() << "private final static int " << RS_EXPORT_FOREACH_INDEX_PREFIX 660 << EF->getName() << " = " << getNextExportForEachSlot() 661 << ";\n"; 662 663 // forEach_*() 664 ArgTy Args; 665 666 slangAssert(EF->getNumParameters() > 0 || EF->hasReturn()); 667 668 if (EF->hasIn()) 669 Args.push_back(std::make_pair("Allocation", "ain")); 670 if (EF->hasOut() || EF->hasReturn()) 671 Args.push_back(std::make_pair("Allocation", "aout")); 672 673 const RSExportRecordType *ERT = EF->getParamPacketType(); 674 if (ERT) { 675 for (RSExportForEach::const_param_iterator I = EF->params_begin(), 676 E = EF->params_end(); 677 I != E; I++) { 678 Args.push_back( 679 std::make_pair(GetTypeName((*I)->getType()), (*I)->getName())); 680 } 681 } 682 683 const RSExportType *IET = EF->getInType(); 684 const RSExportType *OET = EF->getOutType(); 685 686 if (mRSContext->getTargetAPI() >= SLANG_JB_MR1_TARGET_API) { 687 int signature = 0; 688 startFunction(AM_Public, false, "Script.KernelID", 689 "getKernelID_" + EF->getName(), 0); 690 691 if (IET) 692 signature |= 1; 693 if (OET) 694 signature |= 2; 695 696 // TODO: add element checking 697 mOut.indent() << "return createKernelID(" << RS_EXPORT_FOREACH_INDEX_PREFIX 698 << EF->getName() << ", " << signature << ", null, null);\n"; 699 700 endFunction(); 701 } 702 703 if (mRSContext->getTargetAPI() >= SLANG_JB_MR2_TARGET_API) { 704 startFunction(AM_Public, false, "void", "forEach_" + EF->getName(), Args); 705 706 mOut.indent() << "forEach_" << EF->getName(); 707 mOut << "("; 708 709 if (EF->hasIn()) { 710 mOut << "ain, "; 711 } 712 713 if (EF->hasOut() || EF->hasReturn()) { 714 mOut << "aout, "; 715 } 716 717 if (EF->hasUsrData()) { 718 mOut << Args.back().second << ", "; 719 } 720 721 // No clipped bounds to pass in. 722 mOut << "null);\n"; 723 724 endFunction(); 725 726 // Add the clipped kernel parameters to the Args list. 727 Args.push_back(std::make_pair("Script.LaunchOptions", "sc")); 728 } 729 730 startFunction(AM_Public, false, "void", "forEach_" + EF->getName(), Args); 731 732 if (IET) { 733 genTypeCheck(IET, "ain"); 734 } 735 if (OET) { 736 genTypeCheck(OET, "aout"); 737 } 738 739 if (EF->hasIn() && (EF->hasOut() || EF->hasReturn())) { 740 mOut.indent() << "// Verify dimensions\n"; 741 mOut.indent() << "Type tIn = ain.getType();\n"; 742 mOut.indent() << "Type tOut = aout.getType();\n"; 743 mOut.indent() << "if ((tIn.getCount() != tOut.getCount()) ||\n"; 744 mOut.indent() << " (tIn.getX() != tOut.getX()) ||\n"; 745 mOut.indent() << " (tIn.getY() != tOut.getY()) ||\n"; 746 mOut.indent() << " (tIn.getZ() != tOut.getZ()) ||\n"; 747 mOut.indent() << " (tIn.hasFaces() != tOut.hasFaces()) ||\n"; 748 mOut.indent() << " (tIn.hasMipmaps() != tOut.hasMipmaps())) {\n"; 749 mOut.indent() << " throw new RSRuntimeException(\"Dimension mismatch " 750 << "between input and output parameters!\");\n"; 751 mOut.indent() << "}\n"; 752 } 753 754 std::string FieldPackerName = EF->getName() + "_fp"; 755 if (ERT) { 756 if (genCreateFieldPacker(ERT, FieldPackerName.c_str())) { 757 genPackVarOfType(ERT, NULL, FieldPackerName.c_str()); 758 } 759 } 760 mOut.indent() << "forEach(" << RS_EXPORT_FOREACH_INDEX_PREFIX 761 << EF->getName(); 762 763 if (EF->hasIn()) 764 mOut << ", ain"; 765 else 766 mOut << ", null"; 767 768 if (EF->hasOut() || EF->hasReturn()) 769 mOut << ", aout"; 770 else 771 mOut << ", null"; 772 773 if (EF->hasUsrData()) 774 mOut << ", " << FieldPackerName; 775 else 776 mOut << ", null"; 777 778 if (mRSContext->getTargetAPI() >= SLANG_JB_MR2_TARGET_API) { 779 mOut << ", sc);\n"; 780 } else { 781 mOut << ");\n"; 782 } 783 784 endFunction(); 785} 786 787void RSReflectionJava::genTypeInstanceFromPointer(const RSExportType *ET) { 788 if (ET->getClass() == RSExportType::ExportClassPointer) { 789 // For pointer parameters to original forEach kernels. 790 const RSExportPointerType *EPT = 791 static_cast<const RSExportPointerType *>(ET); 792 genTypeInstance(EPT->getPointeeType()); 793 } else { 794 // For handling pass-by-value kernel parameters. 795 genTypeInstance(ET); 796 } 797} 798 799void RSReflectionJava::genTypeInstance(const RSExportType *ET) { 800 switch (ET->getClass()) { 801 case RSExportType::ExportClassPrimitive: 802 case RSExportType::ExportClassVector: 803 case RSExportType::ExportClassConstantArray: { 804 std::string TypeName = ET->getElementName(); 805 if (addTypeNameForElement(TypeName)) { 806 mOut.indent() << RS_ELEM_PREFIX << TypeName << " = Element." << TypeName 807 << "(rs);\n"; 808 } 809 break; 810 } 811 812 case RSExportType::ExportClassRecord: { 813 std::string ClassName = ET->getElementName(); 814 if (addTypeNameForElement(ClassName)) { 815 mOut.indent() << RS_ELEM_PREFIX << ClassName << " = " << ClassName 816 << ".createElement(rs);\n"; 817 } 818 break; 819 } 820 821 default: 822 break; 823 } 824} 825 826void RSReflectionJava::genFieldPackerInstance(const RSExportType *ET) { 827 switch (ET->getClass()) { 828 case RSExportType::ExportClassPrimitive: 829 case RSExportType::ExportClassVector: 830 case RSExportType::ExportClassConstantArray: 831 case RSExportType::ExportClassRecord: { 832 std::string TypeName = ET->getElementName(); 833 addTypeNameForFieldPacker(TypeName); 834 break; 835 } 836 837 default: 838 break; 839 } 840} 841 842void RSReflectionJava::genTypeCheck(const RSExportType *ET, 843 const char *VarName) { 844 mOut.indent() << "// check " << VarName << "\n"; 845 846 if (ET->getClass() == RSExportType::ExportClassPointer) { 847 const RSExportPointerType *EPT = 848 static_cast<const RSExportPointerType *>(ET); 849 ET = EPT->getPointeeType(); 850 } 851 852 std::string TypeName; 853 854 switch (ET->getClass()) { 855 case RSExportType::ExportClassPrimitive: 856 case RSExportType::ExportClassVector: 857 case RSExportType::ExportClassRecord: { 858 TypeName = ET->getElementName(); 859 break; 860 } 861 862 default: 863 break; 864 } 865 866 if (!TypeName.empty()) { 867 mOut.indent() << "if (!" << VarName 868 << ".getType().getElement().isCompatible(" RS_ELEM_PREFIX 869 << TypeName << ")) {\n"; 870 mOut.indent() << " throw new RSRuntimeException(\"Type mismatch with " 871 << TypeName << "!\");\n"; 872 mOut.indent() << "}\n"; 873 } 874} 875 876void RSReflectionJava::genPrimitiveTypeExportVariable(const RSExportVar *EV) { 877 slangAssert( 878 (EV->getType()->getClass() == RSExportType::ExportClassPrimitive) && 879 "Variable should be type of primitive here"); 880 881 const RSExportPrimitiveType *EPT = 882 static_cast<const RSExportPrimitiveType *>(EV->getType()); 883 std::string TypeName = GetTypeName(EPT); 884 std::string VarName = EV->getName(); 885 886 genPrivateExportVariable(TypeName, EV->getName()); 887 888 if (EV->isConst()) { 889 mOut.indent() << "public final static " << TypeName 890 << " " RS_EXPORT_VAR_CONST_PREFIX << VarName << " = "; 891 const clang::APValue &Val = EV->getInit(); 892 genInitValue(Val, EPT->getType() == DataTypeBoolean); 893 mOut << ";\n"; 894 } else { 895 // set_*() 896 // This must remain synchronized, since multiple Dalvik threads may 897 // be calling setters. 898 startFunction(AM_PublicSynchronized, false, "void", "set_" + VarName, 1, 899 TypeName.c_str(), "v"); 900 if ((EPT->getSize() < 4) || EV->isUnsigned()) { 901 // We create/cache a per-type FieldPacker. This allows us to reuse the 902 // validation logic (for catching negative inputs from Dalvik, as well 903 // as inputs that are too large to be represented in the unsigned type). 904 // Sub-integer types are also handled specially here, so that we don't 905 // overwrite bytes accidentally. 906 std::string ElemName = EPT->getElementName(); 907 std::string FPName; 908 FPName = RS_FP_PREFIX + ElemName; 909 mOut.indent() << "if (" << FPName << "!= null) {\n"; 910 mOut.increaseIndent(); 911 mOut.indent() << FPName << ".reset();\n"; 912 mOut.decreaseIndent(); 913 mOut.indent() << "} else {\n"; 914 mOut.increaseIndent(); 915 mOut.indent() << FPName << " = new FieldPacker(" << EPT->getSize() 916 << ");\n"; 917 mOut.decreaseIndent(); 918 mOut.indent() << "}\n"; 919 920 genPackVarOfType(EPT, "v", FPName.c_str()); 921 mOut.indent() << "setVar(" << RS_EXPORT_VAR_INDEX_PREFIX << VarName 922 << ", " << FPName << ");\n"; 923 } else { 924 mOut.indent() << "setVar(" << RS_EXPORT_VAR_INDEX_PREFIX << VarName 925 << ", v);\n"; 926 } 927 928 // Dalvik update comes last, since the input may be invalid (and hence 929 // throw an exception). 930 mOut.indent() << RS_EXPORT_VAR_PREFIX << VarName << " = v;\n"; 931 932 endFunction(); 933 } 934 935 genGetExportVariable(TypeName, VarName); 936 genGetFieldID(VarName); 937} 938 939void RSReflectionJava::genInitValue(const clang::APValue &Val, bool asBool) { 940 switch (Val.getKind()) { 941 case clang::APValue::Int: { 942 llvm::APInt api = Val.getInt(); 943 if (asBool) { 944 mOut << ((api.getSExtValue() == 0) ? "false" : "true"); 945 } else { 946 // TODO: Handle unsigned correctly 947 mOut << api.getSExtValue(); 948 if (api.getBitWidth() > 32) { 949 mOut << "L"; 950 } 951 } 952 break; 953 } 954 955 case clang::APValue::Float: { 956 llvm::APFloat apf = Val.getFloat(); 957 llvm::SmallString<30> s; 958 apf.toString(s); 959 mOut << s.c_str(); 960 if (&apf.getSemantics() == &llvm::APFloat::IEEEsingle) { 961 if (s.count('.') == 0) { 962 mOut << ".f"; 963 } else { 964 mOut << "f"; 965 } 966 } 967 break; 968 } 969 970 case clang::APValue::ComplexInt: 971 case clang::APValue::ComplexFloat: 972 case clang::APValue::LValue: 973 case clang::APValue::Vector: { 974 slangAssert(false && "Primitive type cannot have such kind of initializer"); 975 break; 976 } 977 978 default: { slangAssert(false && "Unknown kind of initializer"); } 979 } 980} 981 982void RSReflectionJava::genPointerTypeExportVariable(const RSExportVar *EV) { 983 const RSExportType *ET = EV->getType(); 984 const RSExportType *PointeeType; 985 986 slangAssert((ET->getClass() == RSExportType::ExportClassPointer) && 987 "Variable should be type of pointer here"); 988 989 PointeeType = static_cast<const RSExportPointerType *>(ET)->getPointeeType(); 990 std::string TypeName = GetTypeName(ET); 991 std::string VarName = EV->getName(); 992 993 genPrivateExportVariable(TypeName, VarName); 994 995 // bind_*() 996 startFunction(AM_Public, false, "void", "bind_" + VarName, 1, 997 TypeName.c_str(), "v"); 998 999 mOut.indent() << RS_EXPORT_VAR_PREFIX << VarName << " = v;\n"; 1000 mOut.indent() << "if (v == null) bindAllocation(null, " 1001 << RS_EXPORT_VAR_INDEX_PREFIX << VarName << ");\n"; 1002 1003 if (PointeeType->getClass() == RSExportType::ExportClassRecord) { 1004 mOut.indent() << "else bindAllocation(v.getAllocation(), " 1005 << RS_EXPORT_VAR_INDEX_PREFIX << VarName << ");\n"; 1006 } else { 1007 mOut.indent() << "else bindAllocation(v, " << RS_EXPORT_VAR_INDEX_PREFIX 1008 << VarName << ");\n"; 1009 } 1010 1011 endFunction(); 1012 1013 genGetExportVariable(TypeName, VarName); 1014} 1015 1016void RSReflectionJava::genVectorTypeExportVariable(const RSExportVar *EV) { 1017 slangAssert((EV->getType()->getClass() == RSExportType::ExportClassVector) && 1018 "Variable should be type of vector here"); 1019 1020 std::string TypeName = GetTypeName(EV->getType()); 1021 std::string VarName = EV->getName(); 1022 1023 genPrivateExportVariable(TypeName, VarName); 1024 genSetExportVariable(TypeName, EV); 1025 genGetExportVariable(TypeName, VarName); 1026 genGetFieldID(VarName); 1027} 1028 1029void RSReflectionJava::genMatrixTypeExportVariable(const RSExportVar *EV) { 1030 slangAssert((EV->getType()->getClass() == RSExportType::ExportClassMatrix) && 1031 "Variable should be type of matrix here"); 1032 1033 const RSExportType *ET = EV->getType(); 1034 std::string TypeName = GetTypeName(ET); 1035 std::string VarName = EV->getName(); 1036 1037 genPrivateExportVariable(TypeName, VarName); 1038 1039 // set_*() 1040 if (!EV->isConst()) { 1041 const char *FieldPackerName = "fp"; 1042 startFunction(AM_PublicSynchronized, false, "void", "set_" + VarName, 1, 1043 TypeName.c_str(), "v"); 1044 mOut.indent() << RS_EXPORT_VAR_PREFIX << VarName << " = v;\n"; 1045 1046 if (genCreateFieldPacker(ET, FieldPackerName)) 1047 genPackVarOfType(ET, "v", FieldPackerName); 1048 mOut.indent() << "setVar(" RS_EXPORT_VAR_INDEX_PREFIX << VarName << ", " 1049 << FieldPackerName << ");\n"; 1050 1051 endFunction(); 1052 } 1053 1054 genGetExportVariable(TypeName, VarName); 1055 genGetFieldID(VarName); 1056} 1057 1058void 1059RSReflectionJava::genConstantArrayTypeExportVariable(const RSExportVar *EV) { 1060 slangAssert( 1061 (EV->getType()->getClass() == RSExportType::ExportClassConstantArray) && 1062 "Variable should be type of constant array here"); 1063 1064 std::string TypeName = GetTypeName(EV->getType()); 1065 std::string VarName = EV->getName(); 1066 1067 genPrivateExportVariable(TypeName, VarName); 1068 genSetExportVariable(TypeName, EV); 1069 genGetExportVariable(TypeName, VarName); 1070 genGetFieldID(VarName); 1071} 1072 1073void RSReflectionJava::genRecordTypeExportVariable(const RSExportVar *EV) { 1074 slangAssert((EV->getType()->getClass() == RSExportType::ExportClassRecord) && 1075 "Variable should be type of struct here"); 1076 1077 std::string TypeName = GetTypeName(EV->getType()); 1078 std::string VarName = EV->getName(); 1079 1080 genPrivateExportVariable(TypeName, VarName); 1081 genSetExportVariable(TypeName, EV); 1082 genGetExportVariable(TypeName, VarName); 1083 genGetFieldID(VarName); 1084} 1085 1086void RSReflectionJava::genPrivateExportVariable(const std::string &TypeName, 1087 const std::string &VarName) { 1088 mOut.indent() << "private " << TypeName << " " << RS_EXPORT_VAR_PREFIX 1089 << VarName << ";\n"; 1090} 1091 1092void RSReflectionJava::genSetExportVariable(const std::string &TypeName, 1093 const RSExportVar *EV) { 1094 if (!EV->isConst()) { 1095 const char *FieldPackerName = "fp"; 1096 std::string VarName = EV->getName(); 1097 const RSExportType *ET = EV->getType(); 1098 startFunction(AM_PublicSynchronized, false, "void", "set_" + VarName, 1, 1099 TypeName.c_str(), "v"); 1100 mOut.indent() << RS_EXPORT_VAR_PREFIX << VarName << " = v;\n"; 1101 1102 if (genCreateFieldPacker(ET, FieldPackerName)) 1103 genPackVarOfType(ET, "v", FieldPackerName); 1104 1105 if (mRSContext->getTargetAPI() < SLANG_JB_TARGET_API) { 1106 // Legacy apps must use the old setVar() without Element/dim components. 1107 mOut.indent() << "setVar(" << RS_EXPORT_VAR_INDEX_PREFIX << VarName 1108 << ", " << FieldPackerName << ");\n"; 1109 } else { 1110 // We only have support for one-dimensional array reflection today, 1111 // but the entry point (i.e. setVar()) takes an array of dimensions. 1112 mOut.indent() << "int []__dimArr = new int[1];\n"; 1113 mOut.indent() << "__dimArr[0] = " << ET->getSize() << ";\n"; 1114 mOut.indent() << "setVar(" << RS_EXPORT_VAR_INDEX_PREFIX << VarName 1115 << ", " << FieldPackerName << ", " << RS_ELEM_PREFIX 1116 << ET->getElementName() << ", __dimArr);\n"; 1117 } 1118 1119 endFunction(); 1120 } 1121} 1122 1123void RSReflectionJava::genGetExportVariable(const std::string &TypeName, 1124 const std::string &VarName) { 1125 startFunction(AM_Public, false, TypeName.c_str(), "get_" + VarName, 0); 1126 1127 mOut.indent() << "return " << RS_EXPORT_VAR_PREFIX << VarName << ";\n"; 1128 1129 endFunction(); 1130} 1131 1132void RSReflectionJava::genGetFieldID(const std::string &VarName) { 1133 // We only generate getFieldID_*() for non-Pointer (bind) types. 1134 if (mRSContext->getTargetAPI() >= SLANG_JB_MR1_TARGET_API) { 1135 startFunction(AM_Public, false, "Script.FieldID", "getFieldID_" + VarName, 1136 0); 1137 1138 mOut.indent() << "return createFieldID(" << RS_EXPORT_VAR_INDEX_PREFIX 1139 << VarName << ", null);\n"; 1140 1141 endFunction(); 1142 } 1143} 1144 1145/******************* Methods to generate script class /end *******************/ 1146 1147bool RSReflectionJava::genCreateFieldPacker(const RSExportType *ET, 1148 const char *FieldPackerName) { 1149 size_t AllocSize = ET->getAllocSize(); 1150 if (AllocSize > 0) 1151 mOut.indent() << "FieldPacker " << FieldPackerName << " = new FieldPacker(" 1152 << AllocSize << ");\n"; 1153 else 1154 return false; 1155 return true; 1156} 1157 1158void RSReflectionJava::genPackVarOfType(const RSExportType *ET, 1159 const char *VarName, 1160 const char *FieldPackerName) { 1161 switch (ET->getClass()) { 1162 case RSExportType::ExportClassPrimitive: 1163 case RSExportType::ExportClassVector: { 1164 mOut.indent() << FieldPackerName << "." 1165 << GetPackerAPIName( 1166 static_cast<const RSExportPrimitiveType *>(ET)) << "(" 1167 << VarName << ");\n"; 1168 break; 1169 } 1170 case RSExportType::ExportClassPointer: { 1171 // Must reflect as type Allocation in Java 1172 const RSExportType *PointeeType = 1173 static_cast<const RSExportPointerType *>(ET)->getPointeeType(); 1174 1175 if (PointeeType->getClass() != RSExportType::ExportClassRecord) { 1176 mOut.indent() << FieldPackerName << ".addI32(" << VarName 1177 << ".getPtr());\n"; 1178 } else { 1179 mOut.indent() << FieldPackerName << ".addI32(" << VarName 1180 << ".getAllocation().getPtr());\n"; 1181 } 1182 break; 1183 } 1184 case RSExportType::ExportClassMatrix: { 1185 mOut.indent() << FieldPackerName << ".addMatrix(" << VarName << ");\n"; 1186 break; 1187 } 1188 case RSExportType::ExportClassConstantArray: { 1189 const RSExportConstantArrayType *ECAT = 1190 static_cast<const RSExportConstantArrayType *>(ET); 1191 1192 // TODO(zonr): more elegant way. Currently, we obtain the unique index 1193 // variable (this method involves recursive call which means 1194 // we may have more than one level loop, therefore we can't 1195 // always use the same index variable name here) name given 1196 // in the for-loop from counting the '.' in @VarName. 1197 unsigned Level = 0; 1198 size_t LastDotPos = 0; 1199 std::string ElementVarName(VarName); 1200 1201 while (LastDotPos != std::string::npos) { 1202 LastDotPos = ElementVarName.find_first_of('.', LastDotPos + 1); 1203 Level++; 1204 } 1205 std::string IndexVarName("ct"); 1206 IndexVarName.append(llvm::utostr_32(Level)); 1207 1208 mOut.indent() << "for (int " << IndexVarName << " = 0; " << IndexVarName 1209 << " < " << ECAT->getSize() << "; " << IndexVarName << "++)"; 1210 mOut.startBlock(); 1211 1212 ElementVarName.append("[" + IndexVarName + "]"); 1213 genPackVarOfType(ECAT->getElementType(), ElementVarName.c_str(), 1214 FieldPackerName); 1215 1216 mOut.endBlock(); 1217 break; 1218 } 1219 case RSExportType::ExportClassRecord: { 1220 const RSExportRecordType *ERT = static_cast<const RSExportRecordType *>(ET); 1221 // Relative pos from now on in field packer 1222 unsigned Pos = 0; 1223 1224 for (RSExportRecordType::const_field_iterator I = ERT->fields_begin(), 1225 E = ERT->fields_end(); 1226 I != E; I++) { 1227 const RSExportRecordType::Field *F = *I; 1228 std::string FieldName; 1229 size_t FieldOffset = F->getOffsetInParent(); 1230 const RSExportType *T = F->getType(); 1231 size_t FieldStoreSize = T->getStoreSize(); 1232 size_t FieldAllocSize = T->getAllocSize(); 1233 1234 if (VarName != NULL) 1235 FieldName = VarName + ("." + F->getName()); 1236 else 1237 FieldName = F->getName(); 1238 1239 if (FieldOffset > Pos) { 1240 mOut.indent() << FieldPackerName << ".skip(" << (FieldOffset - Pos) 1241 << ");\n"; 1242 } 1243 1244 genPackVarOfType(F->getType(), FieldName.c_str(), FieldPackerName); 1245 1246 // There is padding in the field type 1247 if (FieldAllocSize > FieldStoreSize) { 1248 mOut.indent() << FieldPackerName << ".skip(" 1249 << (FieldAllocSize - FieldStoreSize) << ");\n"; 1250 } 1251 1252 Pos = FieldOffset + FieldAllocSize; 1253 } 1254 1255 // There maybe some padding after the struct 1256 if (ERT->getAllocSize() > Pos) { 1257 mOut.indent() << FieldPackerName << ".skip(" << ERT->getAllocSize() - Pos 1258 << ");\n"; 1259 } 1260 break; 1261 } 1262 default: { slangAssert(false && "Unknown class of type"); } 1263 } 1264} 1265 1266void RSReflectionJava::genAllocateVarOfType(const RSExportType *T, 1267 const std::string &VarName) { 1268 switch (T->getClass()) { 1269 case RSExportType::ExportClassPrimitive: { 1270 // Primitive type like int in Java has its own storage once it's declared. 1271 // 1272 // FIXME: Should we allocate storage for RS object? 1273 // if (static_cast<const RSExportPrimitiveType *>(T)->isRSObjectType()) 1274 // mOut.indent() << VarName << " = new " << GetTypeName(T) << "();\n"; 1275 break; 1276 } 1277 case RSExportType::ExportClassPointer: { 1278 // Pointer type is an instance of Allocation or a TypeClass whose value is 1279 // expected to be assigned by programmer later in Java program. Therefore 1280 // we don't reflect things like [VarName] = new Allocation(); 1281 mOut.indent() << VarName << " = null;\n"; 1282 break; 1283 } 1284 case RSExportType::ExportClassConstantArray: { 1285 const RSExportConstantArrayType *ECAT = 1286 static_cast<const RSExportConstantArrayType *>(T); 1287 const RSExportType *ElementType = ECAT->getElementType(); 1288 1289 mOut.indent() << VarName << " = new " << GetTypeName(ElementType) << "[" 1290 << ECAT->getSize() << "];\n"; 1291 1292 // Primitive type element doesn't need allocation code. 1293 if (ElementType->getClass() != RSExportType::ExportClassPrimitive) { 1294 mOut.indent() << "for (int $ct = 0; $ct < " << ECAT->getSize() 1295 << "; $ct++)"; 1296 mOut.startBlock(); 1297 1298 std::string ElementVarName(VarName); 1299 ElementVarName.append("[$ct]"); 1300 genAllocateVarOfType(ElementType, ElementVarName); 1301 1302 mOut.endBlock(); 1303 } 1304 break; 1305 } 1306 case RSExportType::ExportClassVector: 1307 case RSExportType::ExportClassMatrix: 1308 case RSExportType::ExportClassRecord: { 1309 mOut.indent() << VarName << " = new " << GetTypeName(T) << "();\n"; 1310 break; 1311 } 1312 } 1313} 1314 1315void RSReflectionJava::genNewItemBufferIfNull(const char *Index) { 1316 mOut.indent() << "if (" << RS_TYPE_ITEM_BUFFER_NAME " == null) "; 1317 mOut << RS_TYPE_ITEM_BUFFER_NAME << " = new " << RS_TYPE_ITEM_CLASS_NAME 1318 << "[getType().getX() /* count */];\n"; 1319 if (Index != NULL) { 1320 mOut.indent() << "if (" << RS_TYPE_ITEM_BUFFER_NAME << "[" << Index 1321 << "] == null) "; 1322 mOut << RS_TYPE_ITEM_BUFFER_NAME << "[" << Index << "] = new " 1323 << RS_TYPE_ITEM_CLASS_NAME << "();\n"; 1324 } 1325} 1326 1327void RSReflectionJava::genNewItemBufferPackerIfNull() { 1328 mOut.indent() << "if (" << RS_TYPE_ITEM_BUFFER_PACKER_NAME << " == null) "; 1329 mOut << RS_TYPE_ITEM_BUFFER_PACKER_NAME " = new FieldPacker(" 1330 << mItemSizeof << " * getType().getX()/* count */);\n"; 1331} 1332 1333/********************** Methods to generate type class **********************/ 1334bool RSReflectionJava::genTypeClass(const RSExportRecordType *ERT, 1335 std::string &ErrorMsg) { 1336 std::string ClassName = ERT->getElementName(); 1337 std::string superClassName = getRSPackageName(); 1338 superClassName += RS_TYPE_CLASS_SUPER_CLASS_NAME; 1339 1340 if (!startClass(AM_Public, false, ClassName, superClassName.c_str(), 1341 ErrorMsg)) 1342 return false; 1343 1344 mGeneratedFileNames->push_back(ClassName); 1345 1346 genTypeItemClass(ERT); 1347 1348 // Declare item buffer and item buffer packer 1349 mOut.indent() << "private " << RS_TYPE_ITEM_CLASS_NAME << " " 1350 << RS_TYPE_ITEM_BUFFER_NAME << "[];\n"; 1351 mOut.indent() << "private FieldPacker " << RS_TYPE_ITEM_BUFFER_PACKER_NAME 1352 << ";\n"; 1353 mOut.indent() << "private static java.lang.ref.WeakReference<Element> " 1354 << RS_TYPE_ELEMENT_REF_NAME 1355 << " = new java.lang.ref.WeakReference<Element>(null);\n"; 1356 1357 genTypeClassConstructor(ERT); 1358 genTypeClassCopyToArrayLocal(ERT); 1359 genTypeClassCopyToArray(ERT); 1360 genTypeClassItemSetter(ERT); 1361 genTypeClassItemGetter(ERT); 1362 genTypeClassComponentSetter(ERT); 1363 genTypeClassComponentGetter(ERT); 1364 genTypeClassCopyAll(ERT); 1365 if (!mRSContext->isCompatLib()) { 1366 // Skip the resize method if we are targeting a compatibility library. 1367 genTypeClassResize(); 1368 } 1369 1370 endClass(); 1371 1372 resetFieldIndex(); 1373 clearFieldIndexMap(); 1374 1375 return true; 1376} 1377 1378void RSReflectionJava::genTypeItemClass(const RSExportRecordType *ERT) { 1379 mOut.indent() << "static public class " RS_TYPE_ITEM_CLASS_NAME; 1380 mOut.startBlock(); 1381 1382 // Sizeof should not be exposed for 64-bit; it is not accurate 1383 if (mRSContext->getTargetAPI() < 21) { 1384 mOut.indent() << "public static final int sizeof = " << ERT->getAllocSize() 1385 << ";\n"; 1386 } 1387 1388 // Member elements 1389 mOut << "\n"; 1390 for (RSExportRecordType::const_field_iterator FI = ERT->fields_begin(), 1391 FE = ERT->fields_end(); 1392 FI != FE; FI++) { 1393 mOut.indent() << GetTypeName((*FI)->getType()) << " " << (*FI)->getName() 1394 << ";\n"; 1395 } 1396 1397 // Constructor 1398 mOut << "\n"; 1399 mOut.indent() << RS_TYPE_ITEM_CLASS_NAME << "()"; 1400 mOut.startBlock(); 1401 1402 for (RSExportRecordType::const_field_iterator FI = ERT->fields_begin(), 1403 FE = ERT->fields_end(); 1404 FI != FE; FI++) { 1405 const RSExportRecordType::Field *F = *FI; 1406 genAllocateVarOfType(F->getType(), F->getName()); 1407 } 1408 1409 // end Constructor 1410 mOut.endBlock(); 1411 1412 // end Item class 1413 mOut.endBlock(); 1414} 1415 1416void RSReflectionJava::genTypeClassConstructor(const RSExportRecordType *ERT) { 1417 const char *RenderScriptVar = "rs"; 1418 1419 startFunction(AM_Public, true, "Element", "createElement", 1, "RenderScript", 1420 RenderScriptVar); 1421 1422 // TODO(all): Fix weak-refs + multi-context issue. 1423 // mOut.indent() << "Element e = " << RS_TYPE_ELEMENT_REF_NAME 1424 // << ".get();\n"; 1425 // mOut.indent() << "if (e != null) return e;\n"; 1426 RSReflectionJavaElementBuilder builder("eb", ERT, RenderScriptVar, &mOut, 1427 mRSContext, this); 1428 builder.generate(); 1429 1430 mOut.indent() << "return eb.create();\n"; 1431 // mOut.indent() << "e = eb.create();\n"; 1432 // mOut.indent() << RS_TYPE_ELEMENT_REF_NAME 1433 // << " = new java.lang.ref.WeakReference<Element>(e);\n"; 1434 // mOut.indent() << "return e;\n"; 1435 endFunction(); 1436 1437 // private with element 1438 startFunction(AM_Private, false, NULL, getClassName(), 1, "RenderScript", 1439 RenderScriptVar); 1440 mOut.indent() << RS_TYPE_ITEM_BUFFER_NAME << " = null;\n"; 1441 mOut.indent() << RS_TYPE_ITEM_BUFFER_PACKER_NAME << " = null;\n"; 1442 mOut.indent() << "mElement = createElement(" << RenderScriptVar << ");\n"; 1443 endFunction(); 1444 1445 // 1D without usage 1446 startFunction(AM_Public, false, NULL, getClassName(), 2, "RenderScript", 1447 RenderScriptVar, "int", "count"); 1448 1449 mOut.indent() << RS_TYPE_ITEM_BUFFER_NAME << " = null;\n"; 1450 mOut.indent() << RS_TYPE_ITEM_BUFFER_PACKER_NAME << " = null;\n"; 1451 mOut.indent() << "mElement = createElement(" << RenderScriptVar << ");\n"; 1452 // Call init() in super class 1453 mOut.indent() << "init(" << RenderScriptVar << ", count);\n"; 1454 endFunction(); 1455 1456 // 1D with usage 1457 startFunction(AM_Public, false, NULL, getClassName(), 3, "RenderScript", 1458 RenderScriptVar, "int", "count", "int", "usages"); 1459 1460 mOut.indent() << RS_TYPE_ITEM_BUFFER_NAME << " = null;\n"; 1461 mOut.indent() << RS_TYPE_ITEM_BUFFER_PACKER_NAME << " = null;\n"; 1462 mOut.indent() << "mElement = createElement(" << RenderScriptVar << ");\n"; 1463 // Call init() in super class 1464 mOut.indent() << "init(" << RenderScriptVar << ", count, usages);\n"; 1465 endFunction(); 1466 1467 // create1D with usage 1468 startFunction(AM_Public, true, getClassName().c_str(), "create1D", 3, 1469 "RenderScript", RenderScriptVar, "int", "dimX", "int", 1470 "usages"); 1471 mOut.indent() << getClassName() << " obj = new " << getClassName() << "(" 1472 << RenderScriptVar << ");\n"; 1473 mOut.indent() << "obj.mAllocation = Allocation.createSized(" 1474 "rs, obj.mElement, dimX, usages);\n"; 1475 mOut.indent() << "return obj;\n"; 1476 endFunction(); 1477 1478 // create1D without usage 1479 startFunction(AM_Public, true, getClassName().c_str(), "create1D", 2, 1480 "RenderScript", RenderScriptVar, "int", "dimX"); 1481 mOut.indent() << "return create1D(" << RenderScriptVar 1482 << ", dimX, Allocation.USAGE_SCRIPT);\n"; 1483 endFunction(); 1484 1485 // create2D without usage 1486 startFunction(AM_Public, true, getClassName().c_str(), "create2D", 3, 1487 "RenderScript", RenderScriptVar, "int", "dimX", "int", "dimY"); 1488 mOut.indent() << "return create2D(" << RenderScriptVar 1489 << ", dimX, dimY, Allocation.USAGE_SCRIPT);\n"; 1490 endFunction(); 1491 1492 // create2D with usage 1493 startFunction(AM_Public, true, getClassName().c_str(), "create2D", 4, 1494 "RenderScript", RenderScriptVar, "int", "dimX", "int", "dimY", 1495 "int", "usages"); 1496 1497 mOut.indent() << getClassName() << " obj = new " << getClassName() << "(" 1498 << RenderScriptVar << ");\n"; 1499 mOut.indent() << "Type.Builder b = new Type.Builder(rs, obj.mElement);\n"; 1500 mOut.indent() << "b.setX(dimX);\n"; 1501 mOut.indent() << "b.setY(dimY);\n"; 1502 mOut.indent() << "Type t = b.create();\n"; 1503 mOut.indent() << "obj.mAllocation = Allocation.createTyped(rs, t, usages);\n"; 1504 mOut.indent() << "return obj;\n"; 1505 endFunction(); 1506 1507 // createTypeBuilder 1508 startFunction(AM_Public, true, "Type.Builder", "createTypeBuilder", 1, 1509 "RenderScript", RenderScriptVar); 1510 mOut.indent() << "Element e = createElement(" << RenderScriptVar << ");\n"; 1511 mOut.indent() << "return new Type.Builder(rs, e);\n"; 1512 endFunction(); 1513 1514 // createCustom with usage 1515 startFunction(AM_Public, true, getClassName().c_str(), "createCustom", 3, 1516 "RenderScript", RenderScriptVar, "Type.Builder", "tb", "int", 1517 "usages"); 1518 mOut.indent() << getClassName() << " obj = new " << getClassName() << "(" 1519 << RenderScriptVar << ");\n"; 1520 mOut.indent() << "Type t = tb.create();\n"; 1521 mOut.indent() << "if (t.getElement() != obj.mElement) {\n"; 1522 mOut.indent() << " throw new RSIllegalArgumentException(" 1523 "\"Type.Builder did not match expected element type.\");\n"; 1524 mOut.indent() << "}\n"; 1525 mOut.indent() << "obj.mAllocation = Allocation.createTyped(rs, t, usages);\n"; 1526 mOut.indent() << "return obj;\n"; 1527 endFunction(); 1528} 1529 1530void RSReflectionJava::genTypeClassCopyToArray(const RSExportRecordType *ERT) { 1531 startFunction(AM_Private, false, "void", "copyToArray", 2, 1532 RS_TYPE_ITEM_CLASS_NAME, "i", "int", "index"); 1533 1534 genNewItemBufferPackerIfNull(); 1535 mOut.indent() << RS_TYPE_ITEM_BUFFER_PACKER_NAME << ".reset(index * " 1536 << mItemSizeof << ");\n"; 1537 1538 mOut.indent() << "copyToArrayLocal(i, " RS_TYPE_ITEM_BUFFER_PACKER_NAME 1539 ");\n"; 1540 1541 endFunction(); 1542} 1543 1544void 1545RSReflectionJava::genTypeClassCopyToArrayLocal(const RSExportRecordType *ERT) { 1546 startFunction(AM_Private, false, "void", "copyToArrayLocal", 2, 1547 RS_TYPE_ITEM_CLASS_NAME, "i", "FieldPacker", "fp"); 1548 1549 genPackVarOfType(ERT, "i", "fp"); 1550 1551 endFunction(); 1552} 1553 1554void RSReflectionJava::genTypeClassItemSetter(const RSExportRecordType *ERT) { 1555 startFunction(AM_PublicSynchronized, false, "void", "set", 3, 1556 RS_TYPE_ITEM_CLASS_NAME, "i", "int", "index", "boolean", 1557 "copyNow"); 1558 genNewItemBufferIfNull(NULL); 1559 mOut.indent() << RS_TYPE_ITEM_BUFFER_NAME << "[index] = i;\n"; 1560 1561 mOut.indent() << "if (copyNow) "; 1562 mOut.startBlock(); 1563 1564 mOut.indent() << "copyToArray(i, index);\n"; 1565 mOut.indent() << "FieldPacker fp = new FieldPacker(" << mItemSizeof << ");\n"; 1566 mOut.indent() << "copyToArrayLocal(i, fp);\n"; 1567 mOut.indent() << "mAllocation.setFromFieldPacker(index, fp);\n"; 1568 1569 // End of if (copyNow) 1570 mOut.endBlock(); 1571 1572 endFunction(); 1573} 1574 1575void RSReflectionJava::genTypeClassItemGetter(const RSExportRecordType *ERT) { 1576 startFunction(AM_PublicSynchronized, false, RS_TYPE_ITEM_CLASS_NAME, "get", 1, 1577 "int", "index"); 1578 mOut.indent() << "if (" << RS_TYPE_ITEM_BUFFER_NAME 1579 << " == null) return null;\n"; 1580 mOut.indent() << "return " << RS_TYPE_ITEM_BUFFER_NAME << "[index];\n"; 1581 endFunction(); 1582} 1583 1584void 1585RSReflectionJava::genTypeClassComponentSetter(const RSExportRecordType *ERT) { 1586 for (RSExportRecordType::const_field_iterator FI = ERT->fields_begin(), 1587 FE = ERT->fields_end(); 1588 FI != FE; FI++) { 1589 const RSExportRecordType::Field *F = *FI; 1590 size_t FieldOffset = F->getOffsetInParent(); 1591 size_t FieldStoreSize = F->getType()->getStoreSize(); 1592 unsigned FieldIndex = getFieldIndex(F); 1593 1594 startFunction(AM_PublicSynchronized, false, "void", "set_" + F->getName(), 1595 3, "int", "index", GetTypeName(F->getType()).c_str(), "v", 1596 "boolean", "copyNow"); 1597 genNewItemBufferPackerIfNull(); 1598 genNewItemBufferIfNull("index"); 1599 mOut.indent() << RS_TYPE_ITEM_BUFFER_NAME << "[index]." << F->getName() 1600 << " = v;\n"; 1601 1602 mOut.indent() << "if (copyNow) "; 1603 mOut.startBlock(); 1604 1605 if (FieldOffset > 0) { 1606 mOut.indent() << RS_TYPE_ITEM_BUFFER_PACKER_NAME << ".reset(index * " 1607 << mItemSizeof << " + " << FieldOffset 1608 << ");\n"; 1609 } else { 1610 mOut.indent() << RS_TYPE_ITEM_BUFFER_PACKER_NAME << ".reset(index * " 1611 << mItemSizeof << ");\n"; 1612 } 1613 genPackVarOfType(F->getType(), "v", RS_TYPE_ITEM_BUFFER_PACKER_NAME); 1614 1615 mOut.indent() << "FieldPacker fp = new FieldPacker(" << FieldStoreSize 1616 << ");\n"; 1617 genPackVarOfType(F->getType(), "v", "fp"); 1618 mOut.indent() << "mAllocation.setFromFieldPacker(index, " << FieldIndex 1619 << ", fp);\n"; 1620 1621 // End of if (copyNow) 1622 mOut.endBlock(); 1623 1624 endFunction(); 1625 } 1626} 1627 1628void 1629RSReflectionJava::genTypeClassComponentGetter(const RSExportRecordType *ERT) { 1630 for (RSExportRecordType::const_field_iterator FI = ERT->fields_begin(), 1631 FE = ERT->fields_end(); 1632 FI != FE; FI++) { 1633 const RSExportRecordType::Field *F = *FI; 1634 startFunction(AM_PublicSynchronized, false, 1635 GetTypeName(F->getType()).c_str(), "get_" + F->getName(), 1, 1636 "int", "index"); 1637 mOut.indent() << "if (" RS_TYPE_ITEM_BUFFER_NAME << " == null) return " 1638 << GetTypeNullValue(F->getType()) << ";\n"; 1639 mOut.indent() << "return " RS_TYPE_ITEM_BUFFER_NAME << "[index]." 1640 << F->getName() << ";\n"; 1641 endFunction(); 1642 } 1643} 1644 1645void RSReflectionJava::genTypeClassCopyAll(const RSExportRecordType *ERT) { 1646 startFunction(AM_PublicSynchronized, false, "void", "copyAll", 0); 1647 1648 mOut.indent() << "for (int ct = 0; ct < " << RS_TYPE_ITEM_BUFFER_NAME 1649 << ".length; ct++)" 1650 << " copyToArray(" << RS_TYPE_ITEM_BUFFER_NAME 1651 << "[ct], ct);\n"; 1652 mOut.indent() << "mAllocation.setFromFieldPacker(0, " 1653 << RS_TYPE_ITEM_BUFFER_PACKER_NAME ");\n"; 1654 1655 endFunction(); 1656} 1657 1658void RSReflectionJava::genTypeClassResize() { 1659 startFunction(AM_PublicSynchronized, false, "void", "resize", 1, "int", 1660 "newSize"); 1661 1662 mOut.indent() << "if (mItemArray != null) "; 1663 mOut.startBlock(); 1664 mOut.indent() << "int oldSize = mItemArray.length;\n"; 1665 mOut.indent() << "int copySize = Math.min(oldSize, newSize);\n"; 1666 mOut.indent() << "if (newSize == oldSize) return;\n"; 1667 mOut.indent() << "Item ni[] = new Item[newSize];\n"; 1668 mOut.indent() << "System.arraycopy(mItemArray, 0, ni, 0, copySize);\n"; 1669 mOut.indent() << "mItemArray = ni;\n"; 1670 mOut.endBlock(); 1671 mOut.indent() << "mAllocation.resize(newSize);\n"; 1672 1673 mOut.indent() << "if (" RS_TYPE_ITEM_BUFFER_PACKER_NAME 1674 " != null) " RS_TYPE_ITEM_BUFFER_PACKER_NAME " = " 1675 "new FieldPacker(" << mItemSizeof << " * getType().getX()/* count */);\n"; 1676 1677 endFunction(); 1678} 1679 1680/******************** Methods to generate type class /end ********************/ 1681 1682/********** Methods to create Element in Java of given record type ***********/ 1683 1684RSReflectionJavaElementBuilder::RSReflectionJavaElementBuilder( 1685 const char *ElementBuilderName, const RSExportRecordType *ERT, 1686 const char *RenderScriptVar, GeneratedFile *Out, const RSContext *RSContext, 1687 RSReflectionJava *Reflection) 1688 : mElementBuilderName(ElementBuilderName), mERT(ERT), 1689 mRenderScriptVar(RenderScriptVar), mOut(Out), mPaddingFieldIndex(1), 1690 mRSContext(RSContext), mReflection(Reflection) { 1691 if (mRSContext->getTargetAPI() < SLANG_ICS_TARGET_API) { 1692 mPaddingPrefix = "#padding_"; 1693 } else { 1694 mPaddingPrefix = "#rs_padding_"; 1695 } 1696} 1697 1698void RSReflectionJavaElementBuilder::generate() { 1699 mOut->indent() << "Element.Builder " << mElementBuilderName 1700 << " = new Element.Builder(" << mRenderScriptVar << ");\n"; 1701 genAddElement(mERT, "", /* ArraySize = */ 0); 1702} 1703 1704void RSReflectionJavaElementBuilder::genAddElement(const RSExportType *ET, 1705 const std::string &VarName, 1706 unsigned ArraySize) { 1707 std::string ElementConstruct = GetBuiltinElementConstruct(ET); 1708 1709 if (ElementConstruct != "") { 1710 genAddStatementStart(); 1711 *mOut << ElementConstruct << "(" << mRenderScriptVar << ")"; 1712 genAddStatementEnd(VarName, ArraySize); 1713 } else { 1714 1715 switch (ET->getClass()) { 1716 case RSExportType::ExportClassPrimitive: { 1717 const RSExportPrimitiveType *EPT = 1718 static_cast<const RSExportPrimitiveType *>(ET); 1719 const char *DataTypeName = 1720 RSExportPrimitiveType::getRSReflectionType(EPT)->rs_type; 1721 genAddStatementStart(); 1722 *mOut << "Element.createUser(" << mRenderScriptVar 1723 << ", Element.DataType." << DataTypeName << ")"; 1724 genAddStatementEnd(VarName, ArraySize); 1725 break; 1726 } 1727 case RSExportType::ExportClassVector: { 1728 const RSExportVectorType *EVT = 1729 static_cast<const RSExportVectorType *>(ET); 1730 const char *DataTypeName = 1731 RSExportPrimitiveType::getRSReflectionType(EVT)->rs_type; 1732 genAddStatementStart(); 1733 *mOut << "Element.createVector(" << mRenderScriptVar 1734 << ", Element.DataType." << DataTypeName << ", " 1735 << EVT->getNumElement() << ")"; 1736 genAddStatementEnd(VarName, ArraySize); 1737 break; 1738 } 1739 case RSExportType::ExportClassPointer: 1740 // Pointer type variable should be resolved in 1741 // GetBuiltinElementConstruct() 1742 slangAssert(false && "??"); 1743 break; 1744 case RSExportType::ExportClassMatrix: 1745 // Matrix type variable should be resolved 1746 // in GetBuiltinElementConstruct() 1747 slangAssert(false && "??"); 1748 break; 1749 case RSExportType::ExportClassConstantArray: { 1750 const RSExportConstantArrayType *ECAT = 1751 static_cast<const RSExportConstantArrayType *>(ET); 1752 1753 const RSExportType *ElementType = ECAT->getElementType(); 1754 if (ElementType->getClass() != RSExportType::ExportClassRecord) { 1755 genAddElement(ECAT->getElementType(), VarName, ECAT->getSize()); 1756 } else { 1757 std::string NewElementBuilderName(mElementBuilderName); 1758 NewElementBuilderName.append(1, '_'); 1759 1760 RSReflectionJavaElementBuilder builder( 1761 NewElementBuilderName.c_str(), 1762 static_cast<const RSExportRecordType *>(ElementType), 1763 mRenderScriptVar, mOut, mRSContext, mReflection); 1764 builder.generate(); 1765 1766 ArraySize = ECAT->getSize(); 1767 genAddStatementStart(); 1768 *mOut << NewElementBuilderName << ".create()"; 1769 genAddStatementEnd(VarName, ArraySize); 1770 } 1771 break; 1772 } 1773 case RSExportType::ExportClassRecord: { 1774 // Simalar to case of RSExportType::ExportClassRecord in genPackVarOfType. 1775 // 1776 // TODO(zonr): Generalize these two function such that there's no 1777 // duplicated codes. 1778 const RSExportRecordType *ERT = 1779 static_cast<const RSExportRecordType *>(ET); 1780 int Pos = 0; // relative pos from now on 1781 1782 for (RSExportRecordType::const_field_iterator I = ERT->fields_begin(), 1783 E = ERT->fields_end(); 1784 I != E; I++) { 1785 const RSExportRecordType::Field *F = *I; 1786 int FieldOffset = F->getOffsetInParent(); 1787 const RSExportType *T = F->getType(); 1788 int FieldStoreSize = T->getStoreSize(); 1789 int FieldAllocSize = T->getAllocSize(); 1790 1791 std::string FieldName; 1792 if (!VarName.empty()) 1793 FieldName = VarName + "." + F->getName(); 1794 else 1795 FieldName = F->getName(); 1796 1797 // Alignment 1798 genAddPadding(FieldOffset - Pos); 1799 1800 // eb.add(...) 1801 mReflection->addFieldIndexMapping(F); 1802 if (F->getType()->getClass() != RSExportType::ExportClassRecord) { 1803 genAddElement(F->getType(), FieldName, 0); 1804 } else { 1805 std::string NewElementBuilderName(mElementBuilderName); 1806 NewElementBuilderName.append(1, '_'); 1807 1808 RSReflectionJavaElementBuilder builder( 1809 NewElementBuilderName.c_str(), 1810 static_cast<const RSExportRecordType *>(F->getType()), 1811 mRenderScriptVar, mOut, mRSContext, mReflection); 1812 builder.generate(); 1813 1814 genAddStatementStart(); 1815 *mOut << NewElementBuilderName << ".create()"; 1816 genAddStatementEnd(FieldName, ArraySize); 1817 } 1818 1819 if (mRSContext->getTargetAPI() < SLANG_ICS_TARGET_API) { 1820 // There is padding within the field type. This is only necessary 1821 // for HC-targeted APIs. 1822 genAddPadding(FieldAllocSize - FieldStoreSize); 1823 } 1824 1825 Pos = FieldOffset + FieldAllocSize; 1826 } 1827 1828 // There maybe some padding after the struct 1829 size_t RecordAllocSize = ERT->getAllocSize(); 1830 1831 genAddPadding(RecordAllocSize - Pos); 1832 break; 1833 } 1834 default: 1835 slangAssert(false && "Unknown class of type"); 1836 break; 1837 } 1838 } 1839} 1840 1841void RSReflectionJavaElementBuilder::genAddPadding(int PaddingSize) { 1842 while (PaddingSize > 0) { 1843 const std::string &VarName = createPaddingField(); 1844 genAddStatementStart(); 1845 if (PaddingSize >= 4) { 1846 *mOut << "Element.U32(" << mRenderScriptVar << ")"; 1847 PaddingSize -= 4; 1848 } else if (PaddingSize >= 2) { 1849 *mOut << "Element.U16(" << mRenderScriptVar << ")"; 1850 PaddingSize -= 2; 1851 } else if (PaddingSize >= 1) { 1852 *mOut << "Element.U8(" << mRenderScriptVar << ")"; 1853 PaddingSize -= 1; 1854 } 1855 genAddStatementEnd(VarName, 0); 1856 } 1857} 1858 1859void RSReflectionJavaElementBuilder::genAddStatementStart() { 1860 mOut->indent() << mElementBuilderName << ".add("; 1861} 1862 1863void 1864RSReflectionJavaElementBuilder::genAddStatementEnd(const std::string &VarName, 1865 unsigned ArraySize) { 1866 *mOut << ", \"" << VarName << "\""; 1867 if (ArraySize > 0) { 1868 *mOut << ", " << ArraySize; 1869 } 1870 *mOut << ");\n"; 1871 // TODO Review incFieldIndex. It's probably better to assign the numbers at 1872 // the start rather 1873 // than as we're generating the code. 1874 mReflection->incFieldIndex(); 1875} 1876 1877/******** Methods to create Element in Java of given record type /end ********/ 1878 1879bool RSReflectionJava::reflect() { 1880 std::string ErrorMsg; 1881 if (!genScriptClass(mScriptClassName, ErrorMsg)) { 1882 std::cerr << "Failed to generate class " << mScriptClassName << " (" 1883 << ErrorMsg << ")\n"; 1884 return false; 1885 } 1886 1887 mGeneratedFileNames->push_back(mScriptClassName); 1888 1889 // class ScriptField_<TypeName> 1890 for (RSContext::const_export_type_iterator 1891 TI = mRSContext->export_types_begin(), 1892 TE = mRSContext->export_types_end(); 1893 TI != TE; TI++) { 1894 const RSExportType *ET = TI->getValue(); 1895 1896 if (ET->getClass() == RSExportType::ExportClassRecord) { 1897 const RSExportRecordType *ERT = 1898 static_cast<const RSExportRecordType *>(ET); 1899 1900 if (!ERT->isArtificial() && !genTypeClass(ERT, ErrorMsg)) { 1901 std::cerr << "Failed to generate type class for struct '" 1902 << ERT->getName() << "' (" << ErrorMsg << ")\n"; 1903 return false; 1904 } 1905 } 1906 } 1907 1908 return true; 1909} 1910 1911const char *RSReflectionJava::AccessModifierStr(AccessModifier AM) { 1912 switch (AM) { 1913 case AM_Public: 1914 return "public"; 1915 break; 1916 case AM_Protected: 1917 return "protected"; 1918 break; 1919 case AM_Private: 1920 return "private"; 1921 break; 1922 case AM_PublicSynchronized: 1923 return "public synchronized"; 1924 break; 1925 default: 1926 return ""; 1927 break; 1928 } 1929} 1930 1931bool RSReflectionJava::startClass(AccessModifier AM, bool IsStatic, 1932 const std::string &ClassName, 1933 const char *SuperClassName, 1934 std::string &ErrorMsg) { 1935 // Open file for class 1936 std::string FileName = ClassName + ".java"; 1937 if (!mOut.startFile(mOutputDirectory, FileName, mRSSourceFileName, 1938 mRSContext->getLicenseNote(), true, 1939 mRSContext->getVerbose())) { 1940 return false; 1941 } 1942 1943 // Package 1944 if (!mPackageName.empty()) { 1945 mOut << "package " << mPackageName << ";\n"; 1946 } 1947 mOut << "\n"; 1948 1949 // Imports 1950 mOut << "import " << mRSPackageName << ".*;\n"; 1951 if (getEmbedBitcodeInJava()) { 1952 mOut << "import " << mPackageName << "." 1953 << RSSlangReflectUtils::JavaBitcodeClassNameFromRSFileName( 1954 mRSSourceFileName.c_str()) << ";\n"; 1955 } else { 1956 mOut << "import android.content.res.Resources;\n"; 1957 } 1958 mOut << "\n"; 1959 1960 // All reflected classes should be annotated as hidden, so that they won't 1961 // be exposed in SDK. 1962 mOut << "/**\n"; 1963 mOut << " * @hide\n"; 1964 mOut << " */\n"; 1965 1966 mOut << AccessModifierStr(AM) << ((IsStatic) ? " static" : "") << " class " 1967 << ClassName; 1968 if (SuperClassName != NULL) 1969 mOut << " extends " << SuperClassName; 1970 1971 mOut.startBlock(); 1972 1973 mClassName = ClassName; 1974 1975 return true; 1976} 1977 1978void RSReflectionJava::endClass() { 1979 mOut.endBlock(); 1980 mOut.closeFile(); 1981 clear(); 1982} 1983 1984void RSReflectionJava::startTypeClass(const std::string &ClassName) { 1985 mOut.indent() << "public static class " << ClassName; 1986 mOut.startBlock(); 1987} 1988 1989void RSReflectionJava::endTypeClass() { mOut.endBlock(); } 1990 1991void RSReflectionJava::startFunction(AccessModifier AM, bool IsStatic, 1992 const char *ReturnType, 1993 const std::string &FunctionName, int Argc, 1994 ...) { 1995 ArgTy Args; 1996 va_list vl; 1997 va_start(vl, Argc); 1998 1999 for (int i = 0; i < Argc; i++) { 2000 const char *ArgType = va_arg(vl, const char *); 2001 const char *ArgName = va_arg(vl, const char *); 2002 2003 Args.push_back(std::make_pair(ArgType, ArgName)); 2004 } 2005 va_end(vl); 2006 2007 startFunction(AM, IsStatic, ReturnType, FunctionName, Args); 2008} 2009 2010void RSReflectionJava::startFunction(AccessModifier AM, bool IsStatic, 2011 const char *ReturnType, 2012 const std::string &FunctionName, 2013 const ArgTy &Args) { 2014 mOut.indent() << AccessModifierStr(AM) << ((IsStatic) ? " static " : " ") 2015 << ((ReturnType) ? ReturnType : "") << " " << FunctionName 2016 << "("; 2017 2018 bool FirstArg = true; 2019 for (ArgTy::const_iterator I = Args.begin(), E = Args.end(); I != E; I++) { 2020 if (!FirstArg) 2021 mOut << ", "; 2022 else 2023 FirstArg = false; 2024 2025 mOut << I->first << " " << I->second; 2026 } 2027 2028 mOut << ")"; 2029 mOut.startBlock(); 2030} 2031 2032void RSReflectionJava::endFunction() { mOut.endBlock(); } 2033 2034bool RSReflectionJava::addTypeNameForElement(const std::string &TypeName) { 2035 if (mTypesToCheck.find(TypeName) == mTypesToCheck.end()) { 2036 mTypesToCheck.insert(TypeName); 2037 return true; 2038 } else { 2039 return false; 2040 } 2041} 2042 2043bool RSReflectionJava::addTypeNameForFieldPacker(const std::string &TypeName) { 2044 if (mFieldPackerTypes.find(TypeName) == mFieldPackerTypes.end()) { 2045 mFieldPackerTypes.insert(TypeName); 2046 return true; 2047 } else { 2048 return false; 2049 } 2050} 2051 2052} // namespace slang 2053