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