slang_rs_export_type.cpp revision 37dbf5c324322fe2458e63e3fa869fbf903ec6fd
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_export_type.h"
18
19#include <list>
20#include <vector>
21
22#include "clang/AST/ASTContext.h"
23#include "clang/AST/Attr.h"
24#include "clang/AST/RecordLayout.h"
25
26#include "llvm/ADT/StringExtras.h"
27#include "llvm/IR/DataLayout.h"
28#include "llvm/IR/DerivedTypes.h"
29#include "llvm/IR/Type.h"
30
31#include "slang_assert.h"
32#include "slang_rs_context.h"
33#include "slang_rs_export_element.h"
34#include "slang_version.h"
35
36#define CHECK_PARENT_EQUALITY(ParentClass, E) \
37  if (!ParentClass::matchODR(E, true))        \
38    return false;
39
40namespace slang {
41
42namespace {
43
44// For the data types we support:
45//  Category      - data type category
46//  SName         - "common name" in script (C99)
47//  RsType        - element name in RenderScript
48//  RsShortType   - short element name in RenderScript
49//  SizeInBits    - size in bits
50//  CName         - reflected C name
51//  JavaName      - reflected Java name
52//  JavaArrayElementName - reflected name in Java arrays
53//  CVecName      - prefix for C vector types
54//  JavaVecName   - prefix for Java vector type
55//  JavaPromotion - unsigned type undergoing Java promotion
56//
57// IMPORTANT: The data types in this table should be at the same index as
58// specified by the corresponding DataType enum.
59//
60// TODO: Pull this information out into a separate file.
61static RSReflectionType gReflectionTypes[] = {
62#define _ nullptr
63  //      Category     SName              RsType       RsST           CName         JN      JAEN       CVN       JVN     JP
64{PrimitiveDataType,   "half",         "FLOAT_16",     "F16", 16,     "half",   "short",  "short",   "Half",  "Short", false},
65{PrimitiveDataType,  "float",         "FLOAT_32",     "F32", 32,    "float",   "float",  "float",  "Float",  "Float", false},
66{PrimitiveDataType, "double",         "FLOAT_64",     "F64", 64,   "double",  "double", "double", "Double", "Double", false},
67{PrimitiveDataType,   "char",         "SIGNED_8",      "I8",  8,   "int8_t",    "byte",   "byte",   "Byte",   "Byte", false},
68{PrimitiveDataType,  "short",        "SIGNED_16",     "I16", 16,  "int16_t",   "short",  "short",  "Short",  "Short", false},
69{PrimitiveDataType,    "int",        "SIGNED_32",     "I32", 32,  "int32_t",     "int",    "int",    "Int",    "Int", false},
70{PrimitiveDataType,   "long",        "SIGNED_64",     "I64", 64,  "int64_t",    "long",   "long",   "Long",   "Long", false},
71{PrimitiveDataType,  "uchar",       "UNSIGNED_8",      "U8",  8,  "uint8_t",   "short",   "byte",  "UByte",  "Short",  true},
72{PrimitiveDataType, "ushort",      "UNSIGNED_16",     "U16", 16, "uint16_t",     "int",  "short", "UShort",    "Int",  true},
73{PrimitiveDataType,   "uint",      "UNSIGNED_32",     "U32", 32, "uint32_t",    "long",    "int",   "UInt",   "Long",  true},
74{PrimitiveDataType,  "ulong",      "UNSIGNED_64",     "U64", 64, "uint64_t",    "long",   "long",  "ULong",   "Long", false},
75{PrimitiveDataType,   "bool",          "BOOLEAN", "BOOLEAN",  8,     "bool", "boolean",   "byte",        _,        _, false},
76{PrimitiveDataType,        _,   "UNSIGNED_5_6_5",         _, 16,          _,         _,        _,        _,        _, false},
77{PrimitiveDataType,        _, "UNSIGNED_5_5_5_1",         _, 16,          _,         _,        _,        _,        _, false},
78{PrimitiveDataType,        _, "UNSIGNED_4_4_4_4",         _, 16,          _,         _,        _,        _,        _, false},
79
80{MatrixDataType, "rs_matrix2x2", "MATRIX_2X2", _,  4*32, "rs_matrix2x2", "Matrix2f", _, _, _, false},
81{MatrixDataType, "rs_matrix3x3", "MATRIX_3X3", _,  9*32, "rs_matrix3x3", "Matrix3f", _, _, _, false},
82{MatrixDataType, "rs_matrix4x4", "MATRIX_4X4", _, 16*32, "rs_matrix4x4", "Matrix4f", _, _, _, false},
83
84// RS object types are 32 bits in 32-bit RS, but 256 bits in 64-bit RS.
85// This is handled specially by the GetElementSizeInBits() method.
86{ObjectDataType, _,          "RS_ELEMENT",          "ELEMENT", 32,         "Element",         "Element", _, _, _, false},
87{ObjectDataType, _,             "RS_TYPE",             "TYPE", 32,            "Type",            "Type", _, _, _, false},
88{ObjectDataType, _,       "RS_ALLOCATION",       "ALLOCATION", 32,      "Allocation",      "Allocation", _, _, _, false},
89{ObjectDataType, _,          "RS_SAMPLER",          "SAMPLER", 32,         "Sampler",         "Sampler", _, _, _, false},
90{ObjectDataType, _,           "RS_SCRIPT",           "SCRIPT", 32,          "Script",          "Script", _, _, _, false},
91{ObjectDataType, _,             "RS_MESH",             "MESH", 32,            "Mesh",            "Mesh", _, _, _, false},
92{ObjectDataType, _,             "RS_PATH",             "PATH", 32,            "Path",            "Path", _, _, _, false},
93{ObjectDataType, _, "RS_PROGRAM_FRAGMENT", "PROGRAM_FRAGMENT", 32, "ProgramFragment", "ProgramFragment", _, _, _, false},
94{ObjectDataType, _,   "RS_PROGRAM_VERTEX",   "PROGRAM_VERTEX", 32,   "ProgramVertex",   "ProgramVertex", _, _, _, false},
95{ObjectDataType, _,   "RS_PROGRAM_RASTER",   "PROGRAM_RASTER", 32,   "ProgramRaster",   "ProgramRaster", _, _, _, false},
96{ObjectDataType, _,    "RS_PROGRAM_STORE",    "PROGRAM_STORE", 32,    "ProgramStore",    "ProgramStore", _, _, _, false},
97{ObjectDataType, _,             "RS_FONT",             "FONT", 32,            "Font",            "Font", _, _, _, false},
98#undef _
99};
100
101const int kMaxVectorSize = 4;
102
103struct BuiltinInfo {
104  clang::BuiltinType::Kind builtinTypeKind;
105  DataType type;
106  /* TODO If we return std::string instead of llvm::StringRef, we could build
107   * the name instead of duplicating the entries.
108   */
109  const char *cname[kMaxVectorSize];
110};
111
112
113BuiltinInfo BuiltinInfoTable[] = {
114    {clang::BuiltinType::Bool, DataTypeBoolean,
115     {"bool", "bool2", "bool3", "bool4"}},
116    {clang::BuiltinType::Char_U, DataTypeUnsigned8,
117     {"uchar", "uchar2", "uchar3", "uchar4"}},
118    {clang::BuiltinType::UChar, DataTypeUnsigned8,
119     {"uchar", "uchar2", "uchar3", "uchar4"}},
120    {clang::BuiltinType::Char16, DataTypeSigned16,
121     {"short", "short2", "short3", "short4"}},
122    {clang::BuiltinType::Char32, DataTypeSigned32,
123     {"int", "int2", "int3", "int4"}},
124    {clang::BuiltinType::UShort, DataTypeUnsigned16,
125     {"ushort", "ushort2", "ushort3", "ushort4"}},
126    {clang::BuiltinType::UInt, DataTypeUnsigned32,
127     {"uint", "uint2", "uint3", "uint4"}},
128    {clang::BuiltinType::ULong, DataTypeUnsigned64,
129     {"ulong", "ulong2", "ulong3", "ulong4"}},
130    {clang::BuiltinType::ULongLong, DataTypeUnsigned64,
131     {"ulong", "ulong2", "ulong3", "ulong4"}},
132
133    {clang::BuiltinType::Char_S, DataTypeSigned8,
134     {"char", "char2", "char3", "char4"}},
135    {clang::BuiltinType::SChar, DataTypeSigned8,
136     {"char", "char2", "char3", "char4"}},
137    {clang::BuiltinType::Short, DataTypeSigned16,
138     {"short", "short2", "short3", "short4"}},
139    {clang::BuiltinType::Int, DataTypeSigned32,
140     {"int", "int2", "int3", "int4"}},
141    {clang::BuiltinType::Long, DataTypeSigned64,
142     {"long", "long2", "long3", "long4"}},
143    {clang::BuiltinType::LongLong, DataTypeSigned64,
144     {"long", "long2", "long3", "long4"}},
145    {clang::BuiltinType::Half, DataTypeFloat16,
146     {"half", "half2", "half3", "half4"}},
147    {clang::BuiltinType::Float, DataTypeFloat32,
148     {"float", "float2", "float3", "float4"}},
149    {clang::BuiltinType::Double, DataTypeFloat64,
150     {"double", "double2", "double3", "double4"}},
151};
152const int BuiltinInfoTableCount = sizeof(BuiltinInfoTable) / sizeof(BuiltinInfoTable[0]);
153
154struct NameAndPrimitiveType {
155  const char *name;
156  DataType dataType;
157};
158
159static NameAndPrimitiveType MatrixAndObjectDataTypes[] = {
160    {"rs_matrix2x2", DataTypeRSMatrix2x2},
161    {"rs_matrix3x3", DataTypeRSMatrix3x3},
162    {"rs_matrix4x4", DataTypeRSMatrix4x4},
163    {"rs_element", DataTypeRSElement},
164    {"rs_type", DataTypeRSType},
165    {"rs_allocation", DataTypeRSAllocation},
166    {"rs_sampler", DataTypeRSSampler},
167    {"rs_script", DataTypeRSScript},
168    {"rs_mesh", DataTypeRSMesh},
169    {"rs_path", DataTypeRSPath},
170    {"rs_program_fragment", DataTypeRSProgramFragment},
171    {"rs_program_vertex", DataTypeRSProgramVertex},
172    {"rs_program_raster", DataTypeRSProgramRaster},
173    {"rs_program_store", DataTypeRSProgramStore},
174    {"rs_font", DataTypeRSFont},
175};
176
177const int MatrixAndObjectDataTypesCount =
178    sizeof(MatrixAndObjectDataTypes) / sizeof(MatrixAndObjectDataTypes[0]);
179
180static const clang::Type *TypeExportableHelper(
181    const clang::Type *T,
182    llvm::SmallPtrSet<const clang::Type*, 8>& SPS,
183    slang::RSContext *Context,
184    const clang::VarDecl *VD,
185    const clang::RecordDecl *TopLevelRecord,
186    ExportKind EK);
187
188template <unsigned N>
189static void ReportTypeError(slang::RSContext *Context,
190                            const clang::NamedDecl *ND,
191                            const clang::RecordDecl *TopLevelRecord,
192                            const char (&Message)[N],
193                            unsigned int TargetAPI = 0) {
194  // Attempt to use the type declaration first (if we have one).
195  // Fall back to the variable definition, if we are looking at something
196  // like an array declaration that can't be exported.
197  if (TopLevelRecord) {
198    Context->ReportError(TopLevelRecord->getLocation(), Message)
199        << TopLevelRecord->getName() << TargetAPI;
200  } else if (ND) {
201    Context->ReportError(ND->getLocation(), Message) << ND->getName()
202                                                     << TargetAPI;
203  } else {
204    slangAssert(false && "Variables should be validated before exporting");
205  }
206}
207
208static const clang::Type *ConstantArrayTypeExportableHelper(
209    const clang::ConstantArrayType *CAT,
210    llvm::SmallPtrSet<const clang::Type*, 8>& SPS,
211    slang::RSContext *Context,
212    const clang::VarDecl *VD,
213    const clang::RecordDecl *TopLevelRecord,
214    ExportKind EK) {
215  // Check element type
216  const clang::Type *ElementType = GetConstantArrayElementType(CAT);
217  if (ElementType->isArrayType()) {
218    ReportTypeError(Context, VD, TopLevelRecord,
219                    "multidimensional arrays cannot be exported: '%0'");
220    return nullptr;
221  } else if (ElementType->isExtVectorType()) {
222    const clang::ExtVectorType *EVT =
223        static_cast<const clang::ExtVectorType*>(ElementType);
224    unsigned numElements = EVT->getNumElements();
225
226    const clang::Type *BaseElementType = GetExtVectorElementType(EVT);
227    if (!RSExportPrimitiveType::IsPrimitiveType(BaseElementType)) {
228      ReportTypeError(Context, VD, TopLevelRecord,
229        "vectors of non-primitive types cannot be exported: '%0'");
230      return nullptr;
231    }
232
233    if (numElements == 3 && CAT->getSize() != 1) {
234      ReportTypeError(Context, VD, TopLevelRecord,
235        "arrays of width 3 vector types cannot be exported: '%0'");
236      return nullptr;
237    }
238  }
239
240  if (TypeExportableHelper(ElementType, SPS, Context, VD,
241                           TopLevelRecord, EK) == nullptr) {
242    return nullptr;
243  } else {
244    return CAT;
245  }
246}
247
248BuiltinInfo *FindBuiltinType(clang::BuiltinType::Kind builtinTypeKind) {
249  for (int i = 0; i < BuiltinInfoTableCount; i++) {
250    if (builtinTypeKind == BuiltinInfoTable[i].builtinTypeKind) {
251      return &BuiltinInfoTable[i];
252    }
253  }
254  return nullptr;
255}
256
257static const clang::Type *TypeExportableHelper(
258    clang::Type const *T,
259    llvm::SmallPtrSet<clang::Type const *, 8> &SPS,
260    slang::RSContext *Context,
261    clang::VarDecl const *VD,
262    clang::RecordDecl const *TopLevelRecord,
263    ExportKind EK) {
264  // Normalize first
265  if ((T = GetCanonicalType(T)) == nullptr)
266    return nullptr;
267
268  if (SPS.count(T))
269    return T;
270
271  const clang::Type *CTI = T->getCanonicalTypeInternal().getTypePtr();
272
273  switch (T->getTypeClass()) {
274    case clang::Type::Builtin: {
275      const clang::BuiltinType *BT = static_cast<const clang::BuiltinType*>(CTI);
276      return FindBuiltinType(BT->getKind()) == nullptr ? nullptr : T;
277    }
278    case clang::Type::Record: {
279      if (RSExportPrimitiveType::GetRSSpecificType(T) != DataTypeUnknown) {
280        return T;  // RS object type, no further checks are needed
281      }
282
283      // Check internal struct
284      if (T->isUnionType()) {
285        ReportTypeError(Context, VD, T->getAsUnionType()->getDecl(),
286                        "unions cannot be exported: '%0'");
287        return nullptr;
288      } else if (!T->isStructureType()) {
289        slangAssert(false && "Unknown type cannot be exported");
290        return nullptr;
291      }
292
293      clang::RecordDecl *RD = T->getAsStructureType()->getDecl();
294      if (RD != nullptr) {
295        RD = RD->getDefinition();
296        if (RD == nullptr) {
297          ReportTypeError(Context, nullptr, T->getAsStructureType()->getDecl(),
298                          "struct is not defined in this module");
299          return nullptr;
300        }
301      }
302
303      if (!TopLevelRecord) {
304        TopLevelRecord = RD;
305      }
306      if (RD->getName().empty()) {
307        ReportTypeError(Context, nullptr, RD,
308                        "anonymous structures cannot be exported");
309        return nullptr;
310      }
311
312      // Fast check
313      if (RD->hasFlexibleArrayMember() || RD->hasObjectMember())
314        return nullptr;
315
316      // Insert myself into checking set
317      SPS.insert(T);
318
319      // Check all element
320      for (clang::RecordDecl::field_iterator FI = RD->field_begin(),
321               FE = RD->field_end();
322           FI != FE;
323           FI++) {
324        const clang::FieldDecl *FD = *FI;
325        const clang::Type *FT = RSExportType::GetTypeOfDecl(FD);
326        FT = GetCanonicalType(FT);
327
328        if (!TypeExportableHelper(FT, SPS, Context, VD, TopLevelRecord,
329                                  EK)) {
330          return nullptr;
331        }
332
333        // We don't support bit fields yet
334        //
335        // TODO(zonr/srhines): allow bit fields of size 8, 16, 32
336        if (FD->isBitField()) {
337          Context->ReportError(
338              FD->getLocation(),
339              "bit fields are not able to be exported: '%0.%1'")
340              << RD->getName() << FD->getName();
341          return nullptr;
342        }
343      }
344
345      return T;
346    }
347    case clang::Type::FunctionProto:
348    case clang::Type::FunctionNoProto:
349      ReportTypeError(Context, VD, TopLevelRecord,
350                      "function types cannot be exported: '%0'");
351      return nullptr;
352    case clang::Type::Pointer: {
353      if (TopLevelRecord) {
354        ReportTypeError(Context, VD, TopLevelRecord,
355            "structures containing pointers cannot be used as the type of "
356            "an exported global variable or the parameter to an exported "
357            "function: '%0'");
358        return nullptr;
359      }
360
361      const clang::PointerType *PT = static_cast<const clang::PointerType*>(CTI);
362      const clang::Type *PointeeType = GetPointeeType(PT);
363
364      if (PointeeType->getTypeClass() == clang::Type::Pointer) {
365        ReportTypeError(Context, VD, TopLevelRecord,
366            "multiple levels of pointers cannot be exported: '%0'");
367        return nullptr;
368      }
369
370      // Void pointers are forbidden for export, although we must accept
371      // void pointers that come in as arguments to a legacy kernel.
372      if (PointeeType->isVoidType() && EK != LegacyKernelArgument) {
373        ReportTypeError(Context, VD, TopLevelRecord,
374            "void pointers cannot be exported: '%0'");
375        return nullptr;
376      }
377
378      // We don't support pointer with array-type pointee
379      if (PointeeType->isArrayType()) {
380        ReportTypeError(Context, VD, TopLevelRecord,
381            "pointers to arrays cannot be exported: '%0'");
382        return nullptr;
383      }
384
385      // Check for unsupported pointee type
386      if (TypeExportableHelper(PointeeType, SPS, Context, VD,
387                                TopLevelRecord, EK) == nullptr)
388        return nullptr;
389      else
390        return T;
391    }
392    case clang::Type::ExtVector: {
393      const clang::ExtVectorType *EVT =
394              static_cast<const clang::ExtVectorType*>(CTI);
395      // Only vector with size 2, 3 and 4 are supported.
396      if (EVT->getNumElements() < 2 || EVT->getNumElements() > 4)
397        return nullptr;
398
399      // Check base element type
400      const clang::Type *ElementType = GetExtVectorElementType(EVT);
401
402      if ((ElementType->getTypeClass() != clang::Type::Builtin) ||
403          (TypeExportableHelper(ElementType, SPS, Context, VD,
404                                TopLevelRecord, EK) == nullptr))
405        return nullptr;
406      else
407        return T;
408    }
409    case clang::Type::ConstantArray: {
410      const clang::ConstantArrayType *CAT =
411              static_cast<const clang::ConstantArrayType*>(CTI);
412
413      return ConstantArrayTypeExportableHelper(CAT, SPS, Context, VD,
414                                               TopLevelRecord, EK);
415    }
416    case clang::Type::Enum: {
417      // FIXME: We currently convert enums to integers, rather than reflecting
418      // a more complete (and nicer type-safe Java version).
419      return Context->getASTContext().IntTy.getTypePtr();
420    }
421    default: {
422      slangAssert(false && "Unknown type cannot be validated");
423      return nullptr;
424    }
425  }
426}
427
428// Return the type that can be used to create RSExportType, will always return
429// the canonical type.
430//
431// If the Type T is not exportable, this function returns nullptr. DiagEngine is
432// used to generate proper Clang diagnostic messages when a non-exportable type
433// is detected. TopLevelRecord is used to capture the highest struct (in the
434// case of a nested hierarchy) for detecting other types that cannot be exported
435// (mostly pointers within a struct).
436static const clang::Type *TypeExportable(const clang::Type *T,
437                                         slang::RSContext *Context,
438                                         const clang::VarDecl *VD,
439                                         ExportKind EK) {
440  llvm::SmallPtrSet<const clang::Type*, 8> SPS =
441      llvm::SmallPtrSet<const clang::Type*, 8>();
442
443  return TypeExportableHelper(T, SPS, Context, VD, nullptr, EK);
444}
445
446static bool ValidateRSObjectInVarDecl(slang::RSContext *Context,
447                                      const clang::VarDecl *VD, bool InCompositeType,
448                                      unsigned int TargetAPI) {
449  if (TargetAPI < SLANG_JB_TARGET_API) {
450    // Only if we are already in a composite type (like an array or structure).
451    if (InCompositeType) {
452      // Only if we are actually exported (i.e. non-static).
453      if (VD->hasLinkage() &&
454          (VD->getFormalLinkage() == clang::ExternalLinkage)) {
455        // Only if we are not a pointer to an object.
456        const clang::Type *T = GetCanonicalType(VD->getType().getTypePtr());
457        if (T->getTypeClass() != clang::Type::Pointer) {
458          ReportTypeError(Context, VD, nullptr,
459                          "arrays/structures containing RS object types "
460                          "cannot be exported in target API < %1: '%0'",
461                          SLANG_JB_TARGET_API);
462          return false;
463        }
464      }
465    }
466  }
467
468  return true;
469}
470
471// Helper function for ValidateType(). We do a recursive descent on the
472// type hierarchy to ensure that we can properly export/handle the
473// declaration.
474// \return true if the variable declaration is valid,
475//         false if it is invalid (along with proper diagnostics).
476//
477// C - ASTContext (for diagnostics + builtin types).
478// T - sub-type that we are validating.
479// ND - (optional) top-level named declaration that we are validating.
480// SPS - set of types we have already seen/validated.
481// InCompositeType - true if we are within an outer composite type.
482// UnionDecl - set if we are in a sub-type of a union.
483// TargetAPI - target SDK API level.
484// IsFilterscript - whether or not we are compiling for Filterscript
485// IsExtern - is this type externally visible (i.e. extern global or parameter
486//                                             to an extern function)
487static bool ValidateTypeHelper(
488    slang::RSContext *Context,
489    clang::ASTContext &C,
490    const clang::Type *&T,
491    const clang::NamedDecl *ND,
492    clang::SourceLocation Loc,
493    llvm::SmallPtrSet<const clang::Type*, 8>& SPS,
494    bool InCompositeType,
495    clang::RecordDecl *UnionDecl,
496    unsigned int TargetAPI,
497    bool IsFilterscript,
498    bool IsExtern) {
499  if ((T = GetCanonicalType(T)) == nullptr)
500    return true;
501
502  if (SPS.count(T))
503    return true;
504
505  const clang::Type *CTI = T->getCanonicalTypeInternal().getTypePtr();
506
507  switch (T->getTypeClass()) {
508    case clang::Type::Record: {
509      if (RSExportPrimitiveType::IsRSObjectType(T)) {
510        const clang::VarDecl *VD = (ND ? llvm::dyn_cast<clang::VarDecl>(ND) : nullptr);
511        if (VD && !ValidateRSObjectInVarDecl(Context, VD, InCompositeType,
512                                             TargetAPI)) {
513          return false;
514        }
515      }
516
517      if (RSExportPrimitiveType::GetRSSpecificType(T) != DataTypeUnknown) {
518        if (!UnionDecl) {
519          return true;
520        } else if (RSExportPrimitiveType::IsRSObjectType(T)) {
521          ReportTypeError(Context, nullptr, UnionDecl,
522              "unions containing RS object types are not allowed");
523          return false;
524        }
525      }
526
527      clang::RecordDecl *RD = nullptr;
528
529      // Check internal struct
530      if (T->isUnionType()) {
531        RD = T->getAsUnionType()->getDecl();
532        UnionDecl = RD;
533      } else if (T->isStructureType()) {
534        RD = T->getAsStructureType()->getDecl();
535      } else {
536        slangAssert(false && "Unknown type cannot be exported");
537        return false;
538      }
539
540      if (RD != nullptr) {
541        RD = RD->getDefinition();
542        if (RD == nullptr) {
543          // FIXME
544          return true;
545        }
546      }
547
548      // Fast check
549      if (RD->hasFlexibleArrayMember() || RD->hasObjectMember())
550        return false;
551
552      // Insert myself into checking set
553      SPS.insert(T);
554
555      // Check all elements
556      for (clang::RecordDecl::field_iterator FI = RD->field_begin(),
557               FE = RD->field_end();
558           FI != FE;
559           FI++) {
560        const clang::FieldDecl *FD = *FI;
561        const clang::Type *FT = RSExportType::GetTypeOfDecl(FD);
562        FT = GetCanonicalType(FT);
563
564        if (!ValidateTypeHelper(Context, C, FT, ND, Loc, SPS, true, UnionDecl,
565                                TargetAPI, IsFilterscript, IsExtern)) {
566          return false;
567        }
568      }
569
570      return true;
571    }
572
573    case clang::Type::Builtin: {
574      if (IsFilterscript) {
575        clang::QualType QT = T->getCanonicalTypeInternal();
576        if (QT == C.DoubleTy ||
577            QT == C.LongDoubleTy ||
578            QT == C.LongTy ||
579            QT == C.LongLongTy) {
580          if (ND) {
581            Context->ReportError(
582                Loc,
583                "Builtin types > 32 bits in size are forbidden in "
584                "Filterscript: '%0'")
585                << ND->getName();
586          } else {
587            Context->ReportError(
588                Loc,
589                "Builtin types > 32 bits in size are forbidden in "
590                "Filterscript");
591          }
592          return false;
593        }
594      }
595      break;
596    }
597
598    case clang::Type::Pointer: {
599      if (IsFilterscript) {
600        if (ND) {
601          Context->ReportError(Loc,
602                               "Pointers are forbidden in Filterscript: '%0'")
603              << ND->getName();
604          return false;
605        } else {
606          // TODO(srhines): Find a better way to handle expressions (i.e. no
607          // NamedDecl) involving pointers in FS that should be allowed.
608          // An example would be calls to library functions like
609          // rsMatrixMultiply() that take rs_matrixNxN * types.
610        }
611      }
612
613      // Forbid pointers in structures that are externally visible.
614      if (InCompositeType && IsExtern) {
615        if (ND) {
616          Context->ReportError(Loc,
617              "structures containing pointers cannot be used as the type of "
618              "an exported global variable or the parameter to an exported "
619              "function: '%0'")
620            << ND->getName();
621        } else {
622          Context->ReportError(Loc,
623              "structures containing pointers cannot be used as the type of "
624              "an exported global variable or the parameter to an exported "
625              "function");
626        }
627        return false;
628      }
629
630      const clang::PointerType *PT = static_cast<const clang::PointerType*>(CTI);
631      const clang::Type *PointeeType = GetPointeeType(PT);
632
633      return ValidateTypeHelper(Context, C, PointeeType, ND, Loc, SPS,
634                                InCompositeType, UnionDecl, TargetAPI,
635                                IsFilterscript, IsExtern);
636    }
637
638    case clang::Type::ExtVector: {
639      const clang::ExtVectorType *EVT =
640              static_cast<const clang::ExtVectorType*>(CTI);
641      const clang::Type *ElementType = GetExtVectorElementType(EVT);
642      if (TargetAPI < SLANG_ICS_TARGET_API &&
643          InCompositeType &&
644          EVT->getNumElements() == 3 &&
645          ND &&
646          ND->getFormalLinkage() == clang::ExternalLinkage) {
647        ReportTypeError(Context, ND, nullptr,
648                        "structs containing vectors of dimension 3 cannot "
649                        "be exported at this API level: '%0'");
650        return false;
651      }
652      return ValidateTypeHelper(Context, C, ElementType, ND, Loc, SPS, true,
653                                UnionDecl, TargetAPI, IsFilterscript, IsExtern);
654    }
655
656    case clang::Type::ConstantArray: {
657      const clang::ConstantArrayType *CAT = static_cast<const clang::ConstantArrayType*>(CTI);
658      const clang::Type *ElementType = GetConstantArrayElementType(CAT);
659      return ValidateTypeHelper(Context, C, ElementType, ND, Loc, SPS, true,
660                                UnionDecl, TargetAPI, IsFilterscript, IsExtern);
661    }
662
663    default: {
664      break;
665    }
666  }
667
668  return true;
669}
670
671}  // namespace
672
673std::string CreateDummyName(const char *type, const std::string &name) {
674  std::stringstream S;
675  S << "<" << type;
676  if (!name.empty()) {
677    S << ":" << name;
678  }
679  S << ">";
680  return S.str();
681}
682
683/****************************** RSExportType ******************************/
684bool RSExportType::NormalizeType(const clang::Type *&T,
685                                 llvm::StringRef &TypeName,
686                                 RSContext *Context,
687                                 const clang::VarDecl *VD,
688                                 ExportKind EK) {
689  if ((T = TypeExportable(T, Context, VD, EK)) == nullptr) {
690    return false;
691  }
692  // Get type name
693  TypeName = RSExportType::GetTypeName(T);
694  if (Context && TypeName.empty()) {
695    if (VD) {
696      Context->ReportError(VD->getLocation(),
697                           "anonymous types cannot be exported");
698    } else {
699      Context->ReportError("anonymous types cannot be exported");
700    }
701    return false;
702  }
703
704  return true;
705}
706
707bool RSExportType::ValidateType(slang::RSContext *Context, clang::ASTContext &C,
708                                clang::QualType QT, const clang::NamedDecl *ND,
709                                clang::SourceLocation Loc,
710                                unsigned int TargetAPI, bool IsFilterscript,
711                                bool IsExtern) {
712  const clang::Type *T = QT.getTypePtr();
713  llvm::SmallPtrSet<const clang::Type*, 8> SPS =
714      llvm::SmallPtrSet<const clang::Type*, 8>();
715
716  // If this is an externally visible variable declaration, we check if the
717  // type is able to be exported first.
718  if (auto VD = llvm::dyn_cast_or_null<clang::VarDecl>(ND)) {
719    if (VD->getFormalLinkage() == clang::ExternalLinkage) {
720      if (!TypeExportable(T, Context, VD, NotLegacyKernelArgument)) {
721        return false;
722      }
723    }
724  }
725  return ValidateTypeHelper(Context, C, T, ND, Loc, SPS, false, nullptr, TargetAPI,
726                            IsFilterscript, IsExtern);
727}
728
729bool RSExportType::ValidateVarDecl(slang::RSContext *Context,
730                                   clang::VarDecl *VD, unsigned int TargetAPI,
731                                   bool IsFilterscript) {
732  return ValidateType(Context, VD->getASTContext(), VD->getType(), VD,
733                      VD->getLocation(), TargetAPI, IsFilterscript,
734                      (VD->getFormalLinkage() == clang::ExternalLinkage));
735}
736
737const clang::Type
738*RSExportType::GetTypeOfDecl(const clang::DeclaratorDecl *DD) {
739  if (DD) {
740    clang::QualType T = DD->getType();
741
742    if (T.isNull())
743      return nullptr;
744    else
745      return T.getTypePtr();
746  }
747  return nullptr;
748}
749
750llvm::StringRef RSExportType::GetTypeName(const clang::Type* T) {
751  T = GetCanonicalType(T);
752  if (T == nullptr)
753    return llvm::StringRef();
754
755  const clang::Type *CTI = T->getCanonicalTypeInternal().getTypePtr();
756
757  switch (T->getTypeClass()) {
758    case clang::Type::Builtin: {
759      const clang::BuiltinType *BT = static_cast<const clang::BuiltinType*>(CTI);
760      BuiltinInfo *info = FindBuiltinType(BT->getKind());
761      if (info != nullptr) {
762        return info->cname[0];
763      }
764      slangAssert(false && "Unknown data type of the builtin");
765      break;
766    }
767    case clang::Type::Record: {
768      clang::RecordDecl *RD;
769      if (T->isStructureType()) {
770        RD = T->getAsStructureType()->getDecl();
771      } else {
772        break;
773      }
774
775      llvm::StringRef Name = RD->getName();
776      if (Name.empty()) {
777        if (RD->getTypedefNameForAnonDecl() != nullptr) {
778          Name = RD->getTypedefNameForAnonDecl()->getName();
779        }
780
781        if (Name.empty()) {
782          // Try to find a name from redeclaration (i.e. typedef)
783          for (clang::TagDecl::redecl_iterator RI = RD->redecls_begin(),
784                   RE = RD->redecls_end();
785               RI != RE;
786               RI++) {
787            slangAssert(*RI != nullptr && "cannot be NULL object");
788
789            Name = (*RI)->getName();
790            if (!Name.empty())
791              break;
792          }
793        }
794      }
795      return Name;
796    }
797    case clang::Type::Pointer: {
798      // "*" plus pointee name
799      const clang::PointerType *P = static_cast<const clang::PointerType*>(CTI);
800      const clang::Type *PT = GetPointeeType(P);
801      llvm::StringRef PointeeName;
802      if (NormalizeType(PT, PointeeName, nullptr, nullptr,
803                        NotLegacyKernelArgument)) {
804        char *Name = new char[ 1 /* * */ + PointeeName.size() + 1 ];
805        Name[0] = '*';
806        memcpy(Name + 1, PointeeName.data(), PointeeName.size());
807        Name[PointeeName.size() + 1] = '\0';
808        return Name;
809      }
810      break;
811    }
812    case clang::Type::ExtVector: {
813      const clang::ExtVectorType *EVT =
814              static_cast<const clang::ExtVectorType*>(CTI);
815      return RSExportVectorType::GetTypeName(EVT);
816      break;
817    }
818    case clang::Type::ConstantArray : {
819      // Construct name for a constant array is too complicated.
820      return "<ConstantArray>";
821    }
822    default: {
823      break;
824    }
825  }
826
827  return llvm::StringRef();
828}
829
830
831RSExportType *RSExportType::Create(RSContext *Context,
832                                   const clang::Type *T,
833                                   const llvm::StringRef &TypeName,
834                                   ExportKind EK) {
835  // Lookup the context to see whether the type was processed before.
836  // Newly created RSExportType will insert into context
837  // in RSExportType::RSExportType()
838  RSContext::export_type_iterator ETI = Context->findExportType(TypeName);
839
840  if (ETI != Context->export_types_end())
841    return ETI->second;
842
843  const clang::Type *CTI = T->getCanonicalTypeInternal().getTypePtr();
844
845  RSExportType *ET = nullptr;
846  switch (T->getTypeClass()) {
847    case clang::Type::Record: {
848      DataType dt = RSExportPrimitiveType::GetRSSpecificType(TypeName);
849      switch (dt) {
850        case DataTypeUnknown: {
851          // User-defined types
852          ET = RSExportRecordType::Create(Context,
853                                          T->getAsStructureType(),
854                                          TypeName);
855          break;
856        }
857        case DataTypeRSMatrix2x2: {
858          // 2 x 2 Matrix type
859          ET = RSExportMatrixType::Create(Context,
860                                          T->getAsStructureType(),
861                                          TypeName,
862                                          2);
863          break;
864        }
865        case DataTypeRSMatrix3x3: {
866          // 3 x 3 Matrix type
867          ET = RSExportMatrixType::Create(Context,
868                                          T->getAsStructureType(),
869                                          TypeName,
870                                          3);
871          break;
872        }
873        case DataTypeRSMatrix4x4: {
874          // 4 x 4 Matrix type
875          ET = RSExportMatrixType::Create(Context,
876                                          T->getAsStructureType(),
877                                          TypeName,
878                                          4);
879          break;
880        }
881        default: {
882          // Others are primitive types
883          ET = RSExportPrimitiveType::Create(Context, T, TypeName);
884          break;
885        }
886      }
887      break;
888    }
889    case clang::Type::Builtin: {
890      ET = RSExportPrimitiveType::Create(Context, T, TypeName);
891      break;
892    }
893    case clang::Type::Pointer: {
894      ET = RSExportPointerType::Create(Context,
895                                       static_cast<const clang::PointerType*>(CTI),
896                                       TypeName);
897      // FIXME: free the name (allocated in RSExportType::GetTypeName)
898      delete [] TypeName.data();
899      break;
900    }
901    case clang::Type::ExtVector: {
902      ET = RSExportVectorType::Create(Context,
903                                      static_cast<const clang::ExtVectorType*>(CTI),
904                                      TypeName);
905      break;
906    }
907    case clang::Type::ConstantArray: {
908      ET = RSExportConstantArrayType::Create(
909              Context,
910              static_cast<const clang::ConstantArrayType*>(CTI));
911      break;
912    }
913    default: {
914      Context->ReportError("unknown type cannot be exported: '%0'")
915          << T->getTypeClassName();
916      break;
917    }
918  }
919
920  return ET;
921}
922
923RSExportType *RSExportType::Create(RSContext *Context, const clang::Type *T,
924                                   ExportKind EK, const clang::VarDecl *VD) {
925  llvm::StringRef TypeName;
926  if (NormalizeType(T, TypeName, Context, VD, EK)) {
927    return Create(Context, T, TypeName, EK);
928  } else {
929    return nullptr;
930  }
931}
932
933RSExportType *RSExportType::CreateFromDecl(RSContext *Context,
934                                           const clang::VarDecl *VD) {
935  return RSExportType::Create(Context, GetTypeOfDecl(VD),
936                              NotLegacyKernelArgument, VD);
937}
938
939size_t RSExportType::getStoreSize() const {
940  return getRSContext()->getDataLayout().getTypeStoreSize(getLLVMType());
941}
942
943size_t RSExportType::getAllocSize() const {
944    return getRSContext()->getDataLayout().getTypeAllocSize(getLLVMType());
945}
946
947RSExportType::RSExportType(RSContext *Context,
948                           ExportClass Class,
949                           const llvm::StringRef &Name)
950    : RSExportable(Context, RSExportable::EX_TYPE),
951      mClass(Class),
952      // Make a copy on Name since memory stored @Name is either allocated in
953      // ASTContext or allocated in GetTypeName which will be destroyed later.
954      mName(Name.data(), Name.size()),
955      mLLVMType(nullptr) {
956  // Don't cache the type whose name start with '<'. Those type failed to
957  // get their name since constructing their name in GetTypeName() requiring
958  // complicated work.
959  if (!IsDummyName(Name)) {
960    // TODO(zonr): Need to check whether the insertion is successful or not.
961    Context->insertExportType(llvm::StringRef(Name), this);
962  }
963
964}
965
966bool RSExportType::keep() {
967  if (!RSExportable::keep())
968    return false;
969  // Invalidate converted LLVM type.
970  mLLVMType = nullptr;
971  return true;
972}
973
974bool RSExportType::matchODR(const RSExportType *E, bool /* LookInto */) const {
975  return (E->getClass() == getClass());
976}
977
978RSExportType::~RSExportType() {
979}
980
981/************************** RSExportPrimitiveType **************************/
982llvm::ManagedStatic<RSExportPrimitiveType::RSSpecificTypeMapTy>
983RSExportPrimitiveType::RSSpecificTypeMap;
984
985bool RSExportPrimitiveType::IsPrimitiveType(const clang::Type *T) {
986  if ((T != nullptr) && (T->getTypeClass() == clang::Type::Builtin))
987    return true;
988  else
989    return false;
990}
991
992DataType
993RSExportPrimitiveType::GetRSSpecificType(const llvm::StringRef &TypeName) {
994  if (TypeName.empty())
995    return DataTypeUnknown;
996
997  if (RSSpecificTypeMap->empty()) {
998    for (int i = 0; i < MatrixAndObjectDataTypesCount; i++) {
999      (*RSSpecificTypeMap)[MatrixAndObjectDataTypes[i].name] =
1000          MatrixAndObjectDataTypes[i].dataType;
1001    }
1002  }
1003
1004  RSSpecificTypeMapTy::const_iterator I = RSSpecificTypeMap->find(TypeName);
1005  if (I == RSSpecificTypeMap->end())
1006    return DataTypeUnknown;
1007  else
1008    return I->getValue();
1009}
1010
1011DataType RSExportPrimitiveType::GetRSSpecificType(const clang::Type *T) {
1012  T = GetCanonicalType(T);
1013  if ((T == nullptr) || (T->getTypeClass() != clang::Type::Record))
1014    return DataTypeUnknown;
1015
1016  return GetRSSpecificType( RSExportType::GetTypeName(T) );
1017}
1018
1019bool RSExportPrimitiveType::IsRSMatrixType(DataType DT) {
1020    if (DT < 0 || DT >= DataTypeMax) {
1021        return false;
1022    }
1023    return gReflectionTypes[DT].category == MatrixDataType;
1024}
1025
1026bool RSExportPrimitiveType::IsRSObjectType(DataType DT) {
1027    if (DT < 0 || DT >= DataTypeMax) {
1028        return false;
1029    }
1030    return gReflectionTypes[DT].category == ObjectDataType;
1031}
1032
1033bool RSExportPrimitiveType::IsStructureTypeWithRSObject(const clang::Type *T) {
1034  bool RSObjectTypeSeen = false;
1035  while (T && T->isArrayType()) {
1036    T = T->getArrayElementTypeNoTypeQual();
1037  }
1038
1039  const clang::RecordType *RT = T->getAsStructureType();
1040  if (!RT) {
1041    return false;
1042  }
1043
1044  const clang::RecordDecl *RD = RT->getDecl();
1045  if (RD) {
1046    RD = RD->getDefinition();
1047  }
1048  if (!RD) {
1049    return false;
1050  }
1051
1052  for (clang::RecordDecl::field_iterator FI = RD->field_begin(),
1053         FE = RD->field_end();
1054       FI != FE;
1055       FI++) {
1056    // We just look through all field declarations to see if we find a
1057    // declaration for an RS object type (or an array of one).
1058    const clang::FieldDecl *FD = *FI;
1059    const clang::Type *FT = RSExportType::GetTypeOfDecl(FD);
1060    while (FT && FT->isArrayType()) {
1061      FT = FT->getArrayElementTypeNoTypeQual();
1062    }
1063
1064    DataType DT = GetRSSpecificType(FT);
1065    if (IsRSObjectType(DT)) {
1066      // RS object types definitely need to be zero-initialized
1067      RSObjectTypeSeen = true;
1068    } else {
1069      switch (DT) {
1070        case DataTypeRSMatrix2x2:
1071        case DataTypeRSMatrix3x3:
1072        case DataTypeRSMatrix4x4:
1073          // Matrix types should get zero-initialized as well
1074          RSObjectTypeSeen = true;
1075          break;
1076        default:
1077          // Ignore all other primitive types
1078          break;
1079      }
1080      while (FT && FT->isArrayType()) {
1081        FT = FT->getArrayElementTypeNoTypeQual();
1082      }
1083      if (FT->isStructureType()) {
1084        // Recursively handle structs of structs (even though these can't
1085        // be exported, it is possible for a user to have them internally).
1086        RSObjectTypeSeen |= IsStructureTypeWithRSObject(FT);
1087      }
1088    }
1089  }
1090
1091  return RSObjectTypeSeen;
1092}
1093
1094size_t RSExportPrimitiveType::GetElementSizeInBits(const RSExportPrimitiveType *EPT) {
1095  int type = EPT->getType();
1096  slangAssert((type > DataTypeUnknown && type < DataTypeMax) &&
1097              "RSExportPrimitiveType::GetElementSizeInBits : unknown data type");
1098  // All RS object types are 256 bits in 64-bit RS.
1099  if (EPT->isRSObjectType() && EPT->getRSContext()->is64Bit()) {
1100    return 256;
1101  }
1102  return gReflectionTypes[type].size_in_bits;
1103}
1104
1105DataType
1106RSExportPrimitiveType::GetDataType(RSContext *Context, const clang::Type *T) {
1107  if (T == nullptr)
1108    return DataTypeUnknown;
1109
1110  switch (T->getTypeClass()) {
1111    case clang::Type::Builtin: {
1112      const clang::BuiltinType *BT =
1113              static_cast<const clang::BuiltinType*>(T->getCanonicalTypeInternal().getTypePtr());
1114      BuiltinInfo *info = FindBuiltinType(BT->getKind());
1115      if (info != nullptr) {
1116        return info->type;
1117      }
1118      // The size of type WChar depend on platform so we abandon the support
1119      // to them.
1120      Context->ReportError("built-in type cannot be exported: '%0'")
1121          << T->getTypeClassName();
1122      break;
1123    }
1124    case clang::Type::Record: {
1125      // must be RS object type
1126      return RSExportPrimitiveType::GetRSSpecificType(T);
1127    }
1128    default: {
1129      Context->ReportError("primitive type cannot be exported: '%0'")
1130          << T->getTypeClassName();
1131      break;
1132    }
1133  }
1134
1135  return DataTypeUnknown;
1136}
1137
1138RSExportPrimitiveType
1139*RSExportPrimitiveType::Create(RSContext *Context,
1140                               const clang::Type *T,
1141                               const llvm::StringRef &TypeName,
1142                               bool Normalized) {
1143  DataType DT = GetDataType(Context, T);
1144
1145  if ((DT == DataTypeUnknown) || TypeName.empty())
1146    return nullptr;
1147  else
1148    return new RSExportPrimitiveType(Context, ExportClassPrimitive, TypeName,
1149                                     DT, Normalized);
1150}
1151
1152RSExportPrimitiveType *RSExportPrimitiveType::Create(RSContext *Context,
1153                                                     const clang::Type *T) {
1154  llvm::StringRef TypeName;
1155  if (RSExportType::NormalizeType(T, TypeName, Context, nullptr,
1156                                  NotLegacyKernelArgument) &&
1157      IsPrimitiveType(T)) {
1158    return Create(Context, T, TypeName);
1159  } else {
1160    return nullptr;
1161  }
1162}
1163
1164llvm::Type *RSExportPrimitiveType::convertToLLVMType() const {
1165  llvm::LLVMContext &C = getRSContext()->getLLVMContext();
1166
1167  if (isRSObjectType()) {
1168    // struct {
1169    //   int *p;
1170    // } __attribute__((packed, aligned(pointer_size)))
1171    //
1172    // which is
1173    //
1174    // <{ [1 x i32] }> in LLVM
1175    //
1176    std::vector<llvm::Type *> Elements;
1177    if (getRSContext()->is64Bit()) {
1178      // 64-bit path
1179      Elements.push_back(llvm::ArrayType::get(llvm::Type::getInt64Ty(C), 4));
1180      return llvm::StructType::get(C, Elements, true);
1181    } else {
1182      // 32-bit legacy path
1183      Elements.push_back(llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 1));
1184      return llvm::StructType::get(C, Elements, true);
1185    }
1186  }
1187
1188  switch (mType) {
1189    case DataTypeFloat16: {
1190      return llvm::Type::getHalfTy(C);
1191      break;
1192    }
1193    case DataTypeFloat32: {
1194      return llvm::Type::getFloatTy(C);
1195      break;
1196    }
1197    case DataTypeFloat64: {
1198      return llvm::Type::getDoubleTy(C);
1199      break;
1200    }
1201    case DataTypeBoolean: {
1202      return llvm::Type::getInt1Ty(C);
1203      break;
1204    }
1205    case DataTypeSigned8:
1206    case DataTypeUnsigned8: {
1207      return llvm::Type::getInt8Ty(C);
1208      break;
1209    }
1210    case DataTypeSigned16:
1211    case DataTypeUnsigned16:
1212    case DataTypeUnsigned565:
1213    case DataTypeUnsigned5551:
1214    case DataTypeUnsigned4444: {
1215      return llvm::Type::getInt16Ty(C);
1216      break;
1217    }
1218    case DataTypeSigned32:
1219    case DataTypeUnsigned32: {
1220      return llvm::Type::getInt32Ty(C);
1221      break;
1222    }
1223    case DataTypeSigned64:
1224    case DataTypeUnsigned64: {
1225      return llvm::Type::getInt64Ty(C);
1226      break;
1227    }
1228    default: {
1229      slangAssert(false && "Unknown data type");
1230    }
1231  }
1232
1233  return nullptr;
1234}
1235
1236bool RSExportPrimitiveType::matchODR(const RSExportType *E,
1237                                     bool /* LookInto */) const {
1238  CHECK_PARENT_EQUALITY(RSExportType, E);
1239  return (static_cast<const RSExportPrimitiveType*>(E)->getType() == getType());
1240}
1241
1242RSReflectionType *RSExportPrimitiveType::getRSReflectionType(DataType DT) {
1243  if (DT > DataTypeUnknown && DT < DataTypeMax) {
1244    return &gReflectionTypes[DT];
1245  } else {
1246    return nullptr;
1247  }
1248}
1249
1250/**************************** RSExportPointerType ****************************/
1251
1252RSExportPointerType
1253*RSExportPointerType::Create(RSContext *Context,
1254                             const clang::PointerType *PT,
1255                             const llvm::StringRef &TypeName) {
1256  const clang::Type *PointeeType = GetPointeeType(PT);
1257  const RSExportType *PointeeET;
1258
1259  if (PointeeType->getTypeClass() != clang::Type::Pointer) {
1260    PointeeET = RSExportType::Create(Context, PointeeType,
1261                                     NotLegacyKernelArgument);
1262  } else {
1263    // Double or higher dimension of pointer, export as int*
1264    PointeeET = RSExportPrimitiveType::Create(Context,
1265                    Context->getASTContext().IntTy.getTypePtr());
1266  }
1267
1268  if (PointeeET == nullptr) {
1269    // Error diagnostic is emitted for corresponding pointee type
1270    return nullptr;
1271  }
1272
1273  return new RSExportPointerType(Context, TypeName, PointeeET);
1274}
1275
1276llvm::Type *RSExportPointerType::convertToLLVMType() const {
1277  llvm::Type *PointeeType = mPointeeType->getLLVMType();
1278  return llvm::PointerType::getUnqual(PointeeType);
1279}
1280
1281bool RSExportPointerType::keep() {
1282  if (!RSExportType::keep())
1283    return false;
1284  const_cast<RSExportType*>(mPointeeType)->keep();
1285  return true;
1286}
1287
1288bool RSExportPointerType::matchODR(const RSExportType *E,
1289                                   bool /* LookInto */) const {
1290  // Exported types cannot contain pointers
1291  slangAssert(false && "Not supposed to perform ODR check on pointers");
1292  return false;
1293}
1294
1295/***************************** RSExportVectorType *****************************/
1296llvm::StringRef
1297RSExportVectorType::GetTypeName(const clang::ExtVectorType *EVT) {
1298  const clang::Type *ElementType = GetExtVectorElementType(EVT);
1299  llvm::StringRef name;
1300
1301  if ((ElementType->getTypeClass() != clang::Type::Builtin))
1302    return name;
1303
1304  const clang::BuiltinType *BT =
1305          static_cast<const clang::BuiltinType*>(
1306              ElementType->getCanonicalTypeInternal().getTypePtr());
1307
1308  if ((EVT->getNumElements() < 1) ||
1309      (EVT->getNumElements() > 4))
1310    return name;
1311
1312  BuiltinInfo *info = FindBuiltinType(BT->getKind());
1313  if (info != nullptr) {
1314    int I = EVT->getNumElements() - 1;
1315    if (I < kMaxVectorSize) {
1316      name = info->cname[I];
1317    } else {
1318      slangAssert(false && "Max vector is 4");
1319    }
1320  }
1321  return name;
1322}
1323
1324RSExportVectorType *RSExportVectorType::Create(RSContext *Context,
1325                                               const clang::ExtVectorType *EVT,
1326                                               const llvm::StringRef &TypeName,
1327                                               bool Normalized) {
1328  slangAssert(EVT != nullptr && EVT->getTypeClass() == clang::Type::ExtVector);
1329
1330  const clang::Type *ElementType = GetExtVectorElementType(EVT);
1331  DataType DT = RSExportPrimitiveType::GetDataType(Context, ElementType);
1332
1333  if (DT != DataTypeUnknown)
1334    return new RSExportVectorType(Context,
1335                                  TypeName,
1336                                  DT,
1337                                  Normalized,
1338                                  EVT->getNumElements());
1339  else
1340    return nullptr;
1341}
1342
1343llvm::Type *RSExportVectorType::convertToLLVMType() const {
1344  llvm::Type *ElementType = RSExportPrimitiveType::convertToLLVMType();
1345  return llvm::VectorType::get(ElementType, getNumElement());
1346}
1347
1348bool RSExportVectorType::matchODR(const RSExportType *E,
1349                                  bool /* LookInto*/) const {
1350  CHECK_PARENT_EQUALITY(RSExportPrimitiveType, E);
1351  return (static_cast<const RSExportVectorType*>(E)->getNumElement()
1352              == getNumElement());
1353}
1354
1355/***************************** RSExportMatrixType *****************************/
1356RSExportMatrixType *RSExportMatrixType::Create(RSContext *Context,
1357                                               const clang::RecordType *RT,
1358                                               const llvm::StringRef &TypeName,
1359                                               unsigned Dim) {
1360  slangAssert((RT != nullptr) && (RT->getTypeClass() == clang::Type::Record));
1361  slangAssert((Dim > 1) && "Invalid dimension of matrix");
1362
1363  // Check whether the struct rs_matrix is in our expected form (but assume it's
1364  // correct if we're not sure whether it's correct or not)
1365  const clang::RecordDecl* RD = RT->getDecl();
1366  RD = RD->getDefinition();
1367  if (RD != nullptr) {
1368    // Find definition, perform further examination
1369    if (RD->field_empty()) {
1370      Context->ReportError(
1371          RD->getLocation(),
1372          "invalid matrix struct: must have 1 field for saving values: '%0'")
1373          << RD->getName();
1374      return nullptr;
1375    }
1376
1377    clang::RecordDecl::field_iterator FIT = RD->field_begin();
1378    const clang::FieldDecl *FD = *FIT;
1379    const clang::Type *FT = RSExportType::GetTypeOfDecl(FD);
1380    if ((FT == nullptr) || (FT->getTypeClass() != clang::Type::ConstantArray)) {
1381      Context->ReportError(RD->getLocation(),
1382                           "invalid matrix struct: first field should"
1383                           " be an array with constant size: '%0'")
1384          << RD->getName();
1385      return nullptr;
1386    }
1387    const clang::ConstantArrayType *CAT =
1388      static_cast<const clang::ConstantArrayType *>(FT);
1389    const clang::Type *ElementType = GetConstantArrayElementType(CAT);
1390    if ((ElementType == nullptr) ||
1391        (ElementType->getTypeClass() != clang::Type::Builtin) ||
1392        (static_cast<const clang::BuiltinType *>(ElementType)->getKind() !=
1393         clang::BuiltinType::Float)) {
1394      Context->ReportError(RD->getLocation(),
1395                           "invalid matrix struct: first field "
1396                           "should be a float array: '%0'")
1397          << RD->getName();
1398      return nullptr;
1399    }
1400
1401    if (CAT->getSize() != Dim * Dim) {
1402      Context->ReportError(RD->getLocation(),
1403                           "invalid matrix struct: first field "
1404                           "should be an array with size %0: '%1'")
1405          << (Dim * Dim) << (RD->getName());
1406      return nullptr;
1407    }
1408
1409    FIT++;
1410    if (FIT != RD->field_end()) {
1411      Context->ReportError(RD->getLocation(),
1412                           "invalid matrix struct: must have "
1413                           "exactly 1 field: '%0'")
1414          << RD->getName();
1415      return nullptr;
1416    }
1417  }
1418
1419  return new RSExportMatrixType(Context, TypeName, Dim);
1420}
1421
1422llvm::Type *RSExportMatrixType::convertToLLVMType() const {
1423  // Construct LLVM type:
1424  // struct {
1425  //  float X[mDim * mDim];
1426  // }
1427
1428  llvm::LLVMContext &C = getRSContext()->getLLVMContext();
1429  llvm::ArrayType *X = llvm::ArrayType::get(llvm::Type::getFloatTy(C),
1430                                            mDim * mDim);
1431  return llvm::StructType::get(C, X, false);
1432}
1433
1434bool RSExportMatrixType::matchODR(const RSExportType *E,
1435                                  bool /* LookInto */) const {
1436  CHECK_PARENT_EQUALITY(RSExportType, E);
1437  return (static_cast<const RSExportMatrixType*>(E)->getDim() == getDim());
1438}
1439
1440/************************* RSExportConstantArrayType *************************/
1441RSExportConstantArrayType
1442*RSExportConstantArrayType::Create(RSContext *Context,
1443                                   const clang::ConstantArrayType *CAT) {
1444  slangAssert(CAT != nullptr && CAT->getTypeClass() == clang::Type::ConstantArray);
1445
1446  slangAssert((CAT->getSize().getActiveBits() < 32) && "array too large");
1447
1448  unsigned Size = static_cast<unsigned>(CAT->getSize().getZExtValue());
1449  slangAssert((Size > 0) && "Constant array should have size greater than 0");
1450
1451  const clang::Type *ElementType = GetConstantArrayElementType(CAT);
1452  RSExportType *ElementET = RSExportType::Create(Context, ElementType,
1453                                                 NotLegacyKernelArgument);
1454
1455  if (ElementET == nullptr) {
1456    return nullptr;
1457  }
1458
1459  return new RSExportConstantArrayType(Context,
1460                                       ElementET,
1461                                       Size);
1462}
1463
1464llvm::Type *RSExportConstantArrayType::convertToLLVMType() const {
1465  return llvm::ArrayType::get(mElementType->getLLVMType(), getNumElement());
1466}
1467
1468bool RSExportConstantArrayType::keep() {
1469  if (!RSExportType::keep())
1470    return false;
1471  const_cast<RSExportType*>(mElementType)->keep();
1472  return true;
1473}
1474
1475bool RSExportConstantArrayType::matchODR(const RSExportType *E,
1476                                         bool LookInto) const {
1477  CHECK_PARENT_EQUALITY(RSExportType, E);
1478  const RSExportConstantArrayType *RHS =
1479      static_cast<const RSExportConstantArrayType*>(E);
1480  return ((getNumElement() == RHS->getNumElement()) &&
1481          (getElementType()->matchODR(RHS->getElementType(), LookInto)));
1482}
1483
1484/**************************** RSExportRecordType ****************************/
1485RSExportRecordType *RSExportRecordType::Create(RSContext *Context,
1486                                               const clang::RecordType *RT,
1487                                               const llvm::StringRef &TypeName,
1488                                               bool mIsArtificial) {
1489  slangAssert(RT != nullptr && RT->getTypeClass() == clang::Type::Record);
1490
1491  const clang::RecordDecl *RD = RT->getDecl();
1492  slangAssert(RD->isStruct());
1493
1494  RD = RD->getDefinition();
1495  if (RD == nullptr) {
1496    slangAssert(false && "struct is not defined in this module");
1497    return nullptr;
1498  }
1499
1500  // Struct layout construct by clang. We rely on this for obtaining the
1501  // alloc size of a struct and offset of every field in that struct.
1502  const clang::ASTRecordLayout *RL =
1503      &Context->getASTContext().getASTRecordLayout(RD);
1504  slangAssert((RL != nullptr) &&
1505      "Failed to retrieve the struct layout from Clang.");
1506
1507  RSExportRecordType *ERT =
1508      new RSExportRecordType(Context,
1509                             TypeName,
1510                             RD->hasAttr<clang::PackedAttr>(),
1511                             mIsArtificial,
1512                             RL->getDataSize().getQuantity(),
1513                             RL->getSize().getQuantity());
1514  unsigned int Index = 0;
1515
1516  for (clang::RecordDecl::field_iterator FI = RD->field_begin(),
1517           FE = RD->field_end();
1518       FI != FE;
1519       FI++, Index++) {
1520
1521    // FIXME: All fields should be primitive type
1522    slangAssert(FI->getKind() == clang::Decl::Field);
1523    clang::FieldDecl *FD = *FI;
1524
1525    if (FD->isBitField()) {
1526      return nullptr;
1527    }
1528
1529    if (FD->isImplicit() && (FD->getName() == RS_PADDING_FIELD_NAME))
1530      continue;
1531
1532    // Type
1533    RSExportType *ET = RSExportElement::CreateFromDecl(Context, FD);
1534
1535    if (ET != nullptr) {
1536      ERT->mFields.push_back(
1537          new Field(ET, FD->getName(), ERT,
1538                    static_cast<size_t>(RL->getFieldOffset(Index) >> 3)));
1539    } else {
1540      // clang static analysis complains about a potential memory leak
1541      // for the memory pointed by ERT at the end of this basic
1542      // block. This is a false warning because the compiler does not
1543      // see that the pointer to this memory is saved away in the
1544      // constructor for RSExportRecordType by calling
1545      // RSContext::newExportable(this). So, we disable this
1546      // particular instance of the warning.
1547      Context->ReportError(RD->getLocation(),
1548                           "field type cannot be exported: '%0.%1'")
1549          << RD->getName() << FD->getName(); // NOLINT
1550      return nullptr;
1551    }
1552  }
1553
1554  return ERT;
1555}
1556
1557llvm::Type *RSExportRecordType::convertToLLVMType() const {
1558  // Create an opaque type since struct may reference itself recursively.
1559
1560  // TODO(sliao): LLVM took out the OpaqueType. Any other to migrate to?
1561  std::vector<llvm::Type*> FieldTypes;
1562
1563  for (const_field_iterator FI = fields_begin(), FE = fields_end();
1564       FI != FE;
1565       FI++) {
1566    const Field *F = *FI;
1567    const RSExportType *FET = F->getType();
1568
1569    FieldTypes.push_back(FET->getLLVMType());
1570  }
1571
1572  llvm::StructType *ST = llvm::StructType::get(getRSContext()->getLLVMContext(),
1573                                               FieldTypes,
1574                                               mIsPacked);
1575  if (ST != nullptr) {
1576    return ST;
1577  } else {
1578    return nullptr;
1579  }
1580}
1581
1582bool RSExportRecordType::keep() {
1583  if (!RSExportType::keep())
1584    return false;
1585  for (std::list<const Field*>::iterator I = mFields.begin(),
1586          E = mFields.end();
1587       I != E;
1588       I++) {
1589    const_cast<RSExportType*>((*I)->getType())->keep();
1590  }
1591  return true;
1592}
1593
1594bool RSExportRecordType::matchODR(const RSExportType *E, bool LookInto) const {
1595  CHECK_PARENT_EQUALITY(RSExportType, E);
1596  // Enforce ODR checking - the type E represents must hold
1597  // *exactly* the same "definition" as the one defined previously. We
1598  // say two record types A and B have the same definition iff:
1599  //
1600  //  struct A {              struct B {
1601  //    Type(a1) a1,            Type(b1) b1,
1602  //    Type(a2) a2,            Type(b1) b2,
1603  //    ...                     ...
1604  //    Type(aN) aN             Type(bM) bM,
1605  //  };                      }
1606  //  Cond. #0. A = B;
1607  //  Cond. #1. They have same number of fields, i.e., N = M;
1608  //  Cond. #2. for (i := 1 to N)
1609  //              Type(ai).matchODR(Type(bi)) must hold;
1610  //  Cond. #3. for (i := 1 to N)
1611  //              Name(ai) = Name(bi) must hold;
1612  //
1613  // where,
1614  //  Type(F) = the type of field F and
1615  //  Name(F) = the field name.
1616
1617
1618  const RSExportRecordType *ERT = static_cast<const RSExportRecordType*>(E);
1619  // Cond. #0.
1620  if (getName() != ERT->getName())
1621    return false;
1622
1623  // Examine fields - types and names
1624  if (LookInto) {
1625    // Cond. #1
1626    if (ERT->getFields().size() != getFields().size())
1627      return false;
1628
1629    for (RSExportRecordType::const_field_iterator AI = fields_begin(),
1630         BI = ERT->fields_begin(), AE = fields_end(); AI != AE; ++AI, ++BI) {
1631      const RSExportType *AITy = (*AI)->getType();
1632      const RSExportType *BITy = (*BI)->getType();
1633      // Cond. #3; field names must agree
1634      if ((*AI)->getName() != (*BI)->getName())
1635        return false;
1636
1637      // Cond. #2; field types must agree recursively until we see another
1638      // next level of RSExportRecordType - such field types will be
1639      // examined and reported later when checkODR() encounters them.
1640      if (!AITy->matchODR(BITy, false))
1641        return false;
1642    }
1643  }
1644  return true;
1645}
1646
1647void RSExportType::convertToRTD(RSReflectionTypeData *rtd) const {
1648    memset(rtd, 0, sizeof(*rtd));
1649    rtd->vecSize = 1;
1650
1651    switch(getClass()) {
1652    case RSExportType::ExportClassPrimitive: {
1653            const RSExportPrimitiveType *EPT = static_cast<const RSExportPrimitiveType*>(this);
1654            rtd->type = RSExportPrimitiveType::getRSReflectionType(EPT);
1655            return;
1656        }
1657    case RSExportType::ExportClassPointer: {
1658            const RSExportPointerType *EPT = static_cast<const RSExportPointerType*>(this);
1659            const RSExportType *PointeeType = EPT->getPointeeType();
1660            PointeeType->convertToRTD(rtd);
1661            rtd->isPointer = true;
1662            return;
1663        }
1664    case RSExportType::ExportClassVector: {
1665            const RSExportVectorType *EVT = static_cast<const RSExportVectorType*>(this);
1666            rtd->type = EVT->getRSReflectionType(EVT);
1667            rtd->vecSize = EVT->getNumElement();
1668            return;
1669        }
1670    case RSExportType::ExportClassMatrix: {
1671            const RSExportMatrixType *EMT = static_cast<const RSExportMatrixType*>(this);
1672            unsigned Dim = EMT->getDim();
1673            slangAssert((Dim >= 2) && (Dim <= 4));
1674            rtd->type = &gReflectionTypes[15 + Dim-2];
1675            return;
1676        }
1677    case RSExportType::ExportClassConstantArray: {
1678            const RSExportConstantArrayType* CAT =
1679              static_cast<const RSExportConstantArrayType*>(this);
1680            CAT->getElementType()->convertToRTD(rtd);
1681            rtd->arraySize = CAT->getNumElement();
1682            return;
1683        }
1684    case RSExportType::ExportClassRecord: {
1685            slangAssert(!"RSExportType::ExportClassRecord not implemented");
1686            return;// RS_TYPE_CLASS_NAME_PREFIX + ET->getName() + ".Item";
1687        }
1688    default: {
1689            slangAssert(false && "Unknown class of type");
1690        }
1691    }
1692}
1693
1694
1695}  // namespace slang
1696