slang_rs_export_type.h revision b095e05fef8f0230ab42eaed7a06c3b2d698189a
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#ifndef _FRAMEWORKS_COMPILE_SLANG_SLANG_RS_EXPORT_TYPE_H_  // NOLINT
18#define _FRAMEWORKS_COMPILE_SLANG_SLANG_RS_EXPORT_TYPE_H_
19
20#include <list>
21#include <set>
22#include <string>
23#include <sstream>
24
25#include "clang/AST/Decl.h"
26#include "clang/AST/Type.h"
27
28#include "llvm/ADT/SmallPtrSet.h"
29#include "llvm/ADT/StringMap.h"
30#include "llvm/ADT/StringRef.h"
31
32#include "llvm/Support/ManagedStatic.h"
33
34#include "slang_rs_exportable.h"
35
36
37inline const clang::Type* GetCanonicalType(const clang::Type* T) {
38  if (T == NULL) {
39    return  NULL;
40  }
41  return T->getCanonicalTypeInternal().getTypePtr();
42}
43
44inline const clang::Type* GetCanonicalType(clang::QualType QT) {
45  return GetCanonicalType(QT.getTypePtr());
46}
47
48inline const clang::Type* GetExtVectorElementType(const clang::ExtVectorType *T) {
49  if (T == NULL) {
50    return NULL;
51  }
52  return GetCanonicalType(T->getElementType());
53}
54
55inline const clang::Type* GetPointeeType(const clang::PointerType *T) {
56  if (T == NULL) {
57    return NULL;
58  }
59  return GetCanonicalType(T->getPointeeType());
60}
61
62inline const clang::Type* GetConstantArrayElementType(const clang::ConstantArrayType *T) {
63  if (T == NULL) {
64    return NULL;
65  }
66  return GetCanonicalType(T->getElementType());
67}
68
69
70namespace llvm {
71  class Type;
72}   // namespace llvm
73
74namespace slang {
75
76class RSContext;
77
78// Broad grouping of the data types
79enum DataTypeCategory {
80    PrimitiveDataType,
81    MatrixDataType,
82    ObjectDataType
83};
84
85// From graphics/java/android/renderscript/Element.java: Element.DataType
86/* NOTE: The values of the enums are found compiled in the bit code (i.e. as
87 * values, not symbolic.  When adding new types, you must add them to the end.
88 * If removing types, you can't re-use the integer value.
89 *
90 * TODO: but if you do this, you won't be able to keep using First* & Last*
91 * for validation.
92 *
93 * IMPORTANT: This enum should correspond one-for-one to the entries found in the
94 * gReflectionsTypes table (except for the two negative numbers).  Don't edit one without
95 * the other.
96 */
97enum DataType {
98    DataTypeIsStruct = -2,
99    DataTypeUnknown = -1,
100
101    DataTypeFloat16 = 0,
102    DataTypeFloat32 = 1,
103    DataTypeFloat64 = 2,
104    DataTypeSigned8 = 3,
105    DataTypeSigned16 = 4,
106    DataTypeSigned32 = 5,
107    DataTypeSigned64 = 6,
108    DataTypeUnsigned8 = 7,
109    DataTypeUnsigned16 = 8,
110    DataTypeUnsigned32 = 9,
111    DataTypeUnsigned64 = 10,
112    DataTypeBoolean = 11,
113    DataTypeUnsigned565 = 12,
114    DataTypeUnsigned5551 = 13,
115    DataTypeUnsigned4444 = 14,
116
117    DataTypeRSMatrix2x2 = 15,
118    DataTypeRSMatrix3x3 = 16,
119    DataTypeRSMatrix4x4 = 17,
120
121    DataTypeRSElement = 18,
122    DataTypeRSType = 19,
123    DataTypeRSAllocation = 20,
124    DataTypeRSSampler = 21,
125    DataTypeRSScript = 22,
126    DataTypeRSMesh = 23,
127    DataTypeRSPath = 24,
128    DataTypeRSProgramFragment = 25,
129    DataTypeRSProgramVertex = 26,
130    DataTypeRSProgramRaster = 27,
131    DataTypeRSProgramStore = 28,
132    DataTypeRSFont = 29,
133
134    // This should always be last and correspond to the size of the gReflectionTypes table.
135    DataTypeMax
136};
137
138typedef struct {
139    DataTypeCategory category;
140    const char * rs_type;
141    const char * rs_short_type;
142    uint32_t size_in_bits;
143    const char * c_name;
144    const char * java_name;
145    const char * rs_c_vector_prefix;
146    const char * rs_java_vector_prefix;
147    bool java_promotion;
148} RSReflectionType;
149
150
151typedef struct RSReflectionTypeData_rec {
152    const RSReflectionType *type;
153    uint32_t vecSize;
154    bool isPointer;
155    uint32_t arraySize;
156
157    // Subelements
158    //std::vector<const struct RSReflectionTypeData_rec *> fields;
159    //std::vector< std::string > fieldNames;
160    //std::vector< uint32_t> fieldOffsetBytes;
161} RSReflectionTypeData;
162
163// Make a name for types that are too complicated to create the real names.
164std::string CreateDummyName(const char *type, const std::string &name);
165
166inline bool IsDummyName(const llvm::StringRef &Name) {
167  return Name.startswith("<");
168}
169
170class RSExportType : public RSExportable {
171  friend class RSExportElement;
172 public:
173  typedef enum {
174    ExportClassPrimitive,
175    ExportClassPointer,
176    ExportClassVector,
177    ExportClassMatrix,
178    ExportClassConstantArray,
179    ExportClassRecord
180  } ExportClass;
181
182  void convertToRTD(RSReflectionTypeData *rtd) const;
183
184 private:
185  ExportClass mClass;
186  std::string mName;
187
188  // Cache the result after calling convertToLLVMType() at the first time
189  mutable llvm::Type *mLLVMType;
190
191 protected:
192  RSExportType(RSContext *Context,
193               ExportClass Class,
194               const llvm::StringRef &Name);
195
196  // Let's make it private since there're some prerequisites to call this
197  // function.
198  //
199  // @T was normalized by calling RSExportType::NormalizeType().
200  // @TypeName was retrieve from RSExportType::GetTypeName() before calling
201  //           this.
202  //
203  static RSExportType *Create(RSContext *Context,
204                              const clang::Type *T,
205                              const llvm::StringRef &TypeName);
206
207  static llvm::StringRef GetTypeName(const clang::Type *T);
208
209  // This function convert the RSExportType to LLVM type. Actually, it should be
210  // "convert Clang type to LLVM type." However, clang doesn't make this API
211  // (lib/CodeGen/CodeGenTypes.h) public, we need to do by ourselves.
212  //
213  // Once we can get LLVM type, we can use LLVM to get alignment information,
214  // allocation size of a given type and structure layout that LLVM used
215  // (all of these information are target dependent) without dealing with these
216  // by ourselves.
217  virtual llvm::Type *convertToLLVMType() const = 0;
218  // Record type may recursively reference its type definition. We need a
219  // temporary type setup before the type construction gets done.
220  inline void setAbstractLLVMType(llvm::Type *LLVMType) const {
221    mLLVMType = LLVMType;
222  }
223
224  virtual ~RSExportType();
225
226 public:
227  // This function additionally verifies that the Type T is exportable.
228  // If it is not, this function returns false. Otherwise it returns true.
229  static bool NormalizeType(const clang::Type *&T,
230                            llvm::StringRef &TypeName,
231                            RSContext *Context,
232                            const clang::VarDecl *VD);
233
234  // This function checks whether the specified type can be handled by RS/FS.
235  // If it cannot, this function returns false. Otherwise it returns true.
236  // Filterscript has additional restrictions on supported types.
237  static bool ValidateType(slang::RSContext *Context, clang::ASTContext &C,
238                           clang::QualType QT, clang::NamedDecl *ND,
239                           clang::SourceLocation Loc, unsigned int TargetAPI,
240                           bool IsFilterscript);
241
242  // This function ensures that the VarDecl can be properly handled by RS.
243  // If it cannot, this function returns false. Otherwise it returns true.
244  // Filterscript has additional restrictions on supported types.
245  static bool ValidateVarDecl(slang::RSContext *Context, clang::VarDecl *VD,
246                              unsigned int TargetAPI, bool IsFilterscript);
247
248  // @T may not be normalized
249  static RSExportType *Create(RSContext *Context, const clang::Type *T);
250  static RSExportType *CreateFromDecl(RSContext *Context,
251                                      const clang::VarDecl *VD);
252
253  static const clang::Type *GetTypeOfDecl(const clang::DeclaratorDecl *DD);
254
255  inline ExportClass getClass() const { return mClass; }
256
257  virtual unsigned getSize() const { return 1; }
258
259  inline llvm::Type *getLLVMType() const {
260    if (mLLVMType == NULL)
261      mLLVMType = convertToLLVMType();
262    return mLLVMType;
263  }
264
265  // Return the maximum number of bytes that may be written when this type is stored.
266  virtual size_t getStoreSize() const;
267
268  // Return the distance in bytes between successive elements of this type; it includes padding.
269  virtual size_t getAllocSize() const;
270
271  inline const std::string &getName() const { return mName; }
272
273  virtual std::string getElementName() const {
274    // Base case is actually an invalid C/Java identifier.
275    return "@@INVALID@@";
276  }
277
278  virtual bool keep();
279  virtual bool equals(const RSExportable *E) const;
280};  // RSExportType
281
282// Primitive types
283class RSExportPrimitiveType : public RSExportType {
284  friend class RSExportType;
285  friend class RSExportElement;
286 private:
287  DataType mType;
288  bool mNormalized;
289
290  typedef llvm::StringMap<DataType> RSSpecificTypeMapTy;
291  static llvm::ManagedStatic<RSSpecificTypeMapTy> RSSpecificTypeMap;
292
293  static llvm::Type *RSObjectLLVMType;
294
295  static const size_t SizeOfDataTypeInBits[];
296  // @T was normalized by calling RSExportType::NormalizeType() before calling
297  // this.
298  // @TypeName was retrieved from RSExportType::GetTypeName() before calling
299  // this
300  static RSExportPrimitiveType *Create(RSContext *Context,
301                                       const clang::Type *T,
302                                       const llvm::StringRef &TypeName,
303                                       bool Normalized = false);
304
305 protected:
306  RSExportPrimitiveType(RSContext *Context,
307                        // for derived class to set their type class
308                        ExportClass Class,
309                        const llvm::StringRef &Name,
310                        DataType DT,
311                        bool Normalized)
312      : RSExportType(Context, Class, Name),
313        mType(DT),
314        mNormalized(Normalized) {
315    return;
316  }
317
318  virtual llvm::Type *convertToLLVMType() const;
319
320  static DataType GetDataType(RSContext *Context, const clang::Type *T);
321
322 public:
323  // T is normalized by calling RSExportType::NormalizeType() before
324  // calling this
325  static bool IsPrimitiveType(const clang::Type *T);
326
327  // @T may not be normalized
328  static RSExportPrimitiveType *Create(RSContext *Context,
329                                       const clang::Type *T);
330
331  static DataType GetRSSpecificType(const llvm::StringRef &TypeName);
332  static DataType GetRSSpecificType(const clang::Type *T);
333
334  static bool IsRSMatrixType(DataType DT);
335  static bool IsRSObjectType(DataType DT);
336  static bool IsRSObjectType(const clang::Type *T) {
337    return IsRSObjectType(GetRSSpecificType(T));
338  }
339
340  // Determines whether T is [an array of] struct that contains at least one
341  // RS object type within it.
342  static bool IsStructureTypeWithRSObject(const clang::Type *T);
343
344  static size_t GetSizeInBits(const RSExportPrimitiveType *EPT);
345
346  inline DataType getType() const { return mType; }
347  inline bool isRSObjectType() const {
348      return IsRSObjectType(mType);
349  }
350
351  virtual bool equals(const RSExportable *E) const;
352
353  static RSReflectionType *getRSReflectionType(DataType DT);
354  static RSReflectionType *getRSReflectionType(
355      const RSExportPrimitiveType *EPT) {
356    return getRSReflectionType(EPT->getType());
357  }
358
359  virtual unsigned getSize() const { return (GetSizeInBits(this) >> 3); }
360
361  std::string getElementName() const {
362    return getRSReflectionType(this)->rs_short_type;
363  }
364};  // RSExportPrimitiveType
365
366
367class RSExportPointerType : public RSExportType {
368  friend class RSExportType;
369  friend class RSExportFunc;
370 private:
371  const RSExportType *mPointeeType;
372
373  RSExportPointerType(RSContext *Context,
374                      const llvm::StringRef &Name,
375                      const RSExportType *PointeeType)
376      : RSExportType(Context, ExportClassPointer, Name),
377        mPointeeType(PointeeType) {
378    return;
379  }
380
381  // @PT was normalized by calling RSExportType::NormalizeType() before calling
382  // this.
383  static RSExportPointerType *Create(RSContext *Context,
384                                     const clang::PointerType *PT,
385                                     const llvm::StringRef &TypeName);
386
387  virtual llvm::Type *convertToLLVMType() const;
388
389 public:
390  virtual bool keep();
391
392  inline const RSExportType *getPointeeType() const { return mPointeeType; }
393
394  virtual bool equals(const RSExportable *E) const;
395};  // RSExportPointerType
396
397
398class RSExportVectorType : public RSExportPrimitiveType {
399  friend class RSExportType;
400  friend class RSExportElement;
401 private:
402  unsigned mNumElement;   // number of element
403
404  RSExportVectorType(RSContext *Context,
405                     const llvm::StringRef &Name,
406                     DataType DT,
407                     bool Normalized,
408                     unsigned NumElement)
409      : RSExportPrimitiveType(Context, ExportClassVector, Name,
410                              DT, Normalized),
411        mNumElement(NumElement) {
412    return;
413  }
414
415  // @EVT was normalized by calling RSExportType::NormalizeType() before
416  // calling this.
417  static RSExportVectorType *Create(RSContext *Context,
418                                    const clang::ExtVectorType *EVT,
419                                    const llvm::StringRef &TypeName,
420                                    bool Normalized = false);
421
422  virtual llvm::Type *convertToLLVMType() const;
423
424 public:
425  static llvm::StringRef GetTypeName(const clang::ExtVectorType *EVT);
426
427  inline unsigned getNumElement() const { return mNumElement; }
428
429  std::string getElementName() const {
430    std::stringstream Name;
431    Name << RSExportPrimitiveType::getRSReflectionType(this)->rs_short_type
432         << "_" << getNumElement();
433    return Name.str();
434  }
435
436  virtual bool equals(const RSExportable *E) const;
437};
438
439// Only *square* *float* matrix is supported by now.
440//
441// struct rs_matrix{2x2,3x3,4x4, ..., NxN} should be defined as the following
442// form *exactly*:
443//  typedef struct {
444//    float m[{NxN}];
445//  } rs_matrixNxN;
446//
447//  where mDim will be N.
448class RSExportMatrixType : public RSExportType {
449  friend class RSExportType;
450 private:
451  unsigned mDim;  // dimension
452
453  RSExportMatrixType(RSContext *Context,
454                     const llvm::StringRef &Name,
455                     unsigned Dim)
456    : RSExportType(Context, ExportClassMatrix, Name),
457      mDim(Dim) {
458    return;
459  }
460
461  virtual llvm::Type *convertToLLVMType() const;
462
463 public:
464  // @RT was normalized by calling RSExportType::NormalizeType() before
465  // calling this.
466  static RSExportMatrixType *Create(RSContext *Context,
467                                    const clang::RecordType *RT,
468                                    const llvm::StringRef &TypeName,
469                                    unsigned Dim);
470
471  inline unsigned getDim() const { return mDim; }
472
473  virtual bool equals(const RSExportable *E) const;
474};
475
476class RSExportConstantArrayType : public RSExportType {
477  friend class RSExportType;
478 private:
479  const RSExportType *mElementType;  // Array element type
480  unsigned mSize;  // Array size
481
482  RSExportConstantArrayType(RSContext *Context,
483                            const RSExportType *ElementType,
484                            unsigned Size)
485    : RSExportType(Context,
486                   ExportClassConstantArray,
487                   CreateDummyName("ConstantArray", std::string())),
488      mElementType(ElementType),
489      mSize(Size) {
490    return;
491  }
492
493  // @CAT was normalized by calling RSExportType::NormalizeType() before
494  // calling this.
495  static RSExportConstantArrayType *Create(RSContext *Context,
496                                           const clang::ConstantArrayType *CAT);
497
498  virtual llvm::Type *convertToLLVMType() const;
499
500 public:
501  virtual unsigned getSize() const { return mSize; }
502  inline const RSExportType *getElementType() const { return mElementType; }
503
504  std::string getElementName() const {
505    return mElementType->getElementName();
506  }
507
508  virtual bool keep();
509  virtual bool equals(const RSExportable *E) const;
510};
511
512class RSExportRecordType : public RSExportType {
513  friend class RSExportType;
514 public:
515  class Field {
516   private:
517    const RSExportType *mType;
518    // Field name
519    std::string mName;
520    // Link to the struct that contain this field
521    const RSExportRecordType *mParent;
522    // Offset in the container
523    size_t mOffset;
524
525   public:
526    Field(const RSExportType *T,
527          const llvm::StringRef &Name,
528          const RSExportRecordType *Parent,
529          size_t Offset)
530        : mType(T),
531          mName(Name.data(), Name.size()),
532          mParent(Parent),
533          mOffset(Offset) {
534      return;
535    }
536
537    inline const RSExportRecordType *getParent() const { return mParent; }
538    inline const RSExportType *getType() const { return mType; }
539    inline const std::string &getName() const { return mName; }
540    inline size_t getOffsetInParent() const { return mOffset; }
541  };
542
543  typedef std::list<const Field*>::const_iterator const_field_iterator;
544
545  inline const_field_iterator fields_begin() const {
546    return this->mFields.begin();
547  }
548  inline const_field_iterator fields_end() const {
549    return this->mFields.end();
550  }
551
552 private:
553  std::list<const Field*> mFields;
554  bool mIsPacked;
555  // Artificial export struct type is not exported by user (and thus it won't
556  // get reflected)
557  bool mIsArtificial;
558  size_t mStoreSize;
559  size_t mAllocSize;
560
561  RSExportRecordType(RSContext *Context,
562                     const llvm::StringRef &Name,
563                     bool IsPacked,
564                     bool IsArtificial,
565                     size_t StoreSize,
566                     size_t AllocSize)
567      : RSExportType(Context, ExportClassRecord, Name),
568        mIsPacked(IsPacked),
569        mIsArtificial(IsArtificial),
570        mStoreSize(StoreSize),
571        mAllocSize(AllocSize) {
572    return;
573  }
574
575  // @RT was normalized by calling RSExportType::NormalizeType() before calling
576  // this.
577  // @TypeName was retrieved from RSExportType::GetTypeName() before calling
578  // this.
579  static RSExportRecordType *Create(RSContext *Context,
580                                    const clang::RecordType *RT,
581                                    const llvm::StringRef &TypeName,
582                                    bool mIsArtificial = false);
583
584  virtual llvm::Type *convertToLLVMType() const;
585
586 public:
587  inline const std::list<const Field*>& getFields() const { return mFields; }
588  inline bool isPacked() const { return mIsPacked; }
589  inline bool isArtificial() const { return mIsArtificial; }
590  virtual size_t getStoreSize() const { return mStoreSize; }
591  virtual size_t getAllocSize() const { return mAllocSize; }
592
593  virtual std::string getElementName() const {
594    return "ScriptField_" + getName();
595  }
596
597  virtual bool keep();
598  virtual bool equals(const RSExportable *E) const;
599
600  ~RSExportRecordType() {
601    for (std::list<const Field*>::iterator I = mFields.begin(),
602             E = mFields.end();
603         I != E;
604         I++)
605      if (*I != NULL)
606        delete *I;
607    return;
608  }
609};  // RSExportRecordType
610
611}   // namespace slang
612
613#endif  // _FRAMEWORKS_COMPILE_SLANG_SLANG_RS_EXPORT_TYPE_H_  NOLINT
614