CodeGenTypes.cpp revision 206084
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 "CGCall.h"
16#include "CGRecordLayout.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/DeclObjC.h"
19#include "clang/AST/DeclCXX.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/RecordLayout.h"
22#include "llvm/DerivedTypes.h"
23#include "llvm/Module.h"
24#include "llvm/Target/TargetData.h"
25using namespace clang;
26using namespace CodeGen;
27
28CodeGenTypes::CodeGenTypes(ASTContext &Ctx, llvm::Module& M,
29                           const llvm::TargetData &TD, const ABIInfo &Info)
30  : Context(Ctx), Target(Ctx.Target), TheModule(M), TheTargetData(TD),
31    TheABIInfo(Info) {
32}
33
34CodeGenTypes::~CodeGenTypes() {
35  for (llvm::DenseMap<const Type *, CGRecordLayout *>::iterator
36         I = CGRecordLayouts.begin(), E = CGRecordLayouts.end();
37      I != E; ++I)
38    delete I->second;
39
40  for (llvm::FoldingSet<CGFunctionInfo>::iterator
41       I = FunctionInfos.begin(), E = FunctionInfos.end(); I != E; )
42    delete &*I++;
43}
44
45/// ConvertType - Convert the specified type to its LLVM form.
46const llvm::Type *CodeGenTypes::ConvertType(QualType T) {
47  llvm::PATypeHolder Result = ConvertTypeRecursive(T);
48
49  // Any pointers that were converted defered evaluation of their pointee type,
50  // creating an opaque type instead.  This is in order to avoid problems with
51  // circular types.  Loop through all these defered pointees, if any, and
52  // resolve them now.
53  while (!PointersToResolve.empty()) {
54    std::pair<QualType, llvm::OpaqueType*> P = PointersToResolve.pop_back_val();
55
56    // We can handle bare pointers here because we know that the only pointers
57    // to the Opaque type are P.second and from other types.  Refining the
58    // opqaue type away will invalidate P.second, but we don't mind :).
59    const llvm::Type *NT = ConvertTypeForMemRecursive(P.first);
60    P.second->refineAbstractTypeTo(NT);
61  }
62
63  return Result;
64}
65
66const llvm::Type *CodeGenTypes::ConvertTypeRecursive(QualType T) {
67  T = Context.getCanonicalType(T);
68
69  // See if type is already cached.
70  llvm::DenseMap<Type *, llvm::PATypeHolder>::iterator
71    I = TypeCache.find(T.getTypePtr());
72  // If type is found in map and this is not a definition for a opaque
73  // place holder type then use it. Otherwise, convert type T.
74  if (I != TypeCache.end())
75    return I->second.get();
76
77  const llvm::Type *ResultType = ConvertNewType(T);
78  TypeCache.insert(std::make_pair(T.getTypePtr(),
79                                  llvm::PATypeHolder(ResultType)));
80  return ResultType;
81}
82
83const llvm::Type *CodeGenTypes::ConvertTypeForMemRecursive(QualType T) {
84  const llvm::Type *ResultType = ConvertTypeRecursive(T);
85  if (ResultType->isIntegerTy(1))
86    return llvm::IntegerType::get(getLLVMContext(),
87                                  (unsigned)Context.getTypeSize(T));
88  // FIXME: Should assert that the llvm type and AST type has the same size.
89  return ResultType;
90}
91
92/// ConvertTypeForMem - Convert type T into a llvm::Type.  This differs from
93/// ConvertType in that it is used to convert to the memory representation for
94/// a type.  For example, the scalar representation for _Bool is i1, but the
95/// memory representation is usually i8 or i32, depending on the target.
96const llvm::Type *CodeGenTypes::ConvertTypeForMem(QualType T) {
97  const llvm::Type *R = ConvertType(T);
98
99  // If this is a non-bool type, don't map it.
100  if (!R->isIntegerTy(1))
101    return R;
102
103  // Otherwise, return an integer of the target-specified size.
104  return llvm::IntegerType::get(getLLVMContext(),
105                                (unsigned)Context.getTypeSize(T));
106
107}
108
109// Code to verify a given function type is complete, i.e. the return type
110// and all of the argument types are complete.
111static const TagType *VerifyFuncTypeComplete(const Type* T) {
112  const FunctionType *FT = cast<FunctionType>(T);
113  if (const TagType* TT = FT->getResultType()->getAs<TagType>())
114    if (!TT->getDecl()->isDefinition())
115      return TT;
116  if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(T))
117    for (unsigned i = 0; i < FPT->getNumArgs(); i++)
118      if (const TagType* TT = FPT->getArgType(i)->getAs<TagType>())
119        if (!TT->getDecl()->isDefinition())
120          return TT;
121  return 0;
122}
123
124/// UpdateCompletedType - When we find the full definition for a TagDecl,
125/// replace the 'opaque' type we previously made for it if applicable.
126void CodeGenTypes::UpdateCompletedType(const TagDecl *TD) {
127  const Type *Key = Context.getTagDeclType(TD).getTypePtr();
128  llvm::DenseMap<const Type*, llvm::PATypeHolder>::iterator TDTI =
129    TagDeclTypes.find(Key);
130  if (TDTI == TagDeclTypes.end()) return;
131
132  // Remember the opaque LLVM type for this tagdecl.
133  llvm::PATypeHolder OpaqueHolder = TDTI->second;
134  assert(isa<llvm::OpaqueType>(OpaqueHolder.get()) &&
135         "Updating compilation of an already non-opaque type?");
136
137  // Remove it from TagDeclTypes so that it will be regenerated.
138  TagDeclTypes.erase(TDTI);
139
140  // Generate the new type.
141  const llvm::Type *NT = ConvertTagDeclType(TD);
142
143  // Refine the old opaque type to its new definition.
144  cast<llvm::OpaqueType>(OpaqueHolder.get())->refineAbstractTypeTo(NT);
145
146  // Since we just completed a tag type, check to see if any function types
147  // were completed along with the tag type.
148  // FIXME: This is very inefficient; if we track which function types depend
149  // on which tag types, though, it should be reasonably efficient.
150  llvm::DenseMap<const Type*, llvm::PATypeHolder>::iterator i;
151  for (i = FunctionTypes.begin(); i != FunctionTypes.end(); ++i) {
152    if (const TagType* TT = VerifyFuncTypeComplete(i->first)) {
153      // This function type still depends on an incomplete tag type; make sure
154      // that tag type has an associated opaque type.
155      ConvertTagDeclType(TT->getDecl());
156    } else {
157      // This function no longer depends on an incomplete tag type; create the
158      // function type, and refine the opaque type to the new function type.
159      llvm::PATypeHolder OpaqueHolder = i->second;
160      const llvm::Type *NFT = ConvertNewType(QualType(i->first, 0));
161      cast<llvm::OpaqueType>(OpaqueHolder.get())->refineAbstractTypeTo(NFT);
162      FunctionTypes.erase(i);
163    }
164  }
165}
166
167static const llvm::Type* getTypeForFormat(llvm::LLVMContext &VMContext,
168                                          const llvm::fltSemantics &format) {
169  if (&format == &llvm::APFloat::IEEEsingle)
170    return llvm::Type::getFloatTy(VMContext);
171  if (&format == &llvm::APFloat::IEEEdouble)
172    return llvm::Type::getDoubleTy(VMContext);
173  if (&format == &llvm::APFloat::IEEEquad)
174    return llvm::Type::getFP128Ty(VMContext);
175  if (&format == &llvm::APFloat::PPCDoubleDouble)
176    return llvm::Type::getPPC_FP128Ty(VMContext);
177  if (&format == &llvm::APFloat::x87DoubleExtended)
178    return llvm::Type::getX86_FP80Ty(VMContext);
179  assert(0 && "Unknown float format!");
180  return 0;
181}
182
183const llvm::Type *CodeGenTypes::ConvertNewType(QualType T) {
184  const clang::Type &Ty = *Context.getCanonicalType(T).getTypePtr();
185
186  switch (Ty.getTypeClass()) {
187#define TYPE(Class, Base)
188#define ABSTRACT_TYPE(Class, Base)
189#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
190#define DEPENDENT_TYPE(Class, Base) case Type::Class:
191#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
192#include "clang/AST/TypeNodes.def"
193    assert(false && "Non-canonical or dependent types aren't possible.");
194    break;
195
196  case Type::Builtin: {
197    switch (cast<BuiltinType>(Ty).getKind()) {
198    case BuiltinType::Void:
199    case BuiltinType::ObjCId:
200    case BuiltinType::ObjCClass:
201    case BuiltinType::ObjCSel:
202      // LLVM void type can only be used as the result of a function call.  Just
203      // map to the same as char.
204      return llvm::IntegerType::get(getLLVMContext(), 8);
205
206    case BuiltinType::Bool:
207      // Note that we always return bool as i1 for use as a scalar type.
208      return llvm::Type::getInt1Ty(getLLVMContext());
209
210    case BuiltinType::Char_S:
211    case BuiltinType::Char_U:
212    case BuiltinType::SChar:
213    case BuiltinType::UChar:
214    case BuiltinType::Short:
215    case BuiltinType::UShort:
216    case BuiltinType::Int:
217    case BuiltinType::UInt:
218    case BuiltinType::Long:
219    case BuiltinType::ULong:
220    case BuiltinType::LongLong:
221    case BuiltinType::ULongLong:
222    case BuiltinType::WChar:
223    case BuiltinType::Char16:
224    case BuiltinType::Char32:
225      return llvm::IntegerType::get(getLLVMContext(),
226        static_cast<unsigned>(Context.getTypeSize(T)));
227
228    case BuiltinType::Float:
229    case BuiltinType::Double:
230    case BuiltinType::LongDouble:
231      return getTypeForFormat(getLLVMContext(),
232                              Context.getFloatTypeSemantics(T));
233
234    case BuiltinType::NullPtr: {
235      // Model std::nullptr_t as i8*
236      const llvm::Type *Ty = llvm::IntegerType::get(getLLVMContext(), 8);
237      return llvm::PointerType::getUnqual(Ty);
238    }
239
240    case BuiltinType::UInt128:
241    case BuiltinType::Int128:
242      return llvm::IntegerType::get(getLLVMContext(), 128);
243
244    case BuiltinType::Overload:
245    case BuiltinType::Dependent:
246    case BuiltinType::UndeducedAuto:
247      assert(0 && "Unexpected builtin type!");
248      break;
249    }
250    assert(0 && "Unknown builtin type!");
251    break;
252  }
253  case Type::Complex: {
254    const llvm::Type *EltTy =
255      ConvertTypeRecursive(cast<ComplexType>(Ty).getElementType());
256    return llvm::StructType::get(TheModule.getContext(), EltTy, EltTy, NULL);
257  }
258  case Type::LValueReference:
259  case Type::RValueReference: {
260    const ReferenceType &RTy = cast<ReferenceType>(Ty);
261    QualType ETy = RTy.getPointeeType();
262    llvm::OpaqueType *PointeeType = llvm::OpaqueType::get(getLLVMContext());
263    PointersToResolve.push_back(std::make_pair(ETy, PointeeType));
264    return llvm::PointerType::get(PointeeType, ETy.getAddressSpace());
265  }
266  case Type::Pointer: {
267    const PointerType &PTy = cast<PointerType>(Ty);
268    QualType ETy = PTy.getPointeeType();
269    llvm::OpaqueType *PointeeType = llvm::OpaqueType::get(getLLVMContext());
270    PointersToResolve.push_back(std::make_pair(ETy, PointeeType));
271    return llvm::PointerType::get(PointeeType, ETy.getAddressSpace());
272  }
273
274  case Type::VariableArray: {
275    const VariableArrayType &A = cast<VariableArrayType>(Ty);
276    assert(A.getIndexTypeCVRQualifiers() == 0 &&
277           "FIXME: We only handle trivial array types so far!");
278    // VLAs resolve to the innermost element type; this matches
279    // the return of alloca, and there isn't any obviously better choice.
280    return ConvertTypeForMemRecursive(A.getElementType());
281  }
282  case Type::IncompleteArray: {
283    const IncompleteArrayType &A = cast<IncompleteArrayType>(Ty);
284    assert(A.getIndexTypeCVRQualifiers() == 0 &&
285           "FIXME: We only handle trivial array types so far!");
286    // int X[] -> [0 x int]
287    return llvm::ArrayType::get(ConvertTypeForMemRecursive(A.getElementType()), 0);
288  }
289  case Type::ConstantArray: {
290    const ConstantArrayType &A = cast<ConstantArrayType>(Ty);
291    const llvm::Type *EltTy = ConvertTypeForMemRecursive(A.getElementType());
292    return llvm::ArrayType::get(EltTy, A.getSize().getZExtValue());
293  }
294  case Type::ExtVector:
295  case Type::Vector: {
296    const VectorType &VT = cast<VectorType>(Ty);
297    return llvm::VectorType::get(ConvertTypeRecursive(VT.getElementType()),
298                                 VT.getNumElements());
299  }
300  case Type::FunctionNoProto:
301  case Type::FunctionProto: {
302    // First, check whether we can build the full function type.
303    if (const TagType* TT = VerifyFuncTypeComplete(&Ty)) {
304      // This function's type depends on an incomplete tag type; make sure
305      // we have an opaque type corresponding to the tag type.
306      ConvertTagDeclType(TT->getDecl());
307      // Create an opaque type for this function type, save it, and return it.
308      llvm::Type *ResultType = llvm::OpaqueType::get(getLLVMContext());
309      FunctionTypes.insert(std::make_pair(&Ty, ResultType));
310      return ResultType;
311    }
312    // The function type can be built; call the appropriate routines to
313    // build it.
314    if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(&Ty))
315      return GetFunctionType(getFunctionInfo(
316                CanQual<FunctionProtoType>::CreateUnsafe(QualType(FPT,0))),
317                             FPT->isVariadic());
318
319    const FunctionNoProtoType *FNPT = cast<FunctionNoProtoType>(&Ty);
320    return GetFunctionType(getFunctionInfo(
321                CanQual<FunctionNoProtoType>::CreateUnsafe(QualType(FNPT,0))),
322                           true);
323  }
324
325  case Type::ObjCInterface: {
326    // Objective-C interfaces are always opaque (outside of the
327    // runtime, which can do whatever it likes); we never refine
328    // these.
329    const llvm::Type *&T = InterfaceTypes[cast<ObjCInterfaceType>(&Ty)];
330    if (!T)
331        T = llvm::OpaqueType::get(getLLVMContext());
332    return T;
333  }
334
335  case Type::ObjCObjectPointer: {
336    // Protocol qualifications do not influence the LLVM type, we just return a
337    // pointer to the underlying interface type. We don't need to worry about
338    // recursive conversion.
339    const llvm::Type *T =
340      ConvertTypeRecursive(cast<ObjCObjectPointerType>(Ty).getPointeeType());
341    return llvm::PointerType::getUnqual(T);
342  }
343
344  case Type::Record:
345  case Type::Enum: {
346    const TagDecl *TD = cast<TagType>(Ty).getDecl();
347    const llvm::Type *Res = ConvertTagDeclType(TD);
348
349    std::string TypeName(TD->getKindName());
350    TypeName += '.';
351
352    // Name the codegen type after the typedef name
353    // if there is no tag type name available
354    if (TD->getIdentifier())
355      // FIXME: We should not have to check for a null decl context here.
356      // Right now we do it because the implicit Obj-C decls don't have one.
357      TypeName += TD->getDeclContext() ? TD->getQualifiedNameAsString() :
358        TD->getNameAsString();
359    else if (const TypedefType *TdT = dyn_cast<TypedefType>(T))
360      // FIXME: We should not have to check for a null decl context here.
361      // Right now we do it because the implicit Obj-C decls don't have one.
362      TypeName += TdT->getDecl()->getDeclContext() ?
363        TdT->getDecl()->getQualifiedNameAsString() :
364        TdT->getDecl()->getNameAsString();
365    else
366      TypeName += "anon";
367
368    TheModule.addTypeName(TypeName, Res);
369    return Res;
370  }
371
372  case Type::BlockPointer: {
373    const QualType FTy = cast<BlockPointerType>(Ty).getPointeeType();
374    llvm::OpaqueType *PointeeType = llvm::OpaqueType::get(getLLVMContext());
375    PointersToResolve.push_back(std::make_pair(FTy, PointeeType));
376    return llvm::PointerType::get(PointeeType, FTy.getAddressSpace());
377  }
378
379  case Type::MemberPointer: {
380    // FIXME: This is ABI dependent. We use the Itanium C++ ABI.
381    // http://www.codesourcery.com/public/cxx-abi/abi.html#member-pointers
382    // If we ever want to support other ABIs this needs to be abstracted.
383
384    QualType ETy = cast<MemberPointerType>(Ty).getPointeeType();
385    const llvm::Type *PtrDiffTy =
386        ConvertTypeRecursive(Context.getPointerDiffType());
387    if (ETy->isFunctionType())
388      return llvm::StructType::get(TheModule.getContext(), PtrDiffTy, PtrDiffTy,
389                                   NULL);
390    return PtrDiffTy;
391  }
392  }
393
394  // FIXME: implement.
395  return llvm::OpaqueType::get(getLLVMContext());
396}
397
398/// ConvertTagDeclType - Lay out a tagged decl type like struct or union or
399/// enum.
400const llvm::Type *CodeGenTypes::ConvertTagDeclType(const TagDecl *TD) {
401  // TagDecl's are not necessarily unique, instead use the (clang)
402  // type connected to the decl.
403  const Type *Key =
404    Context.getTagDeclType(TD).getTypePtr();
405  llvm::DenseMap<const Type*, llvm::PATypeHolder>::iterator TDTI =
406    TagDeclTypes.find(Key);
407
408  // If we've already compiled this tag type, use the previous definition.
409  if (TDTI != TagDeclTypes.end())
410    return TDTI->second;
411
412  // If this is still a forward declaration, just define an opaque
413  // type to use for this tagged decl.
414  if (!TD->isDefinition()) {
415    llvm::Type *ResultType = llvm::OpaqueType::get(getLLVMContext());
416    TagDeclTypes.insert(std::make_pair(Key, ResultType));
417    return ResultType;
418  }
419
420  // Okay, this is a definition of a type.  Compile the implementation now.
421
422  if (TD->isEnum())  // Don't bother storing enums in TagDeclTypes.
423    return ConvertTypeRecursive(cast<EnumDecl>(TD)->getIntegerType());
424
425  // This decl could well be recursive.  In this case, insert an opaque
426  // definition of this type, which the recursive uses will get.  We will then
427  // refine this opaque version later.
428
429  // Create new OpaqueType now for later use in case this is a recursive
430  // type.  This will later be refined to the actual type.
431  llvm::PATypeHolder ResultHolder = llvm::OpaqueType::get(getLLVMContext());
432  TagDeclTypes.insert(std::make_pair(Key, ResultHolder));
433
434  const RecordDecl *RD = cast<const RecordDecl>(TD);
435
436  // Force conversion of non-virtual base classes recursively.
437  if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
438    for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
439         e = RD->bases_end(); i != e; ++i) {
440      if (!i->isVirtual()) {
441        const CXXRecordDecl *Base =
442          cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
443        ConvertTagDeclType(Base);
444      }
445    }
446  }
447
448  // Layout fields.
449  CGRecordLayout *Layout = ComputeRecordLayout(RD);
450
451  CGRecordLayouts[Key] = Layout;
452  const llvm::Type *ResultType = Layout->getLLVMType();
453
454  // Refine our Opaque type to ResultType.  This can invalidate ResultType, so
455  // make sure to read the result out of the holder.
456  cast<llvm::OpaqueType>(ResultHolder.get())
457    ->refineAbstractTypeTo(ResultType);
458
459  return ResultHolder.get();
460}
461
462/// getCGRecordLayout - Return record layout info for the given llvm::Type.
463const CGRecordLayout &
464CodeGenTypes::getCGRecordLayout(const RecordDecl *TD) const {
465  const Type *Key = Context.getTagDeclType(TD).getTypePtr();
466  const CGRecordLayout *Layout = CGRecordLayouts.lookup(Key);
467  assert(Layout && "Unable to find record layout information for type");
468  return *Layout;
469}
470