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