CodeGenTypes.cpp 19 KB

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