Home | History | Annotate | Download | only in CodeGen
      1 //===--- CodeGenTypes.cpp - Type translation for LLVM CodeGen -------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This is the code that handles AST -> LLVM type lowering.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #include "CodeGenTypes.h"
     15 #include "CGCXXABI.h"
     16 #include "CGCall.h"
     17 #include "CGOpenCLRuntime.h"
     18 #include "CGRecordLayout.h"
     19 #include "TargetInfo.h"
     20 #include "clang/AST/ASTContext.h"
     21 #include "clang/AST/DeclCXX.h"
     22 #include "clang/AST/DeclObjC.h"
     23 #include "clang/AST/Expr.h"
     24 #include "clang/AST/RecordLayout.h"
     25 #include "clang/CodeGen/CGFunctionInfo.h"
     26 #include "llvm/IR/DataLayout.h"
     27 #include "llvm/IR/DerivedTypes.h"
     28 #include "llvm/IR/Module.h"
     29 using namespace clang;
     30 using namespace CodeGen;
     31 
     32 CodeGenTypes::CodeGenTypes(CodeGenModule &cgm)
     33   : CGM(cgm), Context(cgm.getContext()), TheModule(cgm.getModule()),
     34     TheDataLayout(cgm.getDataLayout()),
     35     Target(cgm.getTarget()), TheCXXABI(cgm.getCXXABI()),
     36     TheABIInfo(cgm.getTargetCodeGenInfo().getABIInfo()) {
     37   SkippedLayout = false;
     38 }
     39 
     40 CodeGenTypes::~CodeGenTypes() {
     41   llvm::DeleteContainerSeconds(CGRecordLayouts);
     42 
     43   for (llvm::FoldingSet<CGFunctionInfo>::iterator
     44        I = FunctionInfos.begin(), E = FunctionInfos.end(); I != E; )
     45     delete &*I++;
     46 }
     47 
     48 void CodeGenTypes::addRecordTypeName(const RecordDecl *RD,
     49                                      llvm::StructType *Ty,
     50                                      StringRef suffix) {
     51   SmallString<256> TypeName;
     52   llvm::raw_svector_ostream OS(TypeName);
     53   OS << RD->getKindName() << '.';
     54 
     55   // Name the codegen type after the typedef name
     56   // if there is no tag type name available
     57   if (RD->getIdentifier()) {
     58     // FIXME: We should not have to check for a null decl context here.
     59     // Right now we do it because the implicit Obj-C decls don't have one.
     60     if (RD->getDeclContext())
     61       RD->printQualifiedName(OS);
     62     else
     63       RD->printName(OS);
     64   } else if (const TypedefNameDecl *TDD = RD->getTypedefNameForAnonDecl()) {
     65     // FIXME: We should not have to check for a null decl context here.
     66     // Right now we do it because the implicit Obj-C decls don't have one.
     67     if (TDD->getDeclContext())
     68       TDD->printQualifiedName(OS);
     69     else
     70       TDD->printName(OS);
     71   } else
     72     OS << "anon";
     73 
     74   if (!suffix.empty())
     75     OS << suffix;
     76 
     77   Ty->setName(OS.str());
     78 }
     79 
     80 /// ConvertTypeForMem - Convert type T into a llvm::Type.  This differs from
     81 /// ConvertType in that it is used to convert to the memory representation for
     82 /// a type.  For example, the scalar representation for _Bool is i1, but the
     83 /// memory representation is usually i8 or i32, depending on the target.
     84 llvm::Type *CodeGenTypes::ConvertTypeForMem(QualType T){
     85   llvm::Type *R = ConvertType(T);
     86 
     87   // If this is a non-bool type, don't map it.
     88   if (!R->isIntegerTy(1))
     89     return R;
     90 
     91   // Otherwise, return an integer of the target-specified size.
     92   return llvm::IntegerType::get(getLLVMContext(),
     93                                 (unsigned)Context.getTypeSize(T));
     94 }
     95 
     96 
     97 /// isRecordLayoutComplete - Return true if the specified type is already
     98 /// completely laid out.
     99 bool CodeGenTypes::isRecordLayoutComplete(const Type *Ty) const {
    100   llvm::DenseMap<const Type*, llvm::StructType *>::const_iterator I =
    101   RecordDeclTypes.find(Ty);
    102   return I != RecordDeclTypes.end() && !I->second->isOpaque();
    103 }
    104 
    105 static bool
    106 isSafeToConvert(QualType T, CodeGenTypes &CGT,
    107                 llvm::SmallPtrSet<const RecordDecl*, 16> &AlreadyChecked);
    108 
    109 
    110 /// isSafeToConvert - Return true if it is safe to convert the specified record
    111 /// decl to IR and lay it out, false if doing so would cause us to get into a
    112 /// recursive compilation mess.
    113 static bool
    114 isSafeToConvert(const RecordDecl *RD, CodeGenTypes &CGT,
    115                 llvm::SmallPtrSet<const RecordDecl*, 16> &AlreadyChecked) {
    116   // If we have already checked this type (maybe the same type is used by-value
    117   // multiple times in multiple structure fields, don't check again.
    118   if (!AlreadyChecked.insert(RD)) return true;
    119 
    120   const Type *Key = CGT.getContext().getTagDeclType(RD).getTypePtr();
    121 
    122   // If this type is already laid out, converting it is a noop.
    123   if (CGT.isRecordLayoutComplete(Key)) return true;
    124 
    125   // If this type is currently being laid out, we can't recursively compile it.
    126   if (CGT.isRecordBeingLaidOut(Key))
    127     return false;
    128 
    129   // If this type would require laying out bases that are currently being laid
    130   // out, don't do it.  This includes virtual base classes which get laid out
    131   // when a class is translated, even though they aren't embedded by-value into
    132   // the class.
    133   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
    134     for (const auto &I : CRD->bases())
    135       if (!isSafeToConvert(I.getType()->getAs<RecordType>()->getDecl(),
    136                            CGT, AlreadyChecked))
    137         return false;
    138   }
    139 
    140   // If this type would require laying out members that are currently being laid
    141   // out, don't do it.
    142   for (const auto *I : RD->fields())
    143     if (!isSafeToConvert(I->getType(), CGT, AlreadyChecked))
    144       return false;
    145 
    146   // If there are no problems, lets do it.
    147   return true;
    148 }
    149 
    150 /// isSafeToConvert - Return true if it is safe to convert this field type,
    151 /// which requires the structure elements contained by-value to all be
    152 /// recursively safe to convert.
    153 static bool
    154 isSafeToConvert(QualType T, CodeGenTypes &CGT,
    155                 llvm::SmallPtrSet<const RecordDecl*, 16> &AlreadyChecked) {
    156   T = T.getCanonicalType();
    157 
    158   // If this is a record, check it.
    159   if (const RecordType *RT = dyn_cast<RecordType>(T))
    160     return isSafeToConvert(RT->getDecl(), CGT, AlreadyChecked);
    161 
    162   // If this is an array, check the elements, which are embedded inline.
    163   if (const ArrayType *AT = dyn_cast<ArrayType>(T))
    164     return isSafeToConvert(AT->getElementType(), CGT, AlreadyChecked);
    165 
    166   // Otherwise, there is no concern about transforming this.  We only care about
    167   // things that are contained by-value in a structure that can have another
    168   // structure as a member.
    169   return true;
    170 }
    171 
    172 
    173 /// isSafeToConvert - Return true if it is safe to convert the specified record
    174 /// decl to IR and lay it out, false if doing so would cause us to get into a
    175 /// recursive compilation mess.
    176 static bool isSafeToConvert(const RecordDecl *RD, CodeGenTypes &CGT) {
    177   // If no structs are being laid out, we can certainly do this one.
    178   if (CGT.noRecordsBeingLaidOut()) return true;
    179 
    180   llvm::SmallPtrSet<const RecordDecl*, 16> AlreadyChecked;
    181   return isSafeToConvert(RD, CGT, AlreadyChecked);
    182 }
    183 
    184 /// isFuncParamTypeConvertible - Return true if the specified type in a
    185 /// function parameter or result position can be converted to an IR type at this
    186 /// point.  This boils down to being whether it is complete, as well as whether
    187 /// we've temporarily deferred expanding the type because we're in a recursive
    188 /// context.
    189 bool CodeGenTypes::isFuncParamTypeConvertible(QualType Ty) {
    190   // If this isn't a tagged type, we can convert it!
    191   const TagType *TT = Ty->getAs<TagType>();
    192   if (!TT) return true;
    193 
    194   // Incomplete types cannot be converted.
    195   if (TT->isIncompleteType())
    196     return false;
    197 
    198   // If this is an enum, then it is always safe to convert.
    199   const RecordType *RT = dyn_cast<RecordType>(TT);
    200   if (!RT) return true;
    201 
    202   // Otherwise, we have to be careful.  If it is a struct that we're in the
    203   // process of expanding, then we can't convert the function type.  That's ok
    204   // though because we must be in a pointer context under the struct, so we can
    205   // just convert it to a dummy type.
    206   //
    207   // We decide this by checking whether ConvertRecordDeclType returns us an
    208   // opaque type for a struct that we know is defined.
    209   return isSafeToConvert(RT->getDecl(), *this);
    210 }
    211 
    212 
    213 /// Code to verify a given function type is complete, i.e. the return type
    214 /// and all of the parameter types are complete.  Also check to see if we are in
    215 /// a RS_StructPointer context, and if so whether any struct types have been
    216 /// pended.  If so, we don't want to ask the ABI lowering code to handle a type
    217 /// that cannot be converted to an IR type.
    218 bool CodeGenTypes::isFuncTypeConvertible(const FunctionType *FT) {
    219   if (!isFuncParamTypeConvertible(FT->getReturnType()))
    220     return false;
    221 
    222   if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT))
    223     for (unsigned i = 0, e = FPT->getNumParams(); i != e; i++)
    224       if (!isFuncParamTypeConvertible(FPT->getParamType(i)))
    225         return false;
    226 
    227   return true;
    228 }
    229 
    230 /// UpdateCompletedType - When we find the full definition for a TagDecl,
    231 /// replace the 'opaque' type we previously made for it if applicable.
    232 void CodeGenTypes::UpdateCompletedType(const TagDecl *TD) {
    233   // If this is an enum being completed, then we flush all non-struct types from
    234   // the cache.  This allows function types and other things that may be derived
    235   // from the enum to be recomputed.
    236   if (const EnumDecl *ED = dyn_cast<EnumDecl>(TD)) {
    237     // Only flush the cache if we've actually already converted this type.
    238     if (TypeCache.count(ED->getTypeForDecl())) {
    239       // Okay, we formed some types based on this.  We speculated that the enum
    240       // would be lowered to i32, so we only need to flush the cache if this
    241       // didn't happen.
    242       if (!ConvertType(ED->getIntegerType())->isIntegerTy(32))
    243         TypeCache.clear();
    244     }
    245     // If necessary, provide the full definition of a type only used with a
    246     // declaration so far.
    247     if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
    248       DI->completeType(ED);
    249     return;
    250   }
    251 
    252   // If we completed a RecordDecl that we previously used and converted to an
    253   // anonymous type, then go ahead and complete it now.
    254   const RecordDecl *RD = cast<RecordDecl>(TD);
    255   if (RD->isDependentType()) return;
    256 
    257   // Only complete it if we converted it already.  If we haven't converted it
    258   // yet, we'll just do it lazily.
    259   if (RecordDeclTypes.count(Context.getTagDeclType(RD).getTypePtr()))
    260     ConvertRecordDeclType(RD);
    261 
    262   // If necessary, provide the full definition of a type only used with a
    263   // declaration so far.
    264   if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
    265     DI->completeType(RD);
    266 }
    267 
    268 static llvm::Type *getTypeForFormat(llvm::LLVMContext &VMContext,
    269                                     const llvm::fltSemantics &format,
    270                                     bool UseNativeHalf = false) {
    271   if (&format == &llvm::APFloat::IEEEhalf) {
    272     if (UseNativeHalf)
    273       return llvm::Type::getHalfTy(VMContext);
    274     else
    275       return llvm::Type::getInt16Ty(VMContext);
    276   }
    277   if (&format == &llvm::APFloat::IEEEsingle)
    278     return llvm::Type::getFloatTy(VMContext);
    279   if (&format == &llvm::APFloat::IEEEdouble)
    280     return llvm::Type::getDoubleTy(VMContext);
    281   if (&format == &llvm::APFloat::IEEEquad)
    282     return llvm::Type::getFP128Ty(VMContext);
    283   if (&format == &llvm::APFloat::PPCDoubleDouble)
    284     return llvm::Type::getPPC_FP128Ty(VMContext);
    285   if (&format == &llvm::APFloat::x87DoubleExtended)
    286     return llvm::Type::getX86_FP80Ty(VMContext);
    287   llvm_unreachable("Unknown float format!");
    288 }
    289 
    290 /// ConvertType - Convert the specified type to its LLVM form.
    291 llvm::Type *CodeGenTypes::ConvertType(QualType T) {
    292   T = Context.getCanonicalType(T);
    293 
    294   const Type *Ty = T.getTypePtr();
    295 
    296   // RecordTypes are cached and processed specially.
    297   if (const RecordType *RT = dyn_cast<RecordType>(Ty))
    298     return ConvertRecordDeclType(RT->getDecl());
    299 
    300   // See if type is already cached.
    301   llvm::DenseMap<const Type *, llvm::Type *>::iterator TCI = TypeCache.find(Ty);
    302   // If type is found in map then use it. Otherwise, convert type T.
    303   if (TCI != TypeCache.end())
    304     return TCI->second;
    305 
    306   // If we don't have it in the cache, convert it now.
    307   llvm::Type *ResultType = nullptr;
    308   switch (Ty->getTypeClass()) {
    309   case Type::Record: // Handled above.
    310 #define TYPE(Class, Base)
    311 #define ABSTRACT_TYPE(Class, Base)
    312 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
    313 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
    314 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
    315 #include "clang/AST/TypeNodes.def"
    316     llvm_unreachable("Non-canonical or dependent types aren't possible.");
    317 
    318   case Type::Builtin: {
    319     switch (cast<BuiltinType>(Ty)->getKind()) {
    320     case BuiltinType::Void:
    321     case BuiltinType::ObjCId:
    322     case BuiltinType::ObjCClass:
    323     case BuiltinType::ObjCSel:
    324       // LLVM void type can only be used as the result of a function call.  Just
    325       // map to the same as char.
    326       ResultType = llvm::Type::getInt8Ty(getLLVMContext());
    327       break;
    328 
    329     case BuiltinType::Bool:
    330       // Note that we always return bool as i1 for use as a scalar type.
    331       ResultType = llvm::Type::getInt1Ty(getLLVMContext());
    332       break;
    333 
    334     case BuiltinType::Char_S:
    335     case BuiltinType::Char_U:
    336     case BuiltinType::SChar:
    337     case BuiltinType::UChar:
    338     case BuiltinType::Short:
    339     case BuiltinType::UShort:
    340     case BuiltinType::Int:
    341     case BuiltinType::UInt:
    342     case BuiltinType::Long:
    343     case BuiltinType::ULong:
    344     case BuiltinType::LongLong:
    345     case BuiltinType::ULongLong:
    346     case BuiltinType::WChar_S:
    347     case BuiltinType::WChar_U:
    348     case BuiltinType::Char16:
    349     case BuiltinType::Char32:
    350       ResultType = llvm::IntegerType::get(getLLVMContext(),
    351                                  static_cast<unsigned>(Context.getTypeSize(T)));
    352       break;
    353 
    354     case BuiltinType::Half:
    355       // Half FP can either be storage-only (lowered to i16) or native.
    356       ResultType = getTypeForFormat(getLLVMContext(),
    357           Context.getFloatTypeSemantics(T),
    358           Context.getLangOpts().NativeHalfType);
    359       break;
    360     case BuiltinType::Float:
    361     case BuiltinType::Double:
    362     case BuiltinType::LongDouble:
    363       ResultType = getTypeForFormat(getLLVMContext(),
    364                                     Context.getFloatTypeSemantics(T),
    365                                     /* UseNativeHalf = */ false);
    366       break;
    367 
    368     case BuiltinType::NullPtr:
    369       // Model std::nullptr_t as i8*
    370       ResultType = llvm::Type::getInt8PtrTy(getLLVMContext());
    371       break;
    372 
    373     case BuiltinType::UInt128:
    374     case BuiltinType::Int128:
    375       ResultType = llvm::IntegerType::get(getLLVMContext(), 128);
    376       break;
    377 
    378     case BuiltinType::OCLImage1d:
    379     case BuiltinType::OCLImage1dArray:
    380     case BuiltinType::OCLImage1dBuffer:
    381     case BuiltinType::OCLImage2d:
    382     case BuiltinType::OCLImage2dArray:
    383     case BuiltinType::OCLImage3d:
    384     case BuiltinType::OCLSampler:
    385     case BuiltinType::OCLEvent:
    386       ResultType = CGM.getOpenCLRuntime().convertOpenCLSpecificType(Ty);
    387       break;
    388 
    389     case BuiltinType::Dependent:
    390 #define BUILTIN_TYPE(Id, SingletonId)
    391 #define PLACEHOLDER_TYPE(Id, SingletonId) \
    392     case BuiltinType::Id:
    393 #include "clang/AST/BuiltinTypes.def"
    394       llvm_unreachable("Unexpected placeholder builtin type!");
    395     }
    396     break;
    397   }
    398   case Type::Auto:
    399     llvm_unreachable("Unexpected undeduced auto type!");
    400   case Type::Complex: {
    401     llvm::Type *EltTy = ConvertType(cast<ComplexType>(Ty)->getElementType());
    402     ResultType = llvm::StructType::get(EltTy, EltTy, NULL);
    403     break;
    404   }
    405   case Type::LValueReference:
    406   case Type::RValueReference: {
    407     const ReferenceType *RTy = cast<ReferenceType>(Ty);
    408     QualType ETy = RTy->getPointeeType();
    409     llvm::Type *PointeeType = ConvertTypeForMem(ETy);
    410     unsigned AS = Context.getTargetAddressSpace(ETy);
    411     ResultType = llvm::PointerType::get(PointeeType, AS);
    412     break;
    413   }
    414   case Type::Pointer: {
    415     const PointerType *PTy = cast<PointerType>(Ty);
    416     QualType ETy = PTy->getPointeeType();
    417     llvm::Type *PointeeType = ConvertTypeForMem(ETy);
    418     if (PointeeType->isVoidTy())
    419       PointeeType = llvm::Type::getInt8Ty(getLLVMContext());
    420     unsigned AS = Context.getTargetAddressSpace(ETy);
    421     ResultType = llvm::PointerType::get(PointeeType, AS);
    422     break;
    423   }
    424 
    425   case Type::VariableArray: {
    426     const VariableArrayType *A = cast<VariableArrayType>(Ty);
    427     assert(A->getIndexTypeCVRQualifiers() == 0 &&
    428            "FIXME: We only handle trivial array types so far!");
    429     // VLAs resolve to the innermost element type; this matches
    430     // the return of alloca, and there isn't any obviously better choice.
    431     ResultType = ConvertTypeForMem(A->getElementType());
    432     break;
    433   }
    434   case Type::IncompleteArray: {
    435     const IncompleteArrayType *A = cast<IncompleteArrayType>(Ty);
    436     assert(A->getIndexTypeCVRQualifiers() == 0 &&
    437            "FIXME: We only handle trivial array types so far!");
    438     // int X[] -> [0 x int], unless the element type is not sized.  If it is
    439     // unsized (e.g. an incomplete struct) just use [0 x i8].
    440     ResultType = ConvertTypeForMem(A->getElementType());
    441     if (!ResultType->isSized()) {
    442       SkippedLayout = true;
    443       ResultType = llvm::Type::getInt8Ty(getLLVMContext());
    444     }
    445     ResultType = llvm::ArrayType::get(ResultType, 0);
    446     break;
    447   }
    448   case Type::ConstantArray: {
    449     const ConstantArrayType *A = cast<ConstantArrayType>(Ty);
    450     llvm::Type *EltTy = ConvertTypeForMem(A->getElementType());
    451 
    452     // Lower arrays of undefined struct type to arrays of i8 just to have a
    453     // concrete type.
    454     if (!EltTy->isSized()) {
    455       SkippedLayout = true;
    456       EltTy = llvm::Type::getInt8Ty(getLLVMContext());
    457     }
    458 
    459     ResultType = llvm::ArrayType::get(EltTy, A->getSize().getZExtValue());
    460     break;
    461   }
    462   case Type::ExtVector:
    463   case Type::Vector: {
    464     const VectorType *VT = cast<VectorType>(Ty);
    465     ResultType = llvm::VectorType::get(ConvertType(VT->getElementType()),
    466                                        VT->getNumElements());
    467     break;
    468   }
    469   case Type::FunctionNoProto:
    470   case Type::FunctionProto: {
    471     const FunctionType *FT = cast<FunctionType>(Ty);
    472     // First, check whether we can build the full function type.  If the
    473     // function type depends on an incomplete type (e.g. a struct or enum), we
    474     // cannot lower the function type.
    475     if (!isFuncTypeConvertible(FT)) {
    476       // This function's type depends on an incomplete tag type.
    477 
    478       // Force conversion of all the relevant record types, to make sure
    479       // we re-convert the FunctionType when appropriate.
    480       if (const RecordType *RT = FT->getReturnType()->getAs<RecordType>())
    481         ConvertRecordDeclType(RT->getDecl());
    482       if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT))
    483         for (unsigned i = 0, e = FPT->getNumParams(); i != e; i++)
    484           if (const RecordType *RT = FPT->getParamType(i)->getAs<RecordType>())
    485             ConvertRecordDeclType(RT->getDecl());
    486 
    487       // Return a placeholder type.
    488       ResultType = llvm::StructType::get(getLLVMContext());
    489 
    490       SkippedLayout = true;
    491       break;
    492     }
    493 
    494     // While we're converting the parameter types for a function, we don't want
    495     // to recursively convert any pointed-to structs.  Converting directly-used
    496     // structs is ok though.
    497     if (!RecordsBeingLaidOut.insert(Ty)) {
    498       ResultType = llvm::StructType::get(getLLVMContext());
    499 
    500       SkippedLayout = true;
    501       break;
    502     }
    503 
    504     // The function type can be built; call the appropriate routines to
    505     // build it.
    506     const CGFunctionInfo *FI;
    507     if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
    508       FI = &arrangeFreeFunctionType(
    509                    CanQual<FunctionProtoType>::CreateUnsafe(QualType(FPT, 0)));
    510     } else {
    511       const FunctionNoProtoType *FNPT = cast<FunctionNoProtoType>(FT);
    512       FI = &arrangeFreeFunctionType(
    513                 CanQual<FunctionNoProtoType>::CreateUnsafe(QualType(FNPT, 0)));
    514     }
    515 
    516     // If there is something higher level prodding our CGFunctionInfo, then
    517     // don't recurse into it again.
    518     if (FunctionsBeingProcessed.count(FI)) {
    519 
    520       ResultType = llvm::StructType::get(getLLVMContext());
    521       SkippedLayout = true;
    522     } else {
    523 
    524       // Otherwise, we're good to go, go ahead and convert it.
    525       ResultType = GetFunctionType(*FI);
    526     }
    527 
    528     RecordsBeingLaidOut.erase(Ty);
    529 
    530     if (SkippedLayout)
    531       TypeCache.clear();
    532 
    533     if (RecordsBeingLaidOut.empty())
    534       while (!DeferredRecords.empty())
    535         ConvertRecordDeclType(DeferredRecords.pop_back_val());
    536     break;
    537   }
    538 
    539   case Type::ObjCObject:
    540     ResultType = ConvertType(cast<ObjCObjectType>(Ty)->getBaseType());
    541     break;
    542 
    543   case Type::ObjCInterface: {
    544     // Objective-C interfaces are always opaque (outside of the
    545     // runtime, which can do whatever it likes); we never refine
    546     // these.
    547     llvm::Type *&T = InterfaceTypes[cast<ObjCInterfaceType>(Ty)];
    548     if (!T)
    549       T = llvm::StructType::create(getLLVMContext());
    550     ResultType = T;
    551     break;
    552   }
    553 
    554   case Type::ObjCObjectPointer: {
    555     // Protocol qualifications do not influence the LLVM type, we just return a
    556     // pointer to the underlying interface type. We don't need to worry about
    557     // recursive conversion.
    558     llvm::Type *T =
    559       ConvertTypeForMem(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
    560     ResultType = T->getPointerTo();
    561     break;
    562   }
    563 
    564   case Type::Enum: {
    565     const EnumDecl *ED = cast<EnumType>(Ty)->getDecl();
    566     if (ED->isCompleteDefinition() || ED->isFixed())
    567       return ConvertType(ED->getIntegerType());
    568     // Return a placeholder 'i32' type.  This can be changed later when the
    569     // type is defined (see UpdateCompletedType), but is likely to be the
    570     // "right" answer.
    571     ResultType = llvm::Type::getInt32Ty(getLLVMContext());
    572     break;
    573   }
    574 
    575   case Type::BlockPointer: {
    576     const QualType FTy = cast<BlockPointerType>(Ty)->getPointeeType();
    577     llvm::Type *PointeeType = ConvertTypeForMem(FTy);
    578     unsigned AS = Context.getTargetAddressSpace(FTy);
    579     ResultType = llvm::PointerType::get(PointeeType, AS);
    580     break;
    581   }
    582 
    583   case Type::MemberPointer: {
    584     ResultType =
    585       getCXXABI().ConvertMemberPointerType(cast<MemberPointerType>(Ty));
    586     break;
    587   }
    588 
    589   case Type::Atomic: {
    590     QualType valueType = cast<AtomicType>(Ty)->getValueType();
    591     ResultType = ConvertTypeForMem(valueType);
    592 
    593     // Pad out to the inflated size if necessary.
    594     uint64_t valueSize = Context.getTypeSize(valueType);
    595     uint64_t atomicSize = Context.getTypeSize(Ty);
    596     if (valueSize != atomicSize) {
    597       assert(valueSize < atomicSize);
    598       llvm::Type *elts[] = {
    599         ResultType,
    600         llvm::ArrayType::get(CGM.Int8Ty, (atomicSize - valueSize) / 8)
    601       };
    602       ResultType = llvm::StructType::get(getLLVMContext(),
    603                                          llvm::makeArrayRef(elts));
    604     }
    605     break;
    606   }
    607   }
    608 
    609   assert(ResultType && "Didn't convert a type?");
    610 
    611   TypeCache[Ty] = ResultType;
    612   return ResultType;
    613 }
    614 
    615 bool CodeGenModule::isPaddedAtomicType(QualType type) {
    616   return isPaddedAtomicType(type->castAs<AtomicType>());
    617 }
    618 
    619 bool CodeGenModule::isPaddedAtomicType(const AtomicType *type) {
    620   return Context.getTypeSize(type) != Context.getTypeSize(type->getValueType());
    621 }
    622 
    623 /// ConvertRecordDeclType - Lay out a tagged decl type like struct or union.
    624 llvm::StructType *CodeGenTypes::ConvertRecordDeclType(const RecordDecl *RD) {
    625   // TagDecl's are not necessarily unique, instead use the (clang)
    626   // type connected to the decl.
    627   const Type *Key = Context.getTagDeclType(RD).getTypePtr();
    628 
    629   llvm::StructType *&Entry = RecordDeclTypes[Key];
    630 
    631   // If we don't have a StructType at all yet, create the forward declaration.
    632   if (!Entry) {
    633     Entry = llvm::StructType::create(getLLVMContext());
    634     addRecordTypeName(RD, Entry, "");
    635   }
    636   llvm::StructType *Ty = Entry;
    637 
    638   // If this is still a forward declaration, or the LLVM type is already
    639   // complete, there's nothing more to do.
    640   RD = RD->getDefinition();
    641   if (!RD || !RD->isCompleteDefinition() || !Ty->isOpaque())
    642     return Ty;
    643 
    644   // If converting this type would cause us to infinitely loop, don't do it!
    645   if (!isSafeToConvert(RD, *this)) {
    646     DeferredRecords.push_back(RD);
    647     return Ty;
    648   }
    649 
    650   // Okay, this is a definition of a type.  Compile the implementation now.
    651   bool InsertResult = RecordsBeingLaidOut.insert(Key); (void)InsertResult;
    652   assert(InsertResult && "Recursively compiling a struct?");
    653 
    654   // Force conversion of non-virtual base classes recursively.
    655   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
    656     for (const auto &I : CRD->bases()) {
    657       if (I.isVirtual()) continue;
    658 
    659       ConvertRecordDeclType(I.getType()->getAs<RecordType>()->getDecl());
    660     }
    661   }
    662 
    663   // Layout fields.
    664   CGRecordLayout *Layout = ComputeRecordLayout(RD, Ty);
    665   CGRecordLayouts[Key] = Layout;
    666 
    667   // We're done laying out this struct.
    668   bool EraseResult = RecordsBeingLaidOut.erase(Key); (void)EraseResult;
    669   assert(EraseResult && "struct not in RecordsBeingLaidOut set?");
    670 
    671   // If this struct blocked a FunctionType conversion, then recompute whatever
    672   // was derived from that.
    673   // FIXME: This is hugely overconservative.
    674   if (SkippedLayout)
    675     TypeCache.clear();
    676 
    677   // If we're done converting the outer-most record, then convert any deferred
    678   // structs as well.
    679   if (RecordsBeingLaidOut.empty())
    680     while (!DeferredRecords.empty())
    681       ConvertRecordDeclType(DeferredRecords.pop_back_val());
    682 
    683   return Ty;
    684 }
    685 
    686 /// getCGRecordLayout - Return record layout info for the given record decl.
    687 const CGRecordLayout &
    688 CodeGenTypes::getCGRecordLayout(const RecordDecl *RD) {
    689   const Type *Key = Context.getTagDeclType(RD).getTypePtr();
    690 
    691   const CGRecordLayout *Layout = CGRecordLayouts.lookup(Key);
    692   if (!Layout) {
    693     // Compute the type information.
    694     ConvertRecordDeclType(RD);
    695 
    696     // Now try again.
    697     Layout = CGRecordLayouts.lookup(Key);
    698   }
    699 
    700   assert(Layout && "Unable to find record layout information for type");
    701   return *Layout;
    702 }
    703 
    704 bool CodeGenTypes::isZeroInitializable(QualType T) {
    705   // No need to check for member pointers when not compiling C++.
    706   if (!Context.getLangOpts().CPlusPlus)
    707     return true;
    708 
    709   T = Context.getBaseElementType(T);
    710 
    711   // Records are non-zero-initializable if they contain any
    712   // non-zero-initializable subobjects.
    713   if (const RecordType *RT = T->getAs<RecordType>()) {
    714     const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
    715     return isZeroInitializable(RD);
    716   }
    717 
    718   // We have to ask the ABI about member pointers.
    719   if (const MemberPointerType *MPT = T->getAs<MemberPointerType>())
    720     return getCXXABI().isZeroInitializable(MPT);
    721 
    722   // Everything else is okay.
    723   return true;
    724 }
    725 
    726 bool CodeGenTypes::isZeroInitializable(const CXXRecordDecl *RD) {
    727   return getCGRecordLayout(RD).isZeroInitializable();
    728 }
    729