clang 24.0.0git
QualTypeMapper.cpp
Go to the documentation of this file.
1//==---- QualTypeMapper.cpp - Maps Clang QualType to LLVMABI Types ---------==//
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/// \file
10/// Maps Clang QualType instances to corresponding LLVM ABI type
11/// representations. This mapper translates high-level type information from the
12/// AST into low-level ABI-specific types that encode size, alignment, and
13/// layout details required for code generation and cross-language
14/// interoperability.
15///
16//===----------------------------------------------------------------------===//
17#include "QualTypeMapper.h"
19#include "clang/AST/ASTFwd.h"
20#include "clang/AST/Attr.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/DeclCXX.h"
24#include "clang/AST/Type.h"
26#include "clang/Basic/LLVM.h"
28#include "llvm/ABI/Types.h"
29#include "llvm/Support/Alignment.h"
30#include "llvm/Support/ErrorHandling.h"
31#include "llvm/Support/TypeSize.h"
32#include <cstdint>
33
34namespace clang {
35namespace CodeGen {
36
37/// Returns true if \p BT is one of the AArch64 SVE predicate types, i.e.
38/// svbool_t or one of its tuples.
39static bool isSVEPredicateBuiltinType(const BuiltinType *BT) {
40 switch (BT->getKind()) {
41#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId) \
42 case BuiltinType::Id: \
43 return true;
44#include "clang/Basic/AArch64ACLETypes.def"
45 default:
46 return false;
47 }
48}
49
50/// Maps a Clang vector kind onto the ABI library's notion of a vector flavor.
51static llvm::abi::VectorKind getABIVectorKind(clang::VectorKind Kind) {
52 switch (Kind) {
54 return llvm::abi::VectorKind::SVEData;
56 return llvm::abi::VectorKind::SVEPredicate;
57 default:
58 return llvm::abi::VectorKind::Generic;
59 }
60}
61
62/// Main entry point for converting Clang QualType to LLVM ABI Type.
63/// This method performs type canonicalization, caching, and dispatches
64/// to specialized conversion methods based on the type kind.
65///
66/// \param QT The Clang QualType to convert
67/// \return Corresponding LLVM ABI Type representation
68const llvm::abi::Type *QualTypeMapper::convertType(QualType QT) {
69 // Canonicalize type and strip qualifiers
70 // This ensures consistent type representation across different contexts
71 //
72 // TODO: AttributedType is NeverCanonical, so aligned typedef attributes
73 // for instance, __attribute__((aligned(N))) are lost here. Capture the
74 // effective alignment from the original QT and thread it through
75 // convertTypeImpl.
77
78 // Results are cached since type conversion may be expensive.
79 auto It = TypeCache.find(QT);
80 if (It != TypeCache.end())
81 return It->second;
82
83 const llvm::abi::Type *Result = convertTypeImpl(QT);
84 assert(Result && "convertTypeImpl returned nullptr");
85 TypeCache[QT] = Result;
86 return Result;
87}
88
89/// Dispatches to specialized conversion methods based on the type kind.
90const llvm::abi::Type *QualTypeMapper::convertTypeImpl(QualType QT) {
91 switch (QT->getTypeClass()) {
92 // Non-canonical and dependent types should have been stripped by
93 // getCanonicalType() above or cannot appear during code generation.
94#define TYPE(Class, Base)
95#define ABSTRACT_TYPE(Class, Base)
96#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
97#define DEPENDENT_TYPE(Class, Base) case Type::Class:
98#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
99#include "clang/AST/TypeNodes.inc"
100 llvm::reportFatalInternalError(
101 "Non-canonical or dependent types should not reach ABI lowering");
102
103 case Type::Builtin:
104 return convertBuiltinType(cast<BuiltinType>(QT));
105 case Type::Pointer:
106 return createPointerTypeForPointee(cast<PointerType>(QT)->getPointeeType());
107 case Type::LValueReference:
108 case Type::RValueReference:
109 return createPointerTypeForPointee(
111 case Type::ConstantArray:
112 case Type::ArrayParameter:
113 case Type::IncompleteArray:
114 case Type::VariableArray:
115 return convertArrayType(cast<ArrayType>(QT));
116 case Type::Vector:
117 case Type::ExtVector:
118 return convertVectorType(cast<VectorType>(QT));
119 case Type::Record:
120 return convertRecordType(cast<RecordType>(QT));
121 case Type::Enum:
122 return convertEnumType(cast<EnumType>(QT));
123 case Type::Complex:
124 return convertComplexType(cast<ComplexType>(QT));
125 case Type::Atomic: {
126 const auto *AT = cast<AtomicType>(QT);
127 return Builder.getAtomicType(convertType(AT->getValueType()),
128 ASTCtx.getTypeSize(QT), getTypeAlign(QT));
129 }
130 case Type::BlockPointer:
131 case Type::Pipe:
132 return createPointerTypeForPointee(ASTCtx.VoidPtrTy);
133 case Type::ConstantMatrix: {
134 const auto *MT = cast<ConstantMatrixType>(QT);
135 return Builder.getArrayType(convertType(MT->getElementType()),
136 MT->getNumRows() * MT->getNumColumns(),
137 ASTCtx.getTypeSize(QT), /*IsMatrixType=*/true);
138 }
139 case Type::MemberPointer:
140 return convertMemberPointerType(cast<MemberPointerType>(QT));
141 case Type::BitInt: {
142 const auto *BIT = cast<BitIntType>(QT);
143 return Builder.getIntegerType(BIT->getNumBits(), getTypeAlign(QT),
144 /*Signed=*/BIT->isSigned(),
145 /*IsBitInt=*/true);
146 }
147 case Type::ObjCObject:
148 case Type::ObjCInterface:
149 case Type::ObjCObjectPointer:
150 // Objective-C objects are represented as pointers in the ABI.
151 return Builder.getPointerType(
152 ASTCtx.getTargetInfo().getPointerWidth(QT.getAddressSpace()),
153 llvm::Align(
154 ASTCtx.getTargetInfo().getPointerAlign(QT.getAddressSpace()) / 8),
155 ASTCtx.getTargetInfo().getTargetAddressSpace(QT.getAddressSpace()),
156 QT.hasAddressSpace());
157 case Type::OverflowBehavior:
159 case Type::Auto:
160 case Type::DeducedTemplateSpecialization:
161 case Type::FunctionProto:
162 case Type::FunctionNoProto:
163 case Type::HLSLAttributedResource:
164 case Type::HLSLInlineSpirv:
165 llvm::reportFatalInternalError("Type not supported in ABI lowering");
166 }
167 llvm_unreachable("unhandled type class in convertTypeImpl");
168}
169
170/// Converts C/C++ builtin types to LLVM ABI types.
171/// This handles all fundamental scalar types including integers, floats,
172/// and special types like void and bool.
173const llvm::abi::Type *
174QualTypeMapper::convertBuiltinType(const BuiltinType *BT) {
175 QualType QT(BT, 0);
176
177 switch (BT->getKind()) {
178 case BuiltinType::Void:
179 return Builder.getVoidType();
180
181 case BuiltinType::NullPtr:
182 return createPointerTypeForPointee(QT);
183
184 case BuiltinType::Bool:
185 return Builder.getIntegerType(1, getTypeAlign(QT), /*Signed=*/false,
186 /*IsBitInt=*/false);
187
188 case BuiltinType::MetaInfo:
189 llvm::reportFatalInternalError("std::meta::info is consteval-only type");
190
191 case BuiltinType::Char_S:
192 case BuiltinType::Char_U:
193 case BuiltinType::SChar:
194 case BuiltinType::UChar:
195 case BuiltinType::WChar_S:
196 case BuiltinType::WChar_U:
197 case BuiltinType::Char8:
198 case BuiltinType::Char16:
199 case BuiltinType::Char32:
200 case BuiltinType::Short:
201 case BuiltinType::UShort:
202 case BuiltinType::Int:
203 case BuiltinType::UInt:
204 case BuiltinType::Long:
205 case BuiltinType::ULong:
206 case BuiltinType::LongLong:
207 case BuiltinType::ULongLong:
208 case BuiltinType::Int128:
209 case BuiltinType::UInt128:
210 return Builder.getIntegerType(ASTCtx.getTypeSize(QT), getTypeAlign(QT),
211 /*Signed=*/BT->isSignedInteger(),
212 /*IsBitInt=*/false);
213
214 case BuiltinType::Half:
215 case BuiltinType::Float16:
216 case BuiltinType::BFloat16:
217 case BuiltinType::Float:
218 case BuiltinType::Double:
219 case BuiltinType::LongDouble:
220 case BuiltinType::Float128:
221 return Builder.getFloatType(ASTCtx.getFloatTypeSemantics(QT),
222 getTypeAlign(QT));
223
224 // TODO: IBM 128-bit extended double
225 case BuiltinType::Ibm128:
226 llvm::reportFatalInternalError(
227 "IBM128 is not yet supported in the ABI lowering libary");
228
229 // TODO: Fixed-point types
230 case BuiltinType::ShortAccum:
231 case BuiltinType::Accum:
232 case BuiltinType::LongAccum:
233 case BuiltinType::UShortAccum:
234 case BuiltinType::UAccum:
235 case BuiltinType::ULongAccum:
236 case BuiltinType::ShortFract:
237 case BuiltinType::Fract:
238 case BuiltinType::LongFract:
239 case BuiltinType::UShortFract:
240 case BuiltinType::UFract:
241 case BuiltinType::ULongFract:
242 case BuiltinType::SatShortAccum:
243 case BuiltinType::SatAccum:
244 case BuiltinType::SatLongAccum:
245 case BuiltinType::SatUShortAccum:
246 case BuiltinType::SatUAccum:
247 case BuiltinType::SatULongAccum:
248 case BuiltinType::SatShortFract:
249 case BuiltinType::SatFract:
250 case BuiltinType::SatLongFract:
251 case BuiltinType::SatUShortFract:
252 case BuiltinType::SatUFract:
253 case BuiltinType::SatULongFract:
254 llvm::reportFatalInternalError(
255 "Fixed Point types not yet implemented in the ABI lowering library");
256
257 // OpenCL image types are represented as opaque pointers.
258#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
259 case BuiltinType::Id:
260#include "clang/Basic/OpenCLImageTypes.def"
261 // OpenCL extension types are represented as opaque pointers.
262#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) case BuiltinType::Id:
263#include "clang/Basic/OpenCLExtensionTypes.def"
264 case BuiltinType::OCLSampler:
265 case BuiltinType::OCLEvent:
266 case BuiltinType::OCLClkEvent:
267 case BuiltinType::OCLQueue:
268 case BuiltinType::OCLReserveID:
269 return createPointerTypeForPointee(QT);
270
271 // Objective-C builtin types are represented as opaque pointers.
272 case BuiltinType::ObjCId:
273 case BuiltinType::ObjCClass:
274 case BuiltinType::ObjCSel:
275 return createPointerTypeForPointee(QT);
276
277 // AArch64 SVE data and predicate types, including the x2/x3/x4 tuples.
278#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId) \
279 case BuiltinType::Id:
280#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId) \
281 case BuiltinType::Id:
282#include "clang/Basic/AArch64ACLETypes.def"
283 return convertSVEBuiltinType(BT);
284
285 case BuiltinType::SveCount:
286 return Builder.getScalablePredicateOrCountVectorType(
287 getTypeAlign(QT), llvm::abi::VectorKind::SVECount);
288
289 // TODO: __mfp8 has no floating-point semantics of its own, so representing
290 // it needs a decision about how the ABI library should model opaque
291 // floating-point data. As an mfloat8 vector element it is treated as an
292 // 8-bit integer, but that is not right for the scalar type, which is passed
293 // in a floating-point register.
294 case BuiltinType::MFloat8:
295 llvm::reportFatalInternalError(
296 "__mfp8 is not yet supported in the ABI lowering library");
297
298 // Target-specific vector/matrix types — not yet implemented.
299#define PPC_VECTOR_TYPE(Name, Id, Size) case BuiltinType::Id:
300#include "clang/Basic/PPCTypes.def"
301 llvm::reportFatalInternalError(
302 "PPC MMA types not yet supported in ABI lowering library");
303#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
304#include "clang/Basic/RISCVVTypes.def"
305 llvm::reportFatalInternalError(
306 "RISC-V vector types not yet supported in ABI lowering library");
307#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
308#include "clang/Basic/WebAssemblyReferenceTypes.def"
309 llvm::reportFatalInternalError("WebAssembly reference types not yet "
310 "supported in ABI lowering library");
311#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
312#include "clang/Basic/AMDGPUTypes.def"
313 llvm::reportFatalInternalError(
314 "AMDGPU types not yet supported in ABI lowering library");
315#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
316#include "clang/Basic/HLSLIntangibleTypes.def"
317 llvm::reportFatalInternalError(
318 "HLSL intangible types not yet Supported in ABI lowering library");
319#define HLSL_PACKED_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
320#include "clang/Basic/HLSLPackedTypes.def"
321 llvm::reportFatalInternalError(
322 "HLSL packed types not yet Supported in ABI lowering library");
323#define SPIRV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
324#include "clang/Basic/SPIRVTypes.def"
325 llvm::reportFatalInternalError(
326 "SPIR-V types not yet supported in ABI lowering library");
327
328 // Placeholder types should never reach ABI lowering.
329#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
330#define BUILTIN_TYPE(Id, SingletonId)
331#include "clang/AST/BuiltinTypes.def"
332 llvm::reportFatalInternalError(
333 "Placeholder type should not reach ABI lowering");
334
335 case BuiltinType::Dependent:
336 llvm::reportFatalInternalError(
337 "Dependent builtin type should not reach ABI lowering");
338 }
339 llvm_unreachable("unhandled builtin type kind in convertBuiltinType");
340}
341
342/// Converts array types to LLVM ABI array representations.
343/// Handles different array kinds: constant arrays, incomplete arrays,
344/// and variable-length arrays.
345///
346/// \param AT The ArrayType to convert
347/// \return LLVM ABI ArrayType or PointerType
348const llvm::abi::Type *
349QualTypeMapper::convertArrayType(const clang::ArrayType *AT) {
350 const llvm::abi::Type *ElementType = convertType(AT->getElementType());
351 uint64_t Size = ASTCtx.getTypeSize(AT);
352
353 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
354 auto NumElements = CAT->getZExtSize();
355 return Builder.getArrayType(ElementType, NumElements, Size);
356 }
358 return Builder.getArrayType(ElementType, 0, 0);
359 if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
360 return createPointerTypeForPointee(VAT->getPointeeType());
361 llvm::reportFatalInternalError(
362 "unexpected array type in ABI lowering (dependent array types should be "
363 "resolved before reaching this point)");
364}
365
366const llvm::abi::Type *QualTypeMapper::convertVectorType(const VectorType *VT) {
367 const llvm::abi::Type *ElementType = convertType(VT->getElementType());
368 QualType VectorQualType(VT, 0);
369
370 unsigned NElems = VT->getNumElements();
371 llvm::ElementCount NumElements = llvm::ElementCount::getFixed(NElems);
372 llvm::Align VectorAlign = getTypeAlign(VectorQualType);
373
374 // SveFixedLengthPredicate is tagged SVEPredicate, like sizeless svbool_t.
375 // The element type is left as the AST unsigned char (i8). The builtin path
376 // below maps sizeless predicates to i1. Both match the Clang AST, but
377 // consumers that key only off VectorKind cannot assume a 1-bit element.
378 return Builder.getVectorType(ElementType, NumElements, VectorAlign,
379 getABIVectorKind(VT->getVectorKind()));
380}
381
382/// Converts the sizeless AArch64 SVE data and predicate builtin types.
383/// Single vectors become a scalable LLVM ABI VectorType. The x2/x3/x4
384/// forms become a TupleType of that vector.
385///
386/// \param BT The SVE BuiltinType to convert
387/// \return LLVM ABI VectorType or TupleType
388const llvm::abi::Type *
389QualTypeMapper::convertSVEBuiltinType(const BuiltinType *BT) {
390 ASTContext::BuiltinVectorTypeInfo Info = ASTCtx.getBuiltinVectorTypeInfo(BT);
391 assert(Info.NumVectors > 0 && Info.NumVectors <= 4 &&
392 "Expected 1, 2, 3 or 4 vectors!");
393
394 // __mfp8 carries no floating-point semantics, so mfloat8 vectors use an
395 // 8-bit integer element type, which is also how they are represented in
396 // LLVM IR.
397 const llvm::abi::Type *ElementType =
398 Info.ElementType->isMFloat8Type()
399 ? Builder.getIntegerType(8, llvm::Align(1), /*Signed=*/false)
400 : convertType(Info.ElementType);
401
402 llvm::abi::VectorKind VecKind = isSVEPredicateBuiltinType(BT)
403 ? llvm::abi::VectorKind::SVEPredicate
404 : llvm::abi::VectorKind::SVEData;
405
406 const llvm::abi::VectorType *VecTy = Builder.getVectorType(
407 ElementType, Info.EC, getTypeAlign(QualType(BT, 0)), VecKind);
408 if (Info.NumVectors == 1)
409 return VecTy;
410 return Builder.getTupleType(VecTy, Info.NumVectors);
411}
412
413/// Converts complex types to LLVM ABI complex representations.
414/// Complex types consist of two components of the element type
415/// (real and imaginary parts).
416///
417/// \param CT The ComplexType to convert
418/// \return LLVM ABI ComplexType with element type and alignment
419const llvm::abi::Type *
420QualTypeMapper::convertComplexType(const ComplexType *CT) {
421 const llvm::abi::Type *ElementType = convertType(CT->getElementType());
422 llvm::Align ComplexAlign = getTypeAlign(QualType(CT, 0));
423
424 return Builder.getComplexType(ElementType, ComplexAlign);
425}
426
427/// Converts member pointer types to LLVM ABI representations.
428/// Member pointers have different layouts depending on whether they
429/// point to functions or data members.
430///
431/// \param MPT The MemberPointerType to convert
432/// \return LLVM ABI MemberPointerType
433const llvm::abi::Type *
434QualTypeMapper::convertMemberPointerType(const clang::MemberPointerType *MPT) {
435 QualType QT(MPT, 0);
436 uint64_t Size = ASTCtx.getTypeSize(QT);
437 llvm::Align Align = getTypeAlign(QT);
438
439 bool IsFunctionPointer = MPT->isMemberFunctionPointerType();
440
441 return Builder.getMemberPointerType(IsFunctionPointer, Size, Align);
442}
443
444/// Converts record types (struct/class/union) to LLVM ABI representations.
445/// This is the main dispatch method that handles different record kinds
446/// and delegates to specialized converters.
447///
448/// \param RT The RecordType to convert
449/// \return LLVM ABI RecordType
450const llvm::abi::Type *QualTypeMapper::convertRecordType(const RecordType *RT) {
451 const RecordDecl *RD = RT->getDecl()->getDefinition();
452 if (!RD)
453 return Builder.getRecordType({}, llvm::TypeSize::getFixed(0),
454 llvm::Align(1),
455 /*UnadjustedAlign=*/llvm::Align(1));
456
457 if (RD->isUnion())
458 return convertUnionType(RD);
459
460 // Handle C++ classes with base classes
461 auto *CXXRd = dyn_cast<CXXRecordDecl>(RD);
462 if (CXXRd && (CXXRd->getNumBases() > 0 || CXXRd->getNumVBases() > 0))
463 return convertCXXRecordType(CXXRd);
464 return convertStructType(RD);
465}
466
467/// Converts C++ classes with inheritance to LLVM ABI struct representations.
468/// This method handles the complex layout of C++ objects including:
469/// - Virtual table pointers for polymorphic classes
470/// - Base class subobjects (both direct and virtual bases)
471/// - Member field layout with proper offsets
472///
473/// \param RD The C++ record declaration
474/// \return LLVM ABI RecordType representing the complete object layout
475const llvm::abi::RecordType *
476QualTypeMapper::convertCXXRecordType(const CXXRecordDecl *RD) {
477 const ASTRecordLayout &Layout = ASTCtx.getASTRecordLayout(RD);
478 SmallVector<llvm::abi::FieldInfo, 16> Fields;
479 SmallVector<llvm::abi::FieldInfo, 8> BaseClasses;
480 SmallVector<llvm::abi::FieldInfo, 8> VirtualBaseClasses;
481
482 // Add vtable pointer for polymorphic classes
483 if (RD->isPolymorphic()) {
484 const llvm::abi::Type *VtablePointer =
485 createPointerTypeForPointee(ASTCtx.VoidPtrTy);
486 Fields.emplace_back(VtablePointer, 0);
487 }
488
489 for (const auto &Base : RD->bases()) {
490 if (Base.isVirtual())
491 continue;
492
493 const RecordType *BaseRT = Base.getType()->castAs<RecordType>();
494 const llvm::abi::Type *BaseType = convertType(Base.getType());
495 uint64_t BaseOffset =
496 Layout.getBaseClassOffset(BaseRT->getAsCXXRecordDecl()).getQuantity() *
497 8;
498 BaseClasses.emplace_back(BaseType, BaseOffset);
499 }
500
501 for (const auto &VBase : RD->vbases()) {
502 const RecordType *VBaseRT = VBase.getType()->castAs<RecordType>();
503 const llvm::abi::Type *VBaseType = convertType(VBase.getType());
504 uint64_t VBaseOffset =
505 Layout.getVBaseClassOffset(VBaseRT->getAsCXXRecordDecl())
506 .getQuantity() *
507 8;
508 VirtualBaseClasses.emplace_back(VBaseType, VBaseOffset);
509 }
510
511 computeFieldInfo(RD, Fields, Layout);
512
513 llvm::sort(Fields,
514 [](const llvm::abi::FieldInfo &A, const llvm::abi::FieldInfo &B) {
515 return A.OffsetInBits < B.OffsetInBits;
516 });
517
518 llvm::TypeSize Size =
519 llvm::TypeSize::getFixed(Layout.getSize().getQuantity() * 8);
520 llvm::Align Alignment = llvm::Align(Layout.getAlignment().getQuantity());
521 llvm::Align UnadjustedAlign =
522 llvm::Align(Layout.getUnadjustedAlignment().getQuantity());
523
524 llvm::abi::RecordFlags RecFlags = llvm::abi::RecordFlags::IsCXXRecord;
525 if (RD->isPolymorphic())
526 RecFlags |= llvm::abi::RecordFlags::IsPolymorphic;
527 if (RD->canPassInRegisters())
528 RecFlags |= llvm::abi::RecordFlags::CanPassInRegisters;
529 if (RD->hasFlexibleArrayMember())
530 RecFlags |= llvm::abi::RecordFlags::HasFlexibleArrayMember;
531
532 return Builder.getRecordType(Fields, Size, Alignment, UnadjustedAlign,
533 llvm::abi::StructPacking::Default, BaseClasses,
534 VirtualBaseClasses, RecFlags);
535}
536
537/// Converts enumeration types to their underlying integer representations.
538/// This method handles various enum states and falls back to safe defaults
539/// when enum information is incomplete or invalid.
540///
541/// \param ET The EnumType to convert
542/// \return LLVM ABI IntegerType representing the enum's underlying type
543const llvm::abi::Type *
544QualTypeMapper::convertEnumType(const clang::EnumType *ET) {
545 const EnumDecl *ED = ET->getDecl();
546 QualType UnderlyingType = ED->getIntegerType();
547
548 if (UnderlyingType.isNull())
549 UnderlyingType = ASTCtx.IntTy;
550
551 return convertType(UnderlyingType);
552}
553
554/// Converts plain C structs and C++ classes without inheritance.
555/// This handles the simpler case where we only need to layout member fields
556/// without considering base classes or virtual functions.
557///
558/// \param RD The RecordDecl to convert
559/// \return LLVM ABI RecordType
560const llvm::abi::RecordType *
561QualTypeMapper::convertStructType(const clang::RecordDecl *RD) {
562 const ASTRecordLayout &Layout = ASTCtx.getASTRecordLayout(RD);
563
564 bool IsCXXRecord = isa<CXXRecordDecl>(RD);
565 SmallVector<llvm::abi::FieldInfo, 16> Fields;
566 computeFieldInfo(RD, Fields, Layout);
567
568 llvm::TypeSize Size =
569 llvm::TypeSize::getFixed(Layout.getSize().getQuantity() * 8);
570 llvm::Align Alignment = llvm::Align(Layout.getAlignment().getQuantity());
571 llvm::Align UnadjustedAlign =
572 llvm::Align(Layout.getUnadjustedAlignment().getQuantity());
573
574 llvm::abi::RecordFlags RecFlags = llvm::abi::RecordFlags::None;
575 if (IsCXXRecord)
576 RecFlags |= llvm::abi::RecordFlags::IsCXXRecord;
577 if (RD->canPassInRegisters())
578 RecFlags |= llvm::abi::RecordFlags::CanPassInRegisters;
579 if (RD->hasFlexibleArrayMember())
580 RecFlags |= llvm::abi::RecordFlags::HasFlexibleArrayMember;
581
582 return Builder.getRecordType(Fields, Size, Alignment, UnadjustedAlign,
583 llvm::abi::StructPacking::Default, {}, {},
584 RecFlags);
585}
586
587/// Converts C union types where all fields occupy the same memory location.
588/// The union size is determined by its largest member, and all fields
589/// start at offset 0.
590///
591/// \param RD The RecordDecl representing the union
592/// \return LLVM ABI UnionType
593const llvm::abi::RecordType *
594QualTypeMapper::convertUnionType(const clang::RecordDecl *RD) {
595 const ASTRecordLayout &Layout = ASTCtx.getASTRecordLayout(RD);
596
597 SmallVector<llvm::abi::FieldInfo, 16> AllFields;
598 computeFieldInfo(RD, AllFields, Layout);
599
600 llvm::TypeSize Size =
601 llvm::TypeSize::getFixed(Layout.getSize().getQuantity() * 8);
602 llvm::Align Alignment = llvm::Align(Layout.getAlignment().getQuantity());
603 llvm::Align UnadjustedAlign =
604 llvm::Align(Layout.getUnadjustedAlignment().getQuantity());
605
606 llvm::abi::RecordFlags RecFlags = llvm::abi::RecordFlags::None;
607 if (RD->hasAttr<TransparentUnionAttr>())
608 RecFlags |= llvm::abi::RecordFlags::IsTransparent;
609 if (RD->canPassInRegisters())
610 RecFlags |= llvm::abi::RecordFlags::CanPassInRegisters;
611 if (isa<CXXRecordDecl>(RD))
612 RecFlags |= llvm::abi::RecordFlags::IsCXXRecord;
613
614 return Builder.getUnionType(AllFields, Size, Alignment, UnadjustedAlign,
615 llvm::abi::StructPacking::Default, RecFlags);
616}
617
618llvm::Align QualTypeMapper::getTypeAlign(QualType QT) const {
619
620 return llvm::Align(ASTCtx.getTypeAlignInChars(QT).getQuantity());
621}
622
623const llvm::abi::Type *
624QualTypeMapper::createPointerTypeForPointee(QualType PointeeType) {
625 auto AddrSpace = PointeeType.getAddressSpace();
626 auto PointerSize = ASTCtx.getTargetInfo().getPointerWidth(AddrSpace);
627 llvm::Align Alignment =
628 llvm::Align(ASTCtx.getTargetInfo().getPointerAlign(AddrSpace));
629 // Function types without an explicit address space qualifier use the program
630 // address space, which may differ from the default data address space on
631 // targets like AMDGPU.
632 unsigned TargetAddrSpace =
633 PointeeType->isFunctionType() && !PointeeType.hasAddressSpace()
634 ? DL.getProgramAddressSpace()
635 : ASTCtx.getTargetInfo().getTargetAddressSpace(AddrSpace);
636 return Builder.getPointerType(PointerSize, llvm::Align(Alignment.value() / 8),
637 TargetAddrSpace, PointeeType.hasAddressSpace());
638}
639
640/// Processes the fields of a record (struct/class/union) and populates
641/// the Fields vector with FieldInfo objects containing type, offset,
642/// and bitfield information.
643///
644/// \param RD The RecordDecl whose fields to process
645/// \param Fields Output vector to populate with field information
646/// \param Layout The AST record layout containing field offset information
647void QualTypeMapper::computeFieldInfo(
648 const RecordDecl *RD, SmallVectorImpl<llvm::abi::FieldInfo> &Fields,
649 const ASTRecordLayout &Layout) {
650 unsigned FieldIndex = 0;
651
652 for (const auto *FD : RD->fields()) {
653 const llvm::abi::Type *FieldType = convertType(FD->getType());
654 uint64_t OffsetInBits = Layout.getFieldOffset(FieldIndex);
655
656 bool IsBitField = FD->isBitField();
657 uint64_t BitFieldWidth = 0;
658 bool IsUnnamedBitField = false;
659
660 if (IsBitField) {
661 BitFieldWidth = FD->getBitWidthValue();
662 IsUnnamedBitField = FD->isUnnamedBitField();
663 }
664
665 bool HasNoUniqueAddress = FD->hasAttr<NoUniqueAddressAttr>();
666 Fields.emplace_back(FieldType, OffsetInBits, IsBitField, BitFieldWidth,
667 IsUnnamedBitField, HasNoUniqueAddress);
668 ++FieldIndex;
669 }
670}
671
672} // namespace CodeGen
673} // namespace clang
Defines the clang::ASTContext interface.
Forward declaration of all AST node types.
Provides definitions for the various language-specific address spaces.
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Maps Clang QualType instances to corresponding LLVM ABI type representations.
static QualType getUnderlyingType(const SubRegion *R)
static QualType getPointeeType(const MemRegion *R)
C Language Family Type Representation.
CanQualType VoidPtrTy
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
QualType getElementType() const
Definition TypeBase.h:3832
This class is used for builtin types like 'int'.
Definition TypeBase.h:3245
Kind getKind() const
Definition TypeBase.h:3299
const llvm::abi::Type * convertType(clang::QualType QT)
Main entry point for converting Clang QualType to LLVM ABI Type.
bool hasAttr() const
Definition DeclBase.h:587
A (possibly-)qualified type.
Definition TypeBase.h:938
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8572
QualType getCanonicalType() const
Definition TypeBase.h:8498
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8540
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8567
bool canPassInRegisters() const
Determine whether this class can be passed in registers.
Definition Decl.h:4601
bool hasFlexibleArrayMember() const
Definition Decl.h:4497
bool isMemberFunctionPointerType() const
Definition TypeBase.h:8768
TypeClass getTypeClass() const
Definition TypeBase.h:2449
Defines the clang::TargetInfo interface.
static llvm::abi::VectorKind getABIVectorKind(clang::VectorKind Kind)
Maps a Clang vector kind onto the ABI library's notion of a vector flavor.
static bool isSVEPredicateBuiltinType(const BuiltinType *BT)
Returns true if BT is one of the AArch64 SVE predicate types, i.e.
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ Result
The result type of a method or function.
Definition TypeBase.h:906
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
Definition TypeBase.h:4252
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
Definition TypeBase.h:4255
U cast(CodeGen::Address addr)
Definition Address.h:327
unsigned long uint64_t