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