CodeGenTypes.cpp 19 KB

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