CodeGenTypes.cpp 26 KB

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