CodeGenTypes.cpp 29 KB

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