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"
25 using namespace clang;
26 using namespace CodeGen;
27 
28 CodeGenTypes::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 
34 CodeGenTypes::~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.
46 const 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 
66 const 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 
83 const 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.
96 const 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.
111 const TagType *CodeGenTypes::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.
126 void 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 
167 static 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 
183 const 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::ObjCObject:
326     return ConvertTypeRecursive(cast<ObjCObjectType>(Ty).getBaseType());
327 
328   case Type::ObjCInterface: {
329     // Objective-C interfaces are always opaque (outside of the
330     // runtime, which can do whatever it likes); we never refine
331     // these.
332     const llvm::Type *&T = InterfaceTypes[cast<ObjCInterfaceType>(&Ty)];
333     if (!T)
334         T = llvm::OpaqueType::get(getLLVMContext());
335     return T;
336   }
337 
338   case Type::ObjCObjectPointer: {
339     // Protocol qualifications do not influence the LLVM type, we just return a
340     // pointer to the underlying interface type. We don't need to worry about
341     // recursive conversion.
342     const llvm::Type *T =
343       ConvertTypeRecursive(cast<ObjCObjectPointerType>(Ty).getPointeeType());
344     return llvm::PointerType::getUnqual(T);
345   }
346 
347   case Type::Record:
348   case Type::Enum: {
349     const TagDecl *TD = cast<TagType>(Ty).getDecl();
350     const llvm::Type *Res = ConvertTagDeclType(TD);
351 
352     std::string TypeName(TD->getKindName());
353     TypeName += '.';
354 
355     // Name the codegen type after the typedef name
356     // if there is no tag type name available
357     if (TD->getIdentifier())
358       // FIXME: We should not have to check for a null decl context here.
359       // Right now we do it because the implicit Obj-C decls don't have one.
360       TypeName += TD->getDeclContext() ? TD->getQualifiedNameAsString() :
361         TD->getNameAsString();
362     else if (const TypedefType *TdT = dyn_cast<TypedefType>(T))
363       // FIXME: We should not have to check for a null decl context here.
364       // Right now we do it because the implicit Obj-C decls don't have one.
365       TypeName += TdT->getDecl()->getDeclContext() ?
366         TdT->getDecl()->getQualifiedNameAsString() :
367         TdT->getDecl()->getNameAsString();
368     else
369       TypeName += "anon";
370 
371     TheModule.addTypeName(TypeName, Res);
372     return Res;
373   }
374 
375   case Type::BlockPointer: {
376     const QualType FTy = cast<BlockPointerType>(Ty).getPointeeType();
377     llvm::OpaqueType *PointeeType = llvm::OpaqueType::get(getLLVMContext());
378     PointersToResolve.push_back(std::make_pair(FTy, PointeeType));
379     return llvm::PointerType::get(PointeeType, FTy.getAddressSpace());
380   }
381 
382   case Type::MemberPointer: {
383     // FIXME: This is ABI dependent. We use the Itanium C++ ABI.
384     // http://www.codesourcery.com/public/cxx-abi/abi.html#member-pointers
385     // If we ever want to support other ABIs this needs to be abstracted.
386 
387     QualType ETy = cast<MemberPointerType>(Ty).getPointeeType();
388     const llvm::Type *PtrDiffTy =
389         ConvertTypeRecursive(Context.getPointerDiffType());
390     if (ETy->isFunctionType())
391       return llvm::StructType::get(TheModule.getContext(), PtrDiffTy, PtrDiffTy,
392                                    NULL);
393     return PtrDiffTy;
394   }
395   }
396 
397   // FIXME: implement.
398   return llvm::OpaqueType::get(getLLVMContext());
399 }
400 
401 /// ConvertTagDeclType - Lay out a tagged decl type like struct or union or
402 /// enum.
403 const llvm::Type *CodeGenTypes::ConvertTagDeclType(const TagDecl *TD) {
404   // TagDecl's are not necessarily unique, instead use the (clang)
405   // type connected to the decl.
406   const Type *Key =
407     Context.getTagDeclType(TD).getTypePtr();
408   llvm::DenseMap<const Type*, llvm::PATypeHolder>::iterator TDTI =
409     TagDeclTypes.find(Key);
410 
411   // If we've already compiled this tag type, use the previous definition.
412   if (TDTI != TagDeclTypes.end())
413     return TDTI->second;
414 
415   // If this is still a forward declaration, just define an opaque
416   // type to use for this tagged decl.
417   if (!TD->isDefinition()) {
418     llvm::Type *ResultType = llvm::OpaqueType::get(getLLVMContext());
419     TagDeclTypes.insert(std::make_pair(Key, ResultType));
420     return ResultType;
421   }
422 
423   // Okay, this is a definition of a type.  Compile the implementation now.
424 
425   if (TD->isEnum())  // Don't bother storing enums in TagDeclTypes.
426     return ConvertTypeRecursive(cast<EnumDecl>(TD)->getIntegerType());
427 
428   // This decl could well be recursive.  In this case, insert an opaque
429   // definition of this type, which the recursive uses will get.  We will then
430   // refine this opaque version later.
431 
432   // Create new OpaqueType now for later use in case this is a recursive
433   // type.  This will later be refined to the actual type.
434   llvm::PATypeHolder ResultHolder = llvm::OpaqueType::get(getLLVMContext());
435   TagDeclTypes.insert(std::make_pair(Key, ResultHolder));
436 
437   const RecordDecl *RD = cast<const RecordDecl>(TD);
438 
439   // Force conversion of non-virtual base classes recursively.
440   if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
441     for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
442          e = RD->bases_end(); i != e; ++i) {
443       if (!i->isVirtual()) {
444         const CXXRecordDecl *Base =
445           cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
446         ConvertTagDeclType(Base);
447       }
448     }
449   }
450 
451   // Layout fields.
452   CGRecordLayout *Layout = ComputeRecordLayout(RD);
453 
454   CGRecordLayouts[Key] = Layout;
455   const llvm::Type *ResultType = Layout->getLLVMType();
456 
457   // Refine our Opaque type to ResultType.  This can invalidate ResultType, so
458   // make sure to read the result out of the holder.
459   cast<llvm::OpaqueType>(ResultHolder.get())
460     ->refineAbstractTypeTo(ResultType);
461 
462   return ResultHolder.get();
463 }
464 
465 /// getCGRecordLayout - Return record layout info for the given llvm::Type.
466 const CGRecordLayout &
467 CodeGenTypes::getCGRecordLayout(const RecordDecl *TD) const {
468   const Type *Key = Context.getTagDeclType(TD).getTypePtr();
469   const CGRecordLayout *Layout = CGRecordLayouts.lookup(Key);
470   assert(Layout && "Unable to find record layout information for type");
471   return *Layout;
472 }
473 
474 bool CodeGenTypes::ContainsPointerToDataMember(QualType T) {
475   // No need to check for member pointers when not compiling C++.
476   if (!Context.getLangOptions().CPlusPlus)
477     return false;
478 
479   T = Context.getBaseElementType(T);
480 
481   if (const RecordType *RT = T->getAs<RecordType>()) {
482     const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
483 
484     return ContainsPointerToDataMember(RD);
485   }
486 
487   if (const MemberPointerType *MPT = T->getAs<MemberPointerType>())
488     return !MPT->getPointeeType()->isFunctionType();
489 
490   return false;
491 }
492 
493 bool CodeGenTypes::ContainsPointerToDataMember(const CXXRecordDecl *RD) {
494 
495   // FIXME: It would be better if there was a way to explicitly compute the
496   // record layout instead of converting to a type.
497   ConvertTagDeclType(RD);
498 
499   const CGRecordLayout &Layout = getCGRecordLayout(RD);
500   return Layout.containsPointerToDataMember();
501 }
502