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