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