slang_rs_reflection.cpp revision bcae1fe692a8c5d9225a9699a932380b5659a735
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  C.startFunction(Context::AM_Public,
670                  false,
671                  "void",
672                  "forEach_" + EF->getName(),
673                  Args);
674
675  const RSExportType *IET = EF->getInType();
676  if (IET) {
677    genTypeCheck(C, IET, "ain");
678  }
679
680  const RSExportType *OET = EF->getOutType();
681  if (OET) {
682    genTypeCheck(C, OET, "aout");
683  }
684
685  if (EF->hasIn() && (EF->hasOut() || EF->hasReturn())) {
686    C.indent() << "// Verify dimensions" << std::endl;
687    C.indent() << "Type tIn = ain.getType();" << std::endl;
688    C.indent() << "Type tOut = aout.getType();" << std::endl;
689    C.indent() << "if ((tIn.getCount() != tOut.getCount()) ||" << std::endl;
690    C.indent() << "    (tIn.getX() != tOut.getX()) ||" << std::endl;
691    C.indent() << "    (tIn.getY() != tOut.getY()) ||" << std::endl;
692    C.indent() << "    (tIn.getZ() != tOut.getZ()) ||" << std::endl;
693    C.indent() << "    (tIn.hasFaces() != tOut.hasFaces()) ||" << std::endl;
694    C.indent() << "    (tIn.hasMipmaps() != tOut.hasMipmaps())) {" << std::endl;
695    C.indent() << "    throw new RSRuntimeException(\"Dimension mismatch "
696               << "between input and output parameters!\");";
697    C.out()    << std::endl;
698    C.indent() << "}" << std::endl;
699  }
700
701  std::string FieldPackerName = EF->getName() + "_fp";
702  if (ERT) {
703    if (genCreateFieldPacker(C, ERT, FieldPackerName.c_str())) {
704      genPackVarOfType(C, ERT, NULL, FieldPackerName.c_str());
705    }
706  }
707  C.indent() << "forEach("RS_EXPORT_FOREACH_INDEX_PREFIX << EF->getName();
708
709  if (EF->hasIn())
710    C.out() << ", ain";
711  else
712    C.out() << ", null";
713
714  if (EF->hasOut() || EF->hasReturn())
715    C.out() << ", aout";
716  else
717    C.out() << ", null";
718
719  if (EF->hasUsrData())
720    C.out() << ", " << FieldPackerName;
721  else
722    C.out() << ", null";
723
724  C.out() << ");" << std::endl;
725
726  C.endFunction();
727  return;
728}
729
730void RSReflection::genTypeInstanceFromPointer(Context &C,
731                                              const RSExportType *ET) {
732  if (ET->getClass() == RSExportType::ExportClassPointer) {
733    // For pointer parameters to original forEach kernels.
734    const RSExportPointerType *EPT =
735        static_cast<const RSExportPointerType*>(ET);
736    genTypeInstance(C, EPT->getPointeeType());
737  } else {
738    // For handling pass-by-value kernel parameters.
739    genTypeInstance(C, ET);
740  }
741}
742
743void RSReflection::genTypeInstance(Context &C,
744                                   const RSExportType *ET) {
745  switch (ET->getClass()) {
746    case RSExportType::ExportClassPrimitive:
747    case RSExportType::ExportClassVector:
748    case RSExportType::ExportClassConstantArray: {
749      std::string TypeName = ET->getElementName();
750      if (C.addTypeNameForElement(TypeName)) {
751        C.indent() << RS_ELEM_PREFIX << TypeName << " = Element." << TypeName
752                   << "(rs);" << std::endl;
753      }
754      break;
755    }
756
757    case RSExportType::ExportClassRecord: {
758      std::string ClassName = ET->getElementName();
759      if (C.addTypeNameForElement(ClassName)) {
760        C.indent() << RS_ELEM_PREFIX << ClassName << " = " << ClassName <<
761                      ".createElement(rs);" << std::endl;
762      }
763      break;
764    }
765
766    default:
767      break;
768  }
769}
770
771void RSReflection::genFieldPackerInstance(Context &C,
772                                          const RSExportType *ET) {
773  switch (ET->getClass()) {
774    case RSExportType::ExportClassPrimitive:
775    case RSExportType::ExportClassVector:
776    case RSExportType::ExportClassConstantArray:
777    case RSExportType::ExportClassRecord: {
778      std::string TypeName = ET->getElementName();
779      C.addTypeNameForFieldPacker(TypeName);
780      break;
781    }
782
783    default:
784      break;
785  }
786}
787
788void RSReflection::genTypeCheck(Context &C,
789                                const RSExportType *ET,
790                                const char *VarName) {
791  C.indent() << "// check " << VarName << std::endl;
792
793  if (ET->getClass() == RSExportType::ExportClassPointer) {
794    const RSExportPointerType *EPT =
795        static_cast<const RSExportPointerType*>(ET);
796    ET = EPT->getPointeeType();
797  }
798
799  std::string TypeName;
800
801  switch (ET->getClass()) {
802    case RSExportType::ExportClassPrimitive:
803    case RSExportType::ExportClassVector:
804    case RSExportType::ExportClassRecord: {
805      TypeName = ET->getElementName();
806      break;
807    }
808
809    default:
810      break;
811  }
812
813  if (!TypeName.empty()) {
814    C.indent() << "if (!" << VarName
815               << ".getType().getElement().isCompatible(" RS_ELEM_PREFIX
816               << TypeName << ")) {" << std::endl;
817    C.indent() << "    throw new RSRuntimeException(\"Type mismatch with "
818               << TypeName << "!\");" << std::endl;
819    C.indent() << "}" << std::endl;
820  }
821
822  return;
823}
824
825
826void RSReflection::genPrimitiveTypeExportVariable(
827    Context &C,
828    const RSExportVar *EV) {
829  slangAssert((EV->getType()->getClass() == RSExportType::ExportClassPrimitive)
830              && "Variable should be type of primitive here");
831
832  const RSExportPrimitiveType *EPT =
833      static_cast<const RSExportPrimitiveType*>(EV->getType());
834  std::string TypeName = GetTypeName(EPT);
835  std::string VarName = EV->getName();
836
837  genPrivateExportVariable(C, TypeName, EV->getName());
838
839  if (EV->isConst()) {
840    C.indent() << "public final static " << TypeName
841               << " " RS_EXPORT_VAR_CONST_PREFIX << VarName << " = ";
842    const clang::APValue &Val = EV->getInit();
843    C.out() << RSReflectionBase::genInitValue(Val, EPT->getType() ==
844        RSExportPrimitiveType::DataTypeBoolean) << ";" << std::endl;
845  } else {
846    // set_*()
847    // This must remain synchronized, since multiple Dalvik threads may
848    // be calling setters.
849    C.startFunction(Context::AM_PublicSynchronized,
850                    false,
851                    "void",
852                    "set_" + VarName,
853                    1,
854                    TypeName.c_str(), "v");
855    if ((EPT->getSize() < 4) || EV->isUnsigned()) {
856      // We create/cache a per-type FieldPacker. This allows us to reuse the
857      // validation logic (for catching negative inputs from Dalvik, as well
858      // as inputs that are too large to be represented in the unsigned type).
859      // Sub-integer types are also handled specially here, so that we don't
860      // overwrite bytes accidentally.
861      std::string ElemName = EPT->getElementName();
862      std::string FPName;
863      FPName = RS_FP_PREFIX + ElemName;
864      C.indent() << "if (" << FPName << "!= null) {"
865                 << std::endl;
866      C.incIndentLevel();
867      C.indent() << FPName << ".reset();" << std::endl;
868      C.decIndentLevel();
869      C.indent() << "} else {" << std::endl;
870      C.incIndentLevel();
871      C.indent() << FPName << " = new FieldPacker("
872                 << EPT->getSize() << ");" << std::endl;
873      C.decIndentLevel();
874      C.indent() << "}" << std::endl;
875
876      genPackVarOfType(C, EPT, "v", FPName.c_str());
877      C.indent() << "setVar("RS_EXPORT_VAR_INDEX_PREFIX << VarName
878                 << ", " << FPName << ");" << std::endl;
879    } else {
880      C.indent() << "setVar("RS_EXPORT_VAR_INDEX_PREFIX << VarName
881                 << ", v);" << std::endl;
882    }
883
884    // Dalvik update comes last, since the input may be invalid (and hence
885    // throw an exception).
886    C.indent() << RS_EXPORT_VAR_PREFIX << VarName << " = v;" << std::endl;
887
888    C.endFunction();
889  }
890
891  genGetExportVariable(C, TypeName, VarName);
892  return;
893}
894
895void RSReflection::genPointerTypeExportVariable(Context &C,
896                                                const RSExportVar *EV) {
897  const RSExportType *ET = EV->getType();
898  const RSExportType *PointeeType;
899
900  slangAssert((ET->getClass() == RSExportType::ExportClassPointer) &&
901              "Variable should be type of pointer here");
902
903  PointeeType = static_cast<const RSExportPointerType*>(ET)->getPointeeType();
904  std::string TypeName = GetTypeName(ET);
905  std::string VarName = EV->getName();
906
907  genPrivateExportVariable(C, TypeName, VarName);
908
909  // bind_*()
910  C.startFunction(Context::AM_Public,
911                  false,
912                  "void",
913                  "bind_" + VarName,
914                  1,
915                  TypeName.c_str(), "v");
916
917  C.indent() << RS_EXPORT_VAR_PREFIX << VarName << " = v;" << std::endl;
918  C.indent() << "if (v == null) bindAllocation(null, "RS_EXPORT_VAR_INDEX_PREFIX
919             << VarName << ");" << std::endl;
920
921  if (PointeeType->getClass() == RSExportType::ExportClassRecord)
922    C.indent() << "else bindAllocation(v.getAllocation(), "
923        RS_EXPORT_VAR_INDEX_PREFIX << VarName << ");"
924               << std::endl;
925  else
926    C.indent() << "else bindAllocation(v, "RS_EXPORT_VAR_INDEX_PREFIX
927               << VarName << ");" << std::endl;
928
929  C.endFunction();
930
931  genGetExportVariable(C, TypeName, VarName);
932  return;
933}
934
935void RSReflection::genVectorTypeExportVariable(Context &C,
936                                               const RSExportVar *EV) {
937  slangAssert((EV->getType()->getClass() == RSExportType::ExportClassVector) &&
938              "Variable should be type of vector here");
939
940  std::string TypeName = GetTypeName(EV->getType());
941  std::string VarName = EV->getName();
942
943  genPrivateExportVariable(C, TypeName, VarName);
944  genSetExportVariable(C, TypeName, EV);
945  genGetExportVariable(C, TypeName, VarName);
946  return;
947}
948
949void RSReflection::genMatrixTypeExportVariable(Context &C,
950                                               const RSExportVar *EV) {
951  slangAssert((EV->getType()->getClass() == RSExportType::ExportClassMatrix) &&
952              "Variable should be type of matrix here");
953
954    const RSExportType *ET = EV->getType();
955  std::string TypeName = GetTypeName(ET);
956  std::string VarName = EV->getName();
957
958  genPrivateExportVariable(C, TypeName, VarName);
959
960  // set_*()
961  if (!EV->isConst()) {
962    const char *FieldPackerName = "fp";
963    C.startFunction(Context::AM_PublicSynchronized,
964                    false,
965                    "void",
966                    "set_" + VarName,
967                    1,
968                    TypeName.c_str(), "v");
969    C.indent() << RS_EXPORT_VAR_PREFIX << VarName << " = v;" << std::endl;
970
971    if (genCreateFieldPacker(C, ET, FieldPackerName))
972      genPackVarOfType(C, ET, "v", FieldPackerName);
973    C.indent() << "setVar("RS_EXPORT_VAR_INDEX_PREFIX << VarName << ", "
974               << FieldPackerName << ");" << std::endl;
975
976    C.endFunction();
977  }
978
979  genGetExportVariable(C, TypeName, VarName);
980  return;
981}
982
983void RSReflection::genConstantArrayTypeExportVariable(
984    Context &C,
985    const RSExportVar *EV) {
986  slangAssert((EV->getType()->getClass() ==
987               RSExportType::ExportClassConstantArray) &&
988              "Variable should be type of constant array here");
989
990  std::string TypeName = GetTypeName(EV->getType());
991  std::string VarName = EV->getName();
992
993  genPrivateExportVariable(C, TypeName, VarName);
994  genSetExportVariable(C, TypeName, EV);
995  genGetExportVariable(C, TypeName, VarName);
996  return;
997}
998
999void RSReflection::genRecordTypeExportVariable(Context &C,
1000                                               const RSExportVar *EV) {
1001  slangAssert((EV->getType()->getClass() == RSExportType::ExportClassRecord) &&
1002              "Variable should be type of struct here");
1003
1004  std::string TypeName = GetTypeName(EV->getType());
1005  std::string VarName = EV->getName();
1006
1007  genPrivateExportVariable(C, TypeName, VarName);
1008  genSetExportVariable(C, TypeName, EV);
1009  genGetExportVariable(C, TypeName, VarName);
1010  return;
1011}
1012
1013void RSReflection::genPrivateExportVariable(Context &C,
1014                                            const std::string &TypeName,
1015                                            const std::string &VarName) {
1016  C.indent() << "private " << TypeName << " "RS_EXPORT_VAR_PREFIX
1017             << VarName << ";" << std::endl;
1018  return;
1019}
1020
1021void RSReflection::genSetExportVariable(Context &C,
1022                                        const std::string &TypeName,
1023                                        const RSExportVar *EV) {
1024  if (!EV->isConst()) {
1025    const char *FieldPackerName = "fp";
1026    std::string VarName = EV->getName();
1027    const RSExportType *ET = EV->getType();
1028    C.startFunction(Context::AM_PublicSynchronized,
1029                    false,
1030                    "void",
1031                    "set_" + VarName,
1032                    1,
1033                    TypeName.c_str(), "v");
1034    C.indent() << RS_EXPORT_VAR_PREFIX << VarName << " = v;" << std::endl;
1035
1036    if (genCreateFieldPacker(C, ET, FieldPackerName))
1037      genPackVarOfType(C, ET, "v", FieldPackerName);
1038
1039    if (mRSContext->getTargetAPI() < SLANG_JB_TARGET_API) {
1040      // Legacy apps must use the old setVar() without Element/dim components.
1041      C.indent() << "setVar("RS_EXPORT_VAR_INDEX_PREFIX << VarName
1042                 << ", " << FieldPackerName << ");" << std::endl;
1043    } else {
1044      // We only have support for one-dimensional array reflection today,
1045      // but the entry point (i.e. setVar()) takes an array of dimensions.
1046      C.indent() << "int []__dimArr = new int[1];" << std::endl;
1047      C.indent() << "__dimArr[0] = " << ET->getSize() << ";" << std::endl;
1048      C.indent() << "setVar("RS_EXPORT_VAR_INDEX_PREFIX << VarName << ", "
1049                 << FieldPackerName << ", " RS_ELEM_PREFIX
1050                 << ET->getElementName() << ", __dimArr);" << std::endl;
1051    }
1052
1053    C.endFunction();
1054  }
1055  return;
1056}
1057
1058void RSReflection::genGetExportVariable(Context &C,
1059                                        const std::string &TypeName,
1060                                        const std::string &VarName) {
1061  C.startFunction(Context::AM_Public,
1062                  false,
1063                  TypeName.c_str(),
1064                  "get_" + VarName,
1065                  0);
1066
1067  C.indent() << "return "RS_EXPORT_VAR_PREFIX << VarName << ";" << std::endl;
1068
1069  C.endFunction();
1070  return;
1071}
1072
1073/******************* Methods to generate script class /end *******************/
1074
1075bool RSReflection::genCreateFieldPacker(Context &C,
1076                                        const RSExportType *ET,
1077                                        const char *FieldPackerName) {
1078  size_t AllocSize = RSExportType::GetTypeAllocSize(ET);
1079  if (AllocSize > 0)
1080    C.indent() << "FieldPacker " << FieldPackerName << " = new FieldPacker("
1081               << AllocSize << ");" << std::endl;
1082  else
1083    return false;
1084  return true;
1085}
1086
1087void RSReflection::genPackVarOfType(Context &C,
1088                                    const RSExportType *ET,
1089                                    const char *VarName,
1090                                    const char *FieldPackerName) {
1091  switch (ET->getClass()) {
1092    case RSExportType::ExportClassPrimitive:
1093    case RSExportType::ExportClassVector: {
1094      C.indent() << FieldPackerName << "."
1095                 << GetPackerAPIName(
1096                     static_cast<const RSExportPrimitiveType*>(ET))
1097                 << "(" << VarName << ");" << std::endl;
1098      break;
1099    }
1100    case RSExportType::ExportClassPointer: {
1101      // Must reflect as type Allocation in Java
1102      const RSExportType *PointeeType =
1103          static_cast<const RSExportPointerType*>(ET)->getPointeeType();
1104
1105      if (PointeeType->getClass() != RSExportType::ExportClassRecord)
1106        C.indent() << FieldPackerName << ".addI32(" << VarName
1107                   << ".getPtr());" << std::endl;
1108      else
1109        C.indent() << FieldPackerName << ".addI32(" << VarName
1110                   << ".getAllocation().getPtr());" << std::endl;
1111      break;
1112    }
1113    case RSExportType::ExportClassMatrix: {
1114      C.indent() << FieldPackerName << ".addMatrix(" << VarName << ");"
1115                 << std::endl;
1116      break;
1117    }
1118    case RSExportType::ExportClassConstantArray: {
1119      const RSExportConstantArrayType *ECAT =
1120          static_cast<const RSExportConstantArrayType *>(ET);
1121
1122      // TODO(zonr): more elegant way. Currently, we obtain the unique index
1123      //             variable (this method involves recursive call which means
1124      //             we may have more than one level loop, therefore we can't
1125      //             always use the same index variable name here) name given
1126      //             in the for-loop from counting the '.' in @VarName.
1127      unsigned Level = 0;
1128      size_t LastDotPos = 0;
1129      std::string ElementVarName(VarName);
1130
1131      while (LastDotPos != std::string::npos) {
1132        LastDotPos = ElementVarName.find_first_of('.', LastDotPos + 1);
1133        Level++;
1134      }
1135      std::string IndexVarName("ct");
1136      IndexVarName.append(llvm::utostr_32(Level));
1137
1138      C.indent() << "for (int " << IndexVarName << " = 0; " <<
1139                          IndexVarName << " < " << ECAT->getSize() << "; " <<
1140                          IndexVarName << "++)";
1141      C.startBlock();
1142
1143      ElementVarName.append("[" + IndexVarName + "]");
1144      genPackVarOfType(C, ECAT->getElementType(), ElementVarName.c_str(),
1145                       FieldPackerName);
1146
1147      C.endBlock();
1148      break;
1149    }
1150    case RSExportType::ExportClassRecord: {
1151      const RSExportRecordType *ERT =
1152          static_cast<const RSExportRecordType*>(ET);
1153      // Relative pos from now on in field packer
1154      unsigned Pos = 0;
1155
1156      for (RSExportRecordType::const_field_iterator I = ERT->fields_begin(),
1157               E = ERT->fields_end();
1158           I != E;
1159           I++) {
1160        const RSExportRecordType::Field *F = *I;
1161        std::string FieldName;
1162        size_t FieldOffset = F->getOffsetInParent();
1163        size_t FieldStoreSize = RSExportType::GetTypeStoreSize(F->getType());
1164        size_t FieldAllocSize = RSExportType::GetTypeAllocSize(F->getType());
1165
1166        if (VarName != NULL)
1167          FieldName = VarName + ("." + F->getName());
1168        else
1169          FieldName = F->getName();
1170
1171        if (FieldOffset > Pos)
1172          C.indent() << FieldPackerName << ".skip("
1173                     << (FieldOffset - Pos) << ");" << std::endl;
1174
1175        genPackVarOfType(C, F->getType(), FieldName.c_str(), FieldPackerName);
1176
1177        // There is padding in the field type
1178        if (FieldAllocSize > FieldStoreSize)
1179            C.indent() << FieldPackerName << ".skip("
1180                       << (FieldAllocSize - FieldStoreSize)
1181                       << ");" << std::endl;
1182
1183          Pos = FieldOffset + FieldAllocSize;
1184      }
1185
1186      // There maybe some padding after the struct
1187      if (RSExportType::GetTypeAllocSize(ERT) > Pos)
1188        C.indent() << FieldPackerName << ".skip("
1189                   << RSExportType::GetTypeAllocSize(ERT) - Pos << ");"
1190                   << std::endl;
1191      break;
1192    }
1193    default: {
1194      slangAssert(false && "Unknown class of type");
1195    }
1196  }
1197
1198  return;
1199}
1200
1201void RSReflection::genAllocateVarOfType(Context &C,
1202                                        const RSExportType *T,
1203                                        const std::string &VarName) {
1204  switch (T->getClass()) {
1205    case RSExportType::ExportClassPrimitive: {
1206      // Primitive type like int in Java has its own storage once it's declared.
1207      //
1208      // FIXME: Should we allocate storage for RS object?
1209      // if (static_cast<const RSExportPrimitiveType *>(T)->isRSObjectType())
1210      //  C.indent() << VarName << " = new " << GetTypeName(T) << "();"
1211      //             << std::endl;
1212      break;
1213    }
1214    case RSExportType::ExportClassPointer: {
1215      // Pointer type is an instance of Allocation or a TypeClass whose value is
1216      // expected to be assigned by programmer later in Java program. Therefore
1217      // we don't reflect things like [VarName] = new Allocation();
1218      C.indent() << VarName << " = null;" << std::endl;
1219      break;
1220    }
1221    case RSExportType::ExportClassConstantArray: {
1222      const RSExportConstantArrayType *ECAT =
1223          static_cast<const RSExportConstantArrayType *>(T);
1224      const RSExportType *ElementType = ECAT->getElementType();
1225
1226      C.indent() << VarName << " = new " << GetTypeName(ElementType)
1227                 << "[" << ECAT->getSize() << "];" << std::endl;
1228
1229      // Primitive type element doesn't need allocation code.
1230      if (ElementType->getClass() != RSExportType::ExportClassPrimitive) {
1231        C.indent() << "for (int $ct = 0; $ct < " << ECAT->getSize() << "; "
1232                            "$ct++)";
1233        C.startBlock();
1234
1235        std::string ElementVarName(VarName);
1236        ElementVarName.append("[$ct]");
1237        genAllocateVarOfType(C, ElementType, ElementVarName);
1238
1239        C.endBlock();
1240      }
1241      break;
1242    }
1243    case RSExportType::ExportClassVector:
1244    case RSExportType::ExportClassMatrix:
1245    case RSExportType::ExportClassRecord: {
1246      C.indent() << VarName << " = new " << GetTypeName(T) << "();"
1247                 << std::endl;
1248      break;
1249    }
1250  }
1251  return;
1252}
1253
1254void RSReflection::genNewItemBufferIfNull(Context &C,
1255                                          const char *Index) {
1256  C.indent() << "if (" RS_TYPE_ITEM_BUFFER_NAME " == null) "
1257                  RS_TYPE_ITEM_BUFFER_NAME " = "
1258                    "new " RS_TYPE_ITEM_CLASS_NAME
1259                      "[getType().getX() /* count */];"
1260             << std::endl;
1261  if (Index != NULL)
1262    C.indent() << "if ("RS_TYPE_ITEM_BUFFER_NAME"[" << Index << "] == null) "
1263                    RS_TYPE_ITEM_BUFFER_NAME"[" << Index << "] = "
1264                      "new "RS_TYPE_ITEM_CLASS_NAME"();" << std::endl;
1265  return;
1266}
1267
1268void RSReflection::genNewItemBufferPackerIfNull(Context &C) {
1269  C.indent() << "if (" RS_TYPE_ITEM_BUFFER_PACKER_NAME " == null) "
1270                  RS_TYPE_ITEM_BUFFER_PACKER_NAME " = "
1271                    "new FieldPacker(" RS_TYPE_ITEM_CLASS_NAME
1272                      ".sizeof * getType().getX()/* count */"
1273                        ");" << std::endl;
1274  return;
1275}
1276
1277/********************** Methods to generate type class  **********************/
1278bool RSReflection::genTypeClass(Context &C,
1279                                const RSExportRecordType *ERT,
1280                                std::string &ErrorMsg) {
1281  std::string ClassName = ERT->getElementName();
1282
1283  if (!C.startClass(Context::AM_Public,
1284                    false,
1285                    ClassName,
1286                    RS_TYPE_CLASS_SUPER_CLASS_NAME,
1287                    ErrorMsg))
1288    return false;
1289
1290  mGeneratedFileNames->push_back(ClassName);
1291
1292  genTypeItemClass(C, ERT);
1293
1294  // Declare item buffer and item buffer packer
1295  C.indent() << "private "RS_TYPE_ITEM_CLASS_NAME" "RS_TYPE_ITEM_BUFFER_NAME"[]"
1296      ";" << std::endl;
1297  C.indent() << "private FieldPacker "RS_TYPE_ITEM_BUFFER_PACKER_NAME";"
1298             << std::endl;
1299  C.indent() << "private static java.lang.ref.WeakReference<Element> "
1300             RS_TYPE_ELEMENT_REF_NAME
1301             " = new java.lang.ref.WeakReference<Element>(null);" << std::endl;
1302
1303  genTypeClassConstructor(C, ERT);
1304  genTypeClassCopyToArrayLocal(C, ERT);
1305  genTypeClassCopyToArray(C, ERT);
1306  genTypeClassItemSetter(C, ERT);
1307  genTypeClassItemGetter(C, ERT);
1308  genTypeClassComponentSetter(C, ERT);
1309  genTypeClassComponentGetter(C, ERT);
1310  genTypeClassCopyAll(C, ERT);
1311  genTypeClassResize(C);
1312
1313  C.endClass();
1314
1315  C.resetFieldIndex();
1316  C.clearFieldIndexMap();
1317
1318  return true;
1319}
1320
1321void RSReflection::genTypeItemClass(Context &C,
1322                                    const RSExportRecordType *ERT) {
1323  C.indent() << "static public class "RS_TYPE_ITEM_CLASS_NAME;
1324  C.startBlock();
1325
1326  C.indent() << "public static final int sizeof = "
1327             << RSExportType::GetTypeAllocSize(ERT) << ";" << std::endl;
1328
1329  // Member elements
1330  C.out() << std::endl;
1331  for (RSExportRecordType::const_field_iterator FI = ERT->fields_begin(),
1332           FE = ERT->fields_end();
1333       FI != FE;
1334       FI++) {
1335    C.indent() << GetTypeName((*FI)->getType()) << " " << (*FI)->getName()
1336               << ";" << std::endl;
1337  }
1338
1339  // Constructor
1340  C.out() << std::endl;
1341  C.indent() << RS_TYPE_ITEM_CLASS_NAME"()";
1342  C.startBlock();
1343
1344  for (RSExportRecordType::const_field_iterator FI = ERT->fields_begin(),
1345           FE = ERT->fields_end();
1346       FI != FE;
1347       FI++) {
1348    const RSExportRecordType::Field *F = *FI;
1349    genAllocateVarOfType(C, F->getType(), F->getName());
1350  }
1351
1352  // end Constructor
1353  C.endBlock();
1354
1355  // end Item class
1356  C.endBlock();
1357
1358  return;
1359}
1360
1361void RSReflection::genTypeClassConstructor(Context &C,
1362                                           const RSExportRecordType *ERT) {
1363  const char *RenderScriptVar = "rs";
1364
1365  C.startFunction(Context::AM_Public,
1366                  true,
1367                  "Element",
1368                  "createElement",
1369                  1,
1370                  "RenderScript", RenderScriptVar);
1371
1372  // TODO(all): Fix weak-refs + multi-context issue.
1373  // C.indent() << "Element e = " << RS_TYPE_ELEMENT_REF_NAME
1374  //            << ".get();" << std::endl;
1375  // C.indent() << "if (e != null) return e;" << std::endl;
1376  genBuildElement(C, "eb", ERT, RenderScriptVar, /* IsInline = */true);
1377  C.indent() << "return eb.create();" << std::endl;
1378  // C.indent() << "e = eb.create();" << std::endl;
1379  // C.indent() << RS_TYPE_ELEMENT_REF_NAME
1380  //            << " = new java.lang.ref.WeakReference<Element>(e);"
1381  //            << std::endl;
1382  // C.indent() << "return e;" << std::endl;
1383  C.endFunction();
1384
1385
1386  // private with element
1387  C.startFunction(Context::AM_Private,
1388                  false,
1389                  NULL,
1390                  C.getClassName(),
1391                  1,
1392                  "RenderScript", RenderScriptVar);
1393  C.indent() << RS_TYPE_ITEM_BUFFER_NAME" = null;" << std::endl;
1394  C.indent() << RS_TYPE_ITEM_BUFFER_PACKER_NAME" = null;" << std::endl;
1395  C.indent() << "mElement = createElement(" << RenderScriptVar << ");"
1396             << std::endl;
1397  C.endFunction();
1398
1399  // 1D without usage
1400  C.startFunction(Context::AM_Public,
1401                  false,
1402                  NULL,
1403                  C.getClassName(),
1404                  2,
1405                  "RenderScript", RenderScriptVar,
1406                  "int", "count");
1407
1408  C.indent() << RS_TYPE_ITEM_BUFFER_NAME" = null;" << std::endl;
1409  C.indent() << RS_TYPE_ITEM_BUFFER_PACKER_NAME" = null;" << std::endl;
1410  C.indent() << "mElement = createElement(" << RenderScriptVar << ");"
1411             << std::endl;
1412  // Call init() in super class
1413  C.indent() << "init(" << RenderScriptVar << ", count);" << std::endl;
1414  C.endFunction();
1415
1416  // 1D with usage
1417  C.startFunction(Context::AM_Public,
1418                  false,
1419                  NULL,
1420                  C.getClassName(),
1421                  3,
1422                  "RenderScript", RenderScriptVar,
1423                  "int", "count",
1424                  "int", "usages");
1425
1426  C.indent() << RS_TYPE_ITEM_BUFFER_NAME" = null;" << std::endl;
1427  C.indent() << RS_TYPE_ITEM_BUFFER_PACKER_NAME" = null;" << std::endl;
1428  C.indent() << "mElement = createElement(" << RenderScriptVar << ");"
1429             << std::endl;
1430  // Call init() in super class
1431  C.indent() << "init(" << RenderScriptVar << ", count, usages);" << std::endl;
1432  C.endFunction();
1433
1434
1435  // create1D with usage
1436  C.startFunction(Context::AM_Public,
1437                  true,
1438                  C.getClassName().c_str(),
1439                  "create1D",
1440                  3,
1441                  "RenderScript", RenderScriptVar,
1442                  "int", "dimX",
1443                  "int", "usages");
1444  C.indent() << C.getClassName() << " obj = new " << C.getClassName() << "("
1445             << RenderScriptVar << ");" << std::endl;
1446  C.indent() << "obj.mAllocation = Allocation.createSized("
1447                "rs, obj.mElement, dimX, usages);" << std::endl;
1448  C.indent() << "return obj;" << std::endl;
1449  C.endFunction();
1450
1451  // create1D without usage
1452  C.startFunction(Context::AM_Public,
1453                  true,
1454                  C.getClassName().c_str(),
1455                  "create1D",
1456                  2,
1457                  "RenderScript", RenderScriptVar,
1458                  "int", "dimX");
1459  C.indent() << "return create1D(" << RenderScriptVar
1460             << ", dimX, Allocation.USAGE_SCRIPT);" << std::endl;
1461  C.endFunction();
1462
1463
1464  // create2D without usage
1465  C.startFunction(Context::AM_Public,
1466                  true,
1467                  C.getClassName().c_str(),
1468                  "create2D",
1469                  3,
1470                  "RenderScript", RenderScriptVar,
1471                  "int", "dimX",
1472                  "int", "dimY");
1473  C.indent() << "return create2D(" << RenderScriptVar
1474             << ", dimX, dimY, Allocation.USAGE_SCRIPT);" << std::endl;
1475  C.endFunction();
1476
1477  // create2D with usage
1478  C.startFunction(Context::AM_Public,
1479                  true,
1480                  C.getClassName().c_str(),
1481                  "create2D",
1482                  4,
1483                  "RenderScript", RenderScriptVar,
1484                  "int", "dimX",
1485                  "int", "dimY",
1486                  "int", "usages");
1487
1488  C.indent() << C.getClassName() << " obj = new " << C.getClassName() << "("
1489             << RenderScriptVar << ");" << std::endl;
1490  C.indent() << "Type.Builder b = new Type.Builder(rs, obj.mElement);"
1491             << std::endl;
1492  C.indent() << "b.setX(dimX);" << std::endl;
1493  C.indent() << "b.setY(dimY);" << std::endl;
1494  C.indent() << "Type t = b.create();" << std::endl;
1495  C.indent() << "obj.mAllocation = Allocation.createTyped(rs, t, usages);"
1496             << std::endl;
1497  C.indent() << "return obj;" << std::endl;
1498  C.endFunction();
1499
1500
1501  // createTypeBuilder
1502  C.startFunction(Context::AM_Public,
1503                  true,
1504                  "Type.Builder",
1505                  "createTypeBuilder",
1506                  1,
1507                  "RenderScript", RenderScriptVar);
1508  C.indent() << "Element e = createElement(" << RenderScriptVar << ");"
1509             << std::endl;
1510  C.indent() << "return new Type.Builder(rs, e);" << std::endl;
1511  C.endFunction();
1512
1513  // createCustom with usage
1514  C.startFunction(Context::AM_Public,
1515                  true,
1516                  C.getClassName().c_str(),
1517                  "createCustom",
1518                  3,
1519                  "RenderScript", RenderScriptVar,
1520                  "Type.Builder", "tb",
1521                  "int", "usages");
1522  C.indent() << C.getClassName() << " obj = new " << C.getClassName() << "("
1523             << RenderScriptVar << ");" << std::endl;
1524  C.indent() << "Type t = tb.create();" << std::endl;
1525  C.indent() << "if (t.getElement() != obj.mElement) {" << std::endl;
1526  C.indent() << "    throw new RSIllegalArgumentException("
1527                "\"Type.Builder did not match expected element type.\");"
1528             << std::endl;
1529  C.indent() << "}" << std::endl;
1530  C.indent() << "obj.mAllocation = Allocation.createTyped(rs, t, usages);"
1531             << std::endl;
1532  C.indent() << "return obj;" << std::endl;
1533  C.endFunction();
1534}
1535
1536
1537void RSReflection::genTypeClassCopyToArray(Context &C,
1538                                           const RSExportRecordType *ERT) {
1539  C.startFunction(Context::AM_Private,
1540                  false,
1541                  "void",
1542                  "copyToArray",
1543                  2,
1544                  RS_TYPE_ITEM_CLASS_NAME, "i",
1545                  "int", "index");
1546
1547  genNewItemBufferPackerIfNull(C);
1548  C.indent() << RS_TYPE_ITEM_BUFFER_PACKER_NAME
1549                ".reset(index * "RS_TYPE_ITEM_CLASS_NAME".sizeof);"
1550             << std::endl;
1551
1552  C.indent() << "copyToArrayLocal(i, " RS_TYPE_ITEM_BUFFER_PACKER_NAME
1553                ");" << std::endl;
1554
1555  C.endFunction();
1556  return;
1557}
1558
1559void RSReflection::genTypeClassCopyToArrayLocal(Context &C,
1560                                                const RSExportRecordType *ERT) {
1561  C.startFunction(Context::AM_Private,
1562                  false,
1563                  "void",
1564                  "copyToArrayLocal",
1565                  2,
1566                  RS_TYPE_ITEM_CLASS_NAME, "i",
1567                  "FieldPacker", "fp");
1568
1569  genPackVarOfType(C, ERT, "i", "fp");
1570
1571  C.endFunction();
1572  return;
1573}
1574
1575void RSReflection::genTypeClassItemSetter(Context &C,
1576                                          const RSExportRecordType *ERT) {
1577  C.startFunction(Context::AM_PublicSynchronized,
1578                  false,
1579                  "void",
1580                  "set",
1581                  3,
1582                  RS_TYPE_ITEM_CLASS_NAME, "i",
1583                  "int", "index",
1584                  "boolean", "copyNow");
1585  genNewItemBufferIfNull(C, NULL);
1586  C.indent() << RS_TYPE_ITEM_BUFFER_NAME"[index] = i;" << std::endl;
1587
1588  C.indent() << "if (copyNow) ";
1589  C.startBlock();
1590
1591  C.indent() << "copyToArray(i, index);" << std::endl;
1592  C.indent() << "FieldPacker fp = new FieldPacker(" RS_TYPE_ITEM_CLASS_NAME
1593                ".sizeof);" << std::endl;
1594  C.indent() << "copyToArrayLocal(i, fp);" << std::endl;
1595  C.indent() << "mAllocation.setFromFieldPacker(index, fp);" << std::endl;
1596
1597  // End of if (copyNow)
1598  C.endBlock();
1599
1600  C.endFunction();
1601  return;
1602}
1603
1604void RSReflection::genTypeClassItemGetter(Context &C,
1605                                          const RSExportRecordType *ERT) {
1606  C.startFunction(Context::AM_PublicSynchronized,
1607                  false,
1608                  RS_TYPE_ITEM_CLASS_NAME,
1609                  "get",
1610                  1,
1611                  "int", "index");
1612  C.indent() << "if ("RS_TYPE_ITEM_BUFFER_NAME" == null) return null;"
1613             << std::endl;
1614  C.indent() << "return "RS_TYPE_ITEM_BUFFER_NAME"[index];" << std::endl;
1615  C.endFunction();
1616  return;
1617}
1618
1619void RSReflection::genTypeClassComponentSetter(Context &C,
1620                                               const RSExportRecordType *ERT) {
1621  for (RSExportRecordType::const_field_iterator FI = ERT->fields_begin(),
1622           FE = ERT->fields_end();
1623       FI != FE;
1624       FI++) {
1625    const RSExportRecordType::Field *F = *FI;
1626    size_t FieldOffset = F->getOffsetInParent();
1627    size_t FieldStoreSize = RSExportType::GetTypeStoreSize(F->getType());
1628    unsigned FieldIndex = C.getFieldIndex(F);
1629
1630    C.startFunction(Context::AM_PublicSynchronized,
1631                    false,
1632                    "void",
1633                    "set_" + F->getName(), 3,
1634                    "int", "index",
1635                    GetTypeName(F->getType()).c_str(), "v",
1636                    "boolean", "copyNow");
1637    genNewItemBufferPackerIfNull(C);
1638    genNewItemBufferIfNull(C, "index");
1639    C.indent() << RS_TYPE_ITEM_BUFFER_NAME"[index]." << F->getName()
1640               << " = v;" << std::endl;
1641
1642    C.indent() << "if (copyNow) ";
1643    C.startBlock();
1644
1645    if (FieldOffset > 0)
1646      C.indent() << RS_TYPE_ITEM_BUFFER_PACKER_NAME
1647                    ".reset(index * "RS_TYPE_ITEM_CLASS_NAME".sizeof + "
1648                 << FieldOffset << ");" << std::endl;
1649    else
1650      C.indent() << RS_TYPE_ITEM_BUFFER_PACKER_NAME
1651                    ".reset(index * "RS_TYPE_ITEM_CLASS_NAME".sizeof);"
1652                 << std::endl;
1653    genPackVarOfType(C, F->getType(), "v", RS_TYPE_ITEM_BUFFER_PACKER_NAME);
1654
1655    C.indent() << "FieldPacker fp = new FieldPacker(" << FieldStoreSize << ");"
1656               << std::endl;
1657    genPackVarOfType(C, F->getType(), "v", "fp");
1658    C.indent() << "mAllocation.setFromFieldPacker(index, " << FieldIndex
1659               << ", fp);"
1660               << std::endl;
1661
1662    // End of if (copyNow)
1663    C.endBlock();
1664
1665    C.endFunction();
1666  }
1667  return;
1668}
1669
1670void RSReflection::genTypeClassComponentGetter(Context &C,
1671                                               const RSExportRecordType *ERT) {
1672  for (RSExportRecordType::const_field_iterator FI = ERT->fields_begin(),
1673           FE = ERT->fields_end();
1674       FI != FE;
1675       FI++) {
1676    const RSExportRecordType::Field *F = *FI;
1677    C.startFunction(Context::AM_PublicSynchronized,
1678                    false,
1679                    GetTypeName(F->getType()).c_str(),
1680                    "get_" + F->getName(),
1681                    1,
1682                    "int", "index");
1683    C.indent() << "if ("RS_TYPE_ITEM_BUFFER_NAME" == null) return "
1684               << GetTypeNullValue(F->getType()) << ";" << std::endl;
1685    C.indent() << "return "RS_TYPE_ITEM_BUFFER_NAME"[index]." << F->getName()
1686               << ";" << std::endl;
1687    C.endFunction();
1688  }
1689  return;
1690}
1691
1692void RSReflection::genTypeClassCopyAll(Context &C,
1693                                       const RSExportRecordType *ERT) {
1694  C.startFunction(Context::AM_PublicSynchronized, false, "void", "copyAll", 0);
1695
1696  C.indent() << "for (int ct = 0; ct < "RS_TYPE_ITEM_BUFFER_NAME".length; ct++)"
1697                  " copyToArray("RS_TYPE_ITEM_BUFFER_NAME"[ct], ct);"
1698             << std::endl;
1699  C.indent() << "mAllocation.setFromFieldPacker(0, "
1700                  RS_TYPE_ITEM_BUFFER_PACKER_NAME");"
1701             << std::endl;
1702
1703  C.endFunction();
1704  return;
1705}
1706
1707void RSReflection::genTypeClassResize(Context &C) {
1708  C.startFunction(Context::AM_PublicSynchronized,
1709                  false,
1710                  "void",
1711                  "resize",
1712                  1,
1713                  "int", "newSize");
1714
1715  C.indent() << "if (mItemArray != null) ";
1716  C.startBlock();
1717  C.indent() << "int oldSize = mItemArray.length;" << std::endl;
1718  C.indent() << "int copySize = Math.min(oldSize, newSize);" << std::endl;
1719  C.indent() << "if (newSize == oldSize) return;" << std::endl;
1720  C.indent() << "Item ni[] = new Item[newSize];" << std::endl;
1721  C.indent() << "System.arraycopy(mItemArray, 0, ni, 0, copySize);"
1722             << std::endl;
1723  C.indent() << "mItemArray = ni;" << std::endl;
1724  C.endBlock();
1725  C.indent() << "mAllocation.resize(newSize);" << std::endl;
1726
1727  C.indent() << "if (" RS_TYPE_ITEM_BUFFER_PACKER_NAME " != null) "
1728                  RS_TYPE_ITEM_BUFFER_PACKER_NAME " = "
1729                    "new FieldPacker(" RS_TYPE_ITEM_CLASS_NAME
1730                      ".sizeof * getType().getX()/* count */"
1731                        ");" << std::endl;
1732
1733  C.endFunction();
1734  return;
1735}
1736
1737/******************** Methods to generate type class /end ********************/
1738
1739/********** Methods to create Element in Java of given record type ***********/
1740void RSReflection::genBuildElement(Context &C,
1741                                   const char *ElementBuilderName,
1742                                   const RSExportRecordType *ERT,
1743                                   const char *RenderScriptVar,
1744                                   bool IsInline) {
1745  C.indent() << "Element.Builder " << ElementBuilderName << " = "
1746      "new Element.Builder(" << RenderScriptVar << ");" << std::endl;
1747
1748  // eb.add(...)
1749  genAddElementToElementBuilder(C,
1750                                ERT,
1751                                "",
1752                                ElementBuilderName,
1753                                RenderScriptVar,
1754                                /* ArraySize = */0);
1755
1756  if (!IsInline)
1757    C.indent() << "return " << ElementBuilderName << ".create();" << std::endl;
1758  return;
1759}
1760
1761#define EB_ADD(x) do {                                              \
1762  C.indent() << ElementBuilderName                                  \
1763             << ".add(" << x << ", \"" << VarName << "\"";  \
1764  if (ArraySize > 0)                                                \
1765    C.out() << ", " << ArraySize;                                   \
1766  C.out() << ");" << std::endl;                                     \
1767  C.incFieldIndex();                                                \
1768} while (false)
1769
1770void RSReflection::genAddElementToElementBuilder(Context &C,
1771                                                 const RSExportType *ET,
1772                                                 const std::string &VarName,
1773                                                 const char *ElementBuilderName,
1774                                                 const char *RenderScriptVar,
1775                                                 unsigned ArraySize) {
1776  std::string ElementConstruct = GetBuiltinElementConstruct(ET);
1777
1778  if (ElementConstruct != "") {
1779    EB_ADD(ElementConstruct << "(" << RenderScriptVar << ")");
1780  } else {
1781    if ((ET->getClass() == RSExportType::ExportClassPrimitive) ||
1782        (ET->getClass() == RSExportType::ExportClassVector)) {
1783      const RSExportPrimitiveType *EPT =
1784          static_cast<const RSExportPrimitiveType*>(ET);
1785      const char *DataTypeName =
1786          RSExportPrimitiveType::getRSReflectionType(EPT)->rs_type;
1787      int Size = (ET->getClass() == RSExportType::ExportClassVector) ?
1788          static_cast<const RSExportVectorType*>(ET)->getNumElement() :
1789          1;
1790
1791      if (EPT->getClass() == RSExportType::ExportClassPrimitive) {
1792        // Element.createUser()
1793        EB_ADD("Element.createUser(" << RenderScriptVar
1794                                     << ", Element.DataType."
1795                                     << DataTypeName << ")");
1796      } else {
1797        slangAssert((ET->getClass() == RSExportType::ExportClassVector) &&
1798                    "Unexpected type.");
1799        EB_ADD("Element.createVector(" << RenderScriptVar
1800                                       << ", Element.DataType."
1801                                       << DataTypeName << ", "
1802                                       << Size << ")");
1803      }
1804#ifndef NDEBUG
1805    } else if (ET->getClass() == RSExportType::ExportClassPointer) {
1806      // Pointer type variable should be resolved in
1807      // GetBuiltinElementConstruct()
1808      slangAssert(false && "??");
1809    } else if (ET->getClass() == RSExportType::ExportClassMatrix) {
1810      // Matrix type variable should be resolved
1811      // in GetBuiltinElementConstruct()
1812      slangAssert(false && "??");
1813#endif
1814    } else if (ET->getClass() == RSExportType::ExportClassConstantArray) {
1815      const RSExportConstantArrayType *ECAT =
1816          static_cast<const RSExportConstantArrayType *>(ET);
1817
1818      const RSExportType *ElementType = ECAT->getElementType();
1819      if (ElementType->getClass() != RSExportType::ExportClassRecord) {
1820        genAddElementToElementBuilder(C,
1821                                      ECAT->getElementType(),
1822                                      VarName,
1823                                      ElementBuilderName,
1824                                      RenderScriptVar,
1825                                      ECAT->getSize());
1826      } else {
1827        std::string NewElementBuilderName(ElementBuilderName);
1828        NewElementBuilderName.append(1, '_');
1829
1830        genBuildElement(C,
1831                        NewElementBuilderName.c_str(),
1832                        static_cast<const RSExportRecordType*>(ElementType),
1833                        RenderScriptVar,
1834                        /* IsInline = */true);
1835        ArraySize = ECAT->getSize();
1836        EB_ADD(NewElementBuilderName << ".create()");
1837      }
1838    } else if (ET->getClass() == RSExportType::ExportClassRecord) {
1839      // Simalar to case of RSExportType::ExportClassRecord in genPackVarOfType.
1840      //
1841      // TODO(zonr): Generalize these two function such that there's no
1842      //             duplicated codes.
1843      const RSExportRecordType *ERT =
1844          static_cast<const RSExportRecordType*>(ET);
1845      int Pos = 0;    // relative pos from now on
1846
1847      for (RSExportRecordType::const_field_iterator I = ERT->fields_begin(),
1848               E = ERT->fields_end();
1849           I != E;
1850           I++) {
1851        const RSExportRecordType::Field *F = *I;
1852        std::string FieldName;
1853        int FieldOffset = F->getOffsetInParent();
1854        int FieldStoreSize = RSExportType::GetTypeStoreSize(F->getType());
1855        int FieldAllocSize = RSExportType::GetTypeAllocSize(F->getType());
1856
1857        if (!VarName.empty())
1858          FieldName = VarName + "." + F->getName();
1859        else
1860          FieldName = F->getName();
1861
1862        // Alignment
1863        genAddPaddingToElementBuiler(C,
1864                                     (FieldOffset - Pos),
1865                                     ElementBuilderName,
1866                                     RenderScriptVar);
1867
1868        // eb.add(...)
1869        C.addFieldIndexMapping(F);
1870        if (F->getType()->getClass() != RSExportType::ExportClassRecord) {
1871          genAddElementToElementBuilder(C,
1872                                        F->getType(),
1873                                        FieldName,
1874                                        ElementBuilderName,
1875                                        RenderScriptVar,
1876                                        0);
1877        } else {
1878          std::string NewElementBuilderName(ElementBuilderName);
1879          NewElementBuilderName.append(1, '_');
1880
1881          genBuildElement(C,
1882                          NewElementBuilderName.c_str(),
1883                          static_cast<const RSExportRecordType*>(F->getType()),
1884                          RenderScriptVar,
1885                          /* IsInline = */true);
1886
1887          const std::string &VarName = FieldName;  // Hack for EB_ADD macro
1888          EB_ADD(NewElementBuilderName << ".create()");
1889        }
1890
1891        if (mRSContext->getTargetAPI() < SLANG_ICS_TARGET_API) {
1892          // There is padding within the field type. This is only necessary
1893          // for HC-targeted APIs.
1894          genAddPaddingToElementBuiler(C,
1895                                       (FieldAllocSize - FieldStoreSize),
1896                                       ElementBuilderName,
1897                                       RenderScriptVar);
1898        }
1899
1900        Pos = FieldOffset + FieldAllocSize;
1901      }
1902
1903      // There maybe some padding after the struct
1904      size_t RecordAllocSize = RSExportType::GetTypeAllocSize(ERT);
1905
1906      genAddPaddingToElementBuiler(C,
1907                                   RecordAllocSize - Pos,
1908                                   ElementBuilderName,
1909                                   RenderScriptVar);
1910    } else {
1911      slangAssert(false && "Unknown class of type");
1912    }
1913  }
1914}
1915
1916void RSReflection::genAddPaddingToElementBuiler(Context &C,
1917                                                int PaddingSize,
1918                                                const char *ElementBuilderName,
1919                                                const char *RenderScriptVar) {
1920  unsigned ArraySize = 0;   // Hack the EB_ADD macro
1921  while (PaddingSize > 0) {
1922    const std::string &VarName = C.createPaddingField();
1923    if (PaddingSize >= 4) {
1924      EB_ADD("Element.U32(" << RenderScriptVar << ")");
1925      PaddingSize -= 4;
1926    } else if (PaddingSize >= 2) {
1927      EB_ADD("Element.U16(" << RenderScriptVar << ")");
1928      PaddingSize -= 2;
1929    } else if (PaddingSize >= 1) {
1930      EB_ADD("Element.U8(" << RenderScriptVar << ")");
1931      PaddingSize -= 1;
1932    }
1933  }
1934  return;
1935}
1936
1937#undef EB_ADD
1938/******** Methods to create Element in Java of given record type /end ********/
1939
1940bool RSReflection::reflect(const std::string &OutputPathBase,
1941                           const std::string &OutputPackageName,
1942                           const std::string &RSPackageName,
1943                           const std::string &InputFileName,
1944                           const std::string &OutputBCFileName) {
1945  Context *C = NULL;
1946  std::string ResourceId = "";
1947  std::string PaddingPrefix = "";
1948
1949  if (mRSContext->getTargetAPI() < SLANG_ICS_TARGET_API) {
1950    PaddingPrefix = "#padding_";
1951  } else {
1952    PaddingPrefix = "#rs_padding_";
1953  }
1954
1955  if (!GetClassNameFromFileName(OutputBCFileName, ResourceId))
1956    return false;
1957
1958  if (ResourceId.empty())
1959    ResourceId = "<Resource ID>";
1960
1961  if (OutputPackageName.empty() || OutputPackageName == "-")
1962    C = new Context(OutputPathBase, InputFileName, "<Package Name>",
1963                    RSPackageName, ResourceId, PaddingPrefix, true);
1964  else
1965    C = new Context(OutputPathBase, InputFileName, OutputPackageName,
1966                    RSPackageName, ResourceId, PaddingPrefix, false);
1967
1968  if (C != NULL) {
1969    std::string ErrorMsg, ScriptClassName;
1970    // class ScriptC_<ScriptName>
1971    if (!GetClassNameFromFileName(InputFileName, ScriptClassName))
1972      return false;
1973
1974    if (ScriptClassName.empty())
1975      ScriptClassName = "<Input Script Name>";
1976
1977    ScriptClassName.insert(0, RS_SCRIPT_CLASS_NAME_PREFIX);
1978
1979    if (mRSContext->getLicenseNote() != NULL) {
1980      C->setLicenseNote(*(mRSContext->getLicenseNote()));
1981    }
1982
1983    if (!genScriptClass(*C, ScriptClassName, ErrorMsg)) {
1984      std::cerr << "Failed to generate class " << ScriptClassName << " ("
1985                << ErrorMsg << ")" << std::endl;
1986      return false;
1987    }
1988
1989    mGeneratedFileNames->push_back(ScriptClassName);
1990
1991    // class ScriptField_<TypeName>
1992    for (RSContext::const_export_type_iterator TI =
1993             mRSContext->export_types_begin(),
1994             TE = mRSContext->export_types_end();
1995         TI != TE;
1996         TI++) {
1997      const RSExportType *ET = TI->getValue();
1998
1999      if (ET->getClass() == RSExportType::ExportClassRecord) {
2000        const RSExportRecordType *ERT =
2001            static_cast<const RSExportRecordType*>(ET);
2002
2003        if (!ERT->isArtificial() && !genTypeClass(*C, ERT, ErrorMsg)) {
2004          std::cerr << "Failed to generate type class for struct '"
2005                    << ERT->getName() << "' (" << ErrorMsg << ")" << std::endl;
2006          return false;
2007        }
2008      }
2009    }
2010  }
2011
2012  return true;
2013}
2014
2015/************************** RSReflection::Context **************************/
2016const char *const RSReflection::Context::ApacheLicenseNote =
2017    "/*\n"
2018    " * Copyright (C) 2011-2012 The Android Open Source Project\n"
2019    " *\n"
2020    " * Licensed under the Apache License, Version 2.0 (the \"License\");\n"
2021    " * you may not use this file except in compliance with the License.\n"
2022    " * You may obtain a copy of the License at\n"
2023    " *\n"
2024    " *      http://www.apache.org/licenses/LICENSE-2.0\n"
2025    " *\n"
2026    " * Unless required by applicable law or agreed to in writing, software\n"
2027    " * distributed under the License is distributed on an \"AS IS\" BASIS,\n"
2028    " * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or "
2029    "implied.\n"
2030    " * See the License for the specific language governing permissions and\n"
2031    " * limitations under the License.\n"
2032    " */\n"
2033    "\n";
2034
2035bool RSReflection::Context::openClassFile(const std::string &ClassName,
2036                                          std::string &ErrorMsg) {
2037  if (!mUseStdout) {
2038    mOF.clear();
2039    std::string Path =
2040        RSSlangReflectUtils::ComputePackagedPath(mOutputPathBase.c_str(),
2041                                                 mPackageName.c_str());
2042
2043    if (!SlangUtils::CreateDirectoryWithParents(Path, &ErrorMsg))
2044      return false;
2045
2046    std::string ClassFile = Path + OS_PATH_SEPARATOR_STR + ClassName + ".java";
2047
2048    mOF.open(ClassFile.c_str());
2049    if (!mOF.good()) {
2050      ErrorMsg = "failed to open file '" + ClassFile + "' for write";
2051      return false;
2052    }
2053  }
2054  return true;
2055}
2056
2057const char *RSReflection::Context::AccessModifierStr(AccessModifier AM) {
2058  switch (AM) {
2059    case AM_Public: return "public"; break;
2060    case AM_Protected: return "protected"; break;
2061    case AM_Private: return "private"; break;
2062    case AM_PublicSynchronized: return "public synchronized"; break;
2063    default: return ""; break;
2064  }
2065}
2066
2067bool RSReflection::Context::startClass(AccessModifier AM,
2068                                       bool IsStatic,
2069                                       const std::string &ClassName,
2070                                       const char *SuperClassName,
2071                                       std::string &ErrorMsg) {
2072  if (mVerbose)
2073    std::cout << "Generating " << ClassName << ".java ..." << std::endl;
2074
2075  // Open file for class
2076  if (!openClassFile(ClassName, ErrorMsg))
2077    return false;
2078
2079  // License
2080  out() << mLicenseNote;
2081
2082  // Notice of generated file
2083  out() << "/*" << std::endl;
2084  out() << " * This file is auto-generated. DO NOT MODIFY!" << std::endl;
2085  out() << " * The source Renderscript file: " << mInputRSFile << std::endl;
2086  out() << " */" << std::endl;
2087
2088  // Package
2089  if (!mPackageName.empty())
2090    out() << "package " << mPackageName << ";" << std::endl;
2091  out() << std::endl;
2092
2093  // Imports
2094  out() << "import " << mRSPackageName << ".*;" << std::endl;
2095  out() << "import android.content.res.Resources;" << std::endl;
2096  out() << std::endl;
2097
2098  // All reflected classes should be annotated as hidden, so that they won't
2099  // be exposed in SDK.
2100  out() << "/**" << std::endl;
2101  out() << " * @hide" << std::endl;
2102  out() << " */" << std::endl;
2103
2104  out() << AccessModifierStr(AM) << ((IsStatic) ? " static" : "") << " class "
2105        << ClassName;
2106  if (SuperClassName != NULL)
2107    out() << " extends " << SuperClassName;
2108
2109  startBlock();
2110
2111  mClassName = ClassName;
2112
2113  return true;
2114}
2115
2116void RSReflection::Context::endClass() {
2117  endBlock();
2118  if (!mUseStdout)
2119    mOF.close();
2120  clear();
2121  return;
2122}
2123
2124void RSReflection::Context::startBlock(bool ShouldIndent) {
2125  if (ShouldIndent)
2126    indent() << "{" << std::endl;
2127  else
2128    out() << " {" << std::endl;
2129  incIndentLevel();
2130  return;
2131}
2132
2133void RSReflection::Context::endBlock() {
2134  decIndentLevel();
2135  indent() << "}" << std::endl << std::endl;
2136  return;
2137}
2138
2139void RSReflection::Context::startTypeClass(const std::string &ClassName) {
2140  indent() << "public static class " << ClassName;
2141  startBlock();
2142  return;
2143}
2144
2145void RSReflection::Context::endTypeClass() {
2146  endBlock();
2147  return;
2148}
2149
2150void RSReflection::Context::startFunction(AccessModifier AM,
2151                                          bool IsStatic,
2152                                          const char *ReturnType,
2153                                          const std::string &FunctionName,
2154                                          int Argc, ...) {
2155  ArgTy Args;
2156  va_list vl;
2157  va_start(vl, Argc);
2158
2159  for (int i = 0; i < Argc; i++) {
2160    const char *ArgType = va_arg(vl, const char*);
2161    const char *ArgName = va_arg(vl, const char*);
2162
2163    Args.push_back(std::make_pair(ArgType, ArgName));
2164  }
2165  va_end(vl);
2166
2167  startFunction(AM, IsStatic, ReturnType, FunctionName, Args);
2168
2169  return;
2170}
2171
2172void RSReflection::Context::startFunction(AccessModifier AM,
2173                                          bool IsStatic,
2174                                          const char *ReturnType,
2175                                          const std::string &FunctionName,
2176                                          const ArgTy &Args) {
2177  indent() << AccessModifierStr(AM) << ((IsStatic) ? " static " : " ")
2178           << ((ReturnType) ? ReturnType : "") << " " << FunctionName << "(";
2179
2180  bool FirstArg = true;
2181  for (ArgTy::const_iterator I = Args.begin(), E = Args.end();
2182       I != E;
2183       I++) {
2184    if (!FirstArg)
2185      out() << ", ";
2186    else
2187      FirstArg = false;
2188
2189    out() << I->first << " " << I->second;
2190  }
2191
2192  out() << ")";
2193  startBlock();
2194
2195  return;
2196}
2197
2198void RSReflection::Context::endFunction() {
2199  endBlock();
2200  return;
2201}
2202
2203bool RSReflection::Context::addTypeNameForElement(
2204    const std::string &TypeName) {
2205  if (mTypesToCheck.find(TypeName) == mTypesToCheck.end()) {
2206    mTypesToCheck.insert(TypeName);
2207    return true;
2208  } else {
2209    return false;
2210  }
2211}
2212
2213bool RSReflection::Context::addTypeNameForFieldPacker(
2214    const std::string &TypeName) {
2215  if (mFieldPackerTypes.find(TypeName) == mFieldPackerTypes.end()) {
2216    mFieldPackerTypes.insert(TypeName);
2217    return true;
2218  } else {
2219    return false;
2220  }
2221}
2222
2223}  // namespace slang
2224