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 case Type::OverflowBehavior:
158 case Type::Auto:
159 case Type::DeducedTemplateSpecialization:
160 case Type::FunctionProto:
161 case Type::FunctionNoProto:
162 case Type::HLSLAttributedResource:
163 case Type::HLSLInlineSpirv:
164 llvm::reportFatalInternalError("Type not supported in ABI lowering");
165 }
166 llvm_unreachable("unhandled type class in convertTypeImpl");
167}
168
169/// Converts C/C++ builtin types to LLVM ABI types.
170/// This handles all fundamental scalar types including integers, floats,
171/// and special types like void and bool.
172const llvm::abi::Type *
173QualTypeMapper::convertBuiltinType(const BuiltinType *BT) {
174 QualType QT(BT, 0);
175
176 switch (BT->getKind()) {
177 case BuiltinType::Void:
178 return Builder.getVoidType();
179
180 case BuiltinType::NullPtr:
181 return createPointerTypeForPointee(QT);
182
183 case BuiltinType::Bool:
184 return Builder.getIntegerType(1, getTypeAlign(QT), /*Signed=*/false,
185 /*IsBitInt=*/false);
186
187 case BuiltinType::Char_S:
188 case BuiltinType::Char_U:
189 case BuiltinType::SChar:
190 case BuiltinType::UChar:
191 case BuiltinType::WChar_S:
192 case BuiltinType::WChar_U:
193 case BuiltinType::Char8:
194 case BuiltinType::Char16:
195 case BuiltinType::Char32:
196 case BuiltinType::Short:
197 case BuiltinType::UShort:
198 case BuiltinType::Int:
199 case BuiltinType::UInt:
200 case BuiltinType::Long:
201 case BuiltinType::ULong:
202 case BuiltinType::LongLong:
203 case BuiltinType::ULongLong:
204 case BuiltinType::Int128:
205 case BuiltinType::UInt128:
206 return Builder.getIntegerType(ASTCtx.getTypeSize(QT), getTypeAlign(QT),
207 /*Signed=*/BT->isSignedInteger(),
208 /*IsBitInt=*/false);
209
210 case BuiltinType::Half:
211 case BuiltinType::Float16:
212 case BuiltinType::BFloat16:
213 case BuiltinType::Float:
214 case BuiltinType::Double:
215 case BuiltinType::LongDouble:
216 case BuiltinType::Float128:
217 return Builder.getFloatType(ASTCtx.getFloatTypeSemantics(QT),
218 getTypeAlign(QT));
219
220 // TODO: IBM 128-bit extended double
221 case BuiltinType::Ibm128:
222 llvm::reportFatalInternalError(
223 "IBM128 is not yet supported in the ABI lowering libary");
224
225 // TODO: Fixed-point types
226 case BuiltinType::ShortAccum:
227 case BuiltinType::Accum:
228 case BuiltinType::LongAccum:
229 case BuiltinType::UShortAccum:
230 case BuiltinType::UAccum:
231 case BuiltinType::ULongAccum:
232 case BuiltinType::ShortFract:
233 case BuiltinType::Fract:
234 case BuiltinType::LongFract:
235 case BuiltinType::UShortFract:
236 case BuiltinType::UFract:
237 case BuiltinType::ULongFract:
238 case BuiltinType::SatShortAccum:
239 case BuiltinType::SatAccum:
240 case BuiltinType::SatLongAccum:
241 case BuiltinType::SatUShortAccum:
242 case BuiltinType::SatUAccum:
243 case BuiltinType::SatULongAccum:
244 case BuiltinType::SatShortFract:
245 case BuiltinType::SatFract:
246 case BuiltinType::SatLongFract:
247 case BuiltinType::SatUShortFract:
248 case BuiltinType::SatUFract:
249 case BuiltinType::SatULongFract:
250 llvm::reportFatalInternalError(
251 "Fixed Point types not yet implemented in the ABI lowering library");
252
253 // OpenCL image types are represented as opaque pointers.
254#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
255 case BuiltinType::Id:
256#include "clang/Basic/OpenCLImageTypes.def"
257 // OpenCL extension types are represented as opaque pointers.
258#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) case BuiltinType::Id:
259#include "clang/Basic/OpenCLExtensionTypes.def"
260 case BuiltinType::OCLSampler:
261 case BuiltinType::OCLEvent:
262 case BuiltinType::OCLClkEvent:
263 case BuiltinType::OCLQueue:
264 case BuiltinType::OCLReserveID:
265 return createPointerTypeForPointee(QT);
266
267 // Objective-C builtin types are represented as opaque pointers.
268 case BuiltinType::ObjCId:
269 case BuiltinType::ObjCClass:
270 case BuiltinType::ObjCSel:
271 return createPointerTypeForPointee(QT);
272
273 // AArch64 SVE data and predicate types, including the x2/x3/x4 tuples.
274#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId) \
275 case BuiltinType::Id:
276#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId) \
277 case BuiltinType::Id:
278#include "clang/Basic/AArch64ACLETypes.def"
279 return convertSVEBuiltinType(BT);
280
281 case BuiltinType::SveCount:
282 return Builder.getScalablePredicateOrCountVectorType(
283 getTypeAlign(QT), llvm::abi::VectorKind::SVECount);
284
285 // TODO: __mfp8 has no floating-point semantics of its own, so representing
286 // it needs a decision about how the ABI library should model opaque
287 // floating-point data. As an mfloat8 vector element it is treated as an
288 // 8-bit integer, but that is not right for the scalar type, which is passed
289 // in a floating-point register.
290 case BuiltinType::MFloat8:
291 llvm::reportFatalInternalError(
292 "__mfp8 is not yet supported in the ABI lowering library");
293
294 // Target-specific vector/matrix types — not yet implemented.
295#define PPC_VECTOR_TYPE(Name, Id, Size) case BuiltinType::Id:
296#include "clang/Basic/PPCTypes.def"
297 llvm::reportFatalInternalError(
298 "PPC MMA types not yet supported in ABI lowering library");
299#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
300#include "clang/Basic/RISCVVTypes.def"
301 llvm::reportFatalInternalError(
302 "RISC-V vector types not yet supported in ABI lowering library");
303#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
304#include "clang/Basic/WebAssemblyReferenceTypes.def"
305 llvm::reportFatalInternalError("WebAssembly reference types not yet "
306 "supported in ABI lowering library");
307#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
308#include "clang/Basic/AMDGPUTypes.def"
309 llvm::reportFatalInternalError(
310 "AMDGPU types not yet supported in ABI lowering library");
311#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
312#include "clang/Basic/HLSLIntangibleTypes.def"
313 llvm::reportFatalInternalError(
314 "HLSL intangible types not yet Supported in ABI lowering library");
315#define HLSL_PACKED_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
316#include "clang/Basic/HLSLPackedTypes.def"
317 llvm::reportFatalInternalError(
318 "HLSL packed types not yet Supported in ABI lowering library");
319#define SPIRV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
320#include "clang/Basic/SPIRVTypes.def"
321 llvm::reportFatalInternalError(
322 "SPIR-V types not yet supported in ABI lowering library");
323
324 // Placeholder types should never reach ABI lowering.
325#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
326#define BUILTIN_TYPE(Id, SingletonId)
327#include "clang/AST/BuiltinTypes.def"
328 llvm::reportFatalInternalError(
329 "Placeholder type should not reach ABI lowering");
330
331 case BuiltinType::Dependent:
332 llvm::reportFatalInternalError(
333 "Dependent builtin type should not reach ABI lowering");
334 }
335 llvm_unreachable("unhandled builtin type kind in convertBuiltinType");
336}
337
338/// Converts array types to LLVM ABI array representations.
339/// Handles different array kinds: constant arrays, incomplete arrays,
340/// and variable-length arrays.
341///
342/// \param AT The ArrayType to convert
343/// \return LLVM ABI ArrayType or PointerType
344const llvm::abi::Type *
345QualTypeMapper::convertArrayType(const clang::ArrayType *AT) {
346 const llvm::abi::Type *ElementType = convertType(AT->getElementType());
347 uint64_t Size = ASTCtx.getTypeSize(AT);
348
349 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
350 auto NumElements = CAT->getZExtSize();
351 return Builder.getArrayType(ElementType, NumElements, Size);
352 }
354 return Builder.getArrayType(ElementType, 0, 0);
355 if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
356 return createPointerTypeForPointee(VAT->getPointeeType());
357 llvm::reportFatalInternalError(
358 "unexpected array type in ABI lowering (dependent array types should be "
359 "resolved before reaching this point)");
360}
361
362const llvm::abi::Type *QualTypeMapper::convertVectorType(const VectorType *VT) {
363 const llvm::abi::Type *ElementType = convertType(VT->getElementType());
364 QualType VectorQualType(VT, 0);
365
366 unsigned NElems = VT->getNumElements();
367 llvm::ElementCount NumElements = llvm::ElementCount::getFixed(NElems);
368 llvm::Align VectorAlign = getTypeAlign(VectorQualType);
369
370 // SveFixedLengthPredicate is tagged SVEPredicate, like sizeless svbool_t.
371 // The element type is left as the AST unsigned char (i8). The builtin path
372 // below maps sizeless predicates to i1. Both match the Clang AST, but
373 // consumers that key only off VectorKind cannot assume a 1-bit element.
374 return Builder.getVectorType(ElementType, NumElements, VectorAlign,
375 getABIVectorKind(VT->getVectorKind()));
376}
377
378/// Converts the sizeless AArch64 SVE data and predicate builtin types.
379/// Single vectors become a scalable LLVM ABI VectorType. The x2/x3/x4
380/// forms become a TupleType of that vector.
381///
382/// \param BT The SVE BuiltinType to convert
383/// \return LLVM ABI VectorType or TupleType
384const llvm::abi::Type *
385QualTypeMapper::convertSVEBuiltinType(const BuiltinType *BT) {
386 ASTContext::BuiltinVectorTypeInfo Info = ASTCtx.getBuiltinVectorTypeInfo(BT);
387 assert(Info.NumVectors > 0 && Info.NumVectors <= 4 &&
388 "Expected 1, 2, 3 or 4 vectors!");
389
390 // __mfp8 carries no floating-point semantics, so mfloat8 vectors use an
391 // 8-bit integer element type, which is also how they are represented in
392 // LLVM IR.
393 const llvm::abi::Type *ElementType =
394 Info.ElementType->isMFloat8Type()
395 ? Builder.getIntegerType(8, llvm::Align(1), /*Signed=*/false)
396 : convertType(Info.ElementType);
397
398 llvm::abi::VectorKind VecKind = isSVEPredicateBuiltinType(BT)
399 ? llvm::abi::VectorKind::SVEPredicate
400 : llvm::abi::VectorKind::SVEData;
401
402 const llvm::abi::VectorType *VecTy = Builder.getVectorType(
403 ElementType, Info.EC, getTypeAlign(QualType(BT, 0)), VecKind);
404 if (Info.NumVectors == 1)
405 return VecTy;
406 return Builder.getTupleType(VecTy, Info.NumVectors);
407}
408
409/// Converts complex types to LLVM ABI complex representations.
410/// Complex types consist of two components of the element type
411/// (real and imaginary parts).
412///
413/// \param CT The ComplexType to convert
414/// \return LLVM ABI ComplexType with element type and alignment
415const llvm::abi::Type *
416QualTypeMapper::convertComplexType(const ComplexType *CT) {
417 const llvm::abi::Type *ElementType = convertType(CT->getElementType());
418 llvm::Align ComplexAlign = getTypeAlign(QualType(CT, 0));
419
420 return Builder.getComplexType(ElementType, ComplexAlign);
421}
422
423/// Converts member pointer types to LLVM ABI representations.
424/// Member pointers have different layouts depending on whether they
425/// point to functions or data members.
426///
427/// \param MPT The MemberPointerType to convert
428/// \return LLVM ABI MemberPointerType
429const llvm::abi::Type *
430QualTypeMapper::convertMemberPointerType(const clang::MemberPointerType *MPT) {
431 QualType QT(MPT, 0);
432 uint64_t Size = ASTCtx.getTypeSize(QT);
433 llvm::Align Align = getTypeAlign(QT);
434
435 bool IsFunctionPointer = MPT->isMemberFunctionPointerType();
436
437 return Builder.getMemberPointerType(IsFunctionPointer, Size, Align);
438}
439
440/// Converts record types (struct/class/union) to LLVM ABI representations.
441/// This is the main dispatch method that handles different record kinds
442/// and delegates to specialized converters.
443///
444/// \param RT The RecordType to convert
445/// \return LLVM ABI RecordType
446const llvm::abi::Type *QualTypeMapper::convertRecordType(const RecordType *RT) {
447 const RecordDecl *RD = RT->getDecl()->getDefinition();
448 if (!RD)
449 return Builder.getRecordType({}, llvm::TypeSize::getFixed(0),
450 llvm::Align(1),
451 /*UnadjustedAlign=*/llvm::Align(1));
452
453 if (RD->isUnion())
454 return convertUnionType(RD);
455
456 // Handle C++ classes with base classes
457 auto *CXXRd = dyn_cast<CXXRecordDecl>(RD);
458 if (CXXRd && (CXXRd->getNumBases() > 0 || CXXRd->getNumVBases() > 0))
459 return convertCXXRecordType(CXXRd);
460 return convertStructType(RD);
461}
462
463/// Converts C++ classes with inheritance to LLVM ABI struct representations.
464/// This method handles the complex layout of C++ objects including:
465/// - Virtual table pointers for polymorphic classes
466/// - Base class subobjects (both direct and virtual bases)
467/// - Member field layout with proper offsets
468///
469/// \param RD The C++ record declaration
470/// \return LLVM ABI RecordType representing the complete object layout
471const llvm::abi::RecordType *
472QualTypeMapper::convertCXXRecordType(const CXXRecordDecl *RD) {
473 const ASTRecordLayout &Layout = ASTCtx.getASTRecordLayout(RD);
474 SmallVector<llvm::abi::FieldInfo, 16> Fields;
475 SmallVector<llvm::abi::FieldInfo, 8> BaseClasses;
476 SmallVector<llvm::abi::FieldInfo, 8> VirtualBaseClasses;
477
478 // Add vtable pointer for polymorphic classes
479 if (RD->isPolymorphic()) {
480 const llvm::abi::Type *VtablePointer =
481 createPointerTypeForPointee(ASTCtx.VoidPtrTy);
482 Fields.emplace_back(VtablePointer, 0);
483 }
484
485 for (const auto &Base : RD->bases()) {
486 if (Base.isVirtual())
487 continue;
488
489 const RecordType *BaseRT = Base.getType()->castAs<RecordType>();
490 const llvm::abi::Type *BaseType = convertType(Base.getType());
491 uint64_t BaseOffset =
492 Layout.getBaseClassOffset(BaseRT->getAsCXXRecordDecl()).getQuantity() *
493 8;
494 BaseClasses.emplace_back(BaseType, BaseOffset);
495 }
496
497 for (const auto &VBase : RD->vbases()) {
498 const RecordType *VBaseRT = VBase.getType()->castAs<RecordType>();
499 const llvm::abi::Type *VBaseType = convertType(VBase.getType());
500 uint64_t VBaseOffset =
501 Layout.getVBaseClassOffset(VBaseRT->getAsCXXRecordDecl())
502 .getQuantity() *
503 8;
504 VirtualBaseClasses.emplace_back(VBaseType, VBaseOffset);
505 }
506
507 computeFieldInfo(RD, Fields, Layout);
508
509 llvm::sort(Fields,
510 [](const llvm::abi::FieldInfo &A, const llvm::abi::FieldInfo &B) {
511 return A.OffsetInBits < B.OffsetInBits;
512 });
513
514 llvm::TypeSize Size =
515 llvm::TypeSize::getFixed(Layout.getSize().getQuantity() * 8);
516 llvm::Align Alignment = llvm::Align(Layout.getAlignment().getQuantity());
517 llvm::Align UnadjustedAlign =
518 llvm::Align(Layout.getUnadjustedAlignment().getQuantity());
519
520 llvm::abi::RecordFlags RecFlags = llvm::abi::RecordFlags::IsCXXRecord;
521 if (RD->isPolymorphic())
522 RecFlags |= llvm::abi::RecordFlags::IsPolymorphic;
523 if (RD->canPassInRegisters())
524 RecFlags |= llvm::abi::RecordFlags::CanPassInRegisters;
525 if (RD->hasFlexibleArrayMember())
526 RecFlags |= llvm::abi::RecordFlags::HasFlexibleArrayMember;
527
528 return Builder.getRecordType(Fields, Size, Alignment, UnadjustedAlign,
529 llvm::abi::StructPacking::Default, BaseClasses,
530 VirtualBaseClasses, RecFlags);
531}
532
533/// Converts enumeration types to their underlying integer representations.
534/// This method handles various enum states and falls back to safe defaults
535/// when enum information is incomplete or invalid.
536///
537/// \param ET The EnumType to convert
538/// \return LLVM ABI IntegerType representing the enum's underlying type
539const llvm::abi::Type *
540QualTypeMapper::convertEnumType(const clang::EnumType *ET) {
541 const EnumDecl *ED = ET->getDecl();
542 QualType UnderlyingType = ED->getIntegerType();
543
544 if (UnderlyingType.isNull())
545 UnderlyingType = ASTCtx.IntTy;
546
547 return convertType(UnderlyingType);
548}
549
550/// Converts plain C structs and C++ classes without inheritance.
551/// This handles the simpler case where we only need to layout member fields
552/// without considering base classes or virtual functions.
553///
554/// \param RD The RecordDecl to convert
555/// \return LLVM ABI RecordType
556const llvm::abi::RecordType *
557QualTypeMapper::convertStructType(const clang::RecordDecl *RD) {
558 const ASTRecordLayout &Layout = ASTCtx.getASTRecordLayout(RD);
559
560 bool IsCXXRecord = isa<CXXRecordDecl>(RD);
561 SmallVector<llvm::abi::FieldInfo, 16> Fields;
562 computeFieldInfo(RD, Fields, Layout);
563
564 llvm::TypeSize Size =
565 llvm::TypeSize::getFixed(Layout.getSize().getQuantity() * 8);
566 llvm::Align Alignment = llvm::Align(Layout.getAlignment().getQuantity());
567 llvm::Align UnadjustedAlign =
568 llvm::Align(Layout.getUnadjustedAlignment().getQuantity());
569
570 llvm::abi::RecordFlags RecFlags = llvm::abi::RecordFlags::None;
571 if (IsCXXRecord)
572 RecFlags |= llvm::abi::RecordFlags::IsCXXRecord;
573 if (RD->canPassInRegisters())
574 RecFlags |= llvm::abi::RecordFlags::CanPassInRegisters;
575 if (RD->hasFlexibleArrayMember())
576 RecFlags |= llvm::abi::RecordFlags::HasFlexibleArrayMember;
577
578 return Builder.getRecordType(Fields, Size, Alignment, UnadjustedAlign,
579 llvm::abi::StructPacking::Default, {}, {},
580 RecFlags);
581}
582
583/// Converts C union types where all fields occupy the same memory location.
584/// The union size is determined by its largest member, and all fields
585/// start at offset 0.
586///
587/// \param RD The RecordDecl representing the union
588/// \return LLVM ABI UnionType
589const llvm::abi::RecordType *
590QualTypeMapper::convertUnionType(const clang::RecordDecl *RD) {
591 const ASTRecordLayout &Layout = ASTCtx.getASTRecordLayout(RD);
592
593 SmallVector<llvm::abi::FieldInfo, 16> AllFields;
594 computeFieldInfo(RD, AllFields, Layout);
595
596 llvm::TypeSize Size =
597 llvm::TypeSize::getFixed(Layout.getSize().getQuantity() * 8);
598 llvm::Align Alignment = llvm::Align(Layout.getAlignment().getQuantity());
599 llvm::Align UnadjustedAlign =
600 llvm::Align(Layout.getUnadjustedAlignment().getQuantity());
601
602 llvm::abi::RecordFlags RecFlags = llvm::abi::RecordFlags::None;
603 if (RD->hasAttr<TransparentUnionAttr>())
604 RecFlags |= llvm::abi::RecordFlags::IsTransparent;
605 if (RD->canPassInRegisters())
606 RecFlags |= llvm::abi::RecordFlags::CanPassInRegisters;
607 if (isa<CXXRecordDecl>(RD))
608 RecFlags |= llvm::abi::RecordFlags::IsCXXRecord;
609
610 return Builder.getUnionType(AllFields, Size, Alignment, UnadjustedAlign,
611 llvm::abi::StructPacking::Default, RecFlags);
612}
613
614llvm::Align QualTypeMapper::getTypeAlign(QualType QT) const {
615
616 return llvm::Align(ASTCtx.getTypeAlignInChars(QT).getQuantity());
617}
618
619const llvm::abi::Type *
620QualTypeMapper::createPointerTypeForPointee(QualType PointeeType) {
621 auto AddrSpace = PointeeType.getAddressSpace();
622 auto PointerSize = ASTCtx.getTargetInfo().getPointerWidth(AddrSpace);
623 llvm::Align Alignment =
624 llvm::Align(ASTCtx.getTargetInfo().getPointerAlign(AddrSpace));
625 // Function types without an explicit address space qualifier use the program
626 // address space, which may differ from the default data address space on
627 // targets like AMDGPU.
628 unsigned TargetAddrSpace =
629 PointeeType->isFunctionType() && !PointeeType.hasAddressSpace()
630 ? DL.getProgramAddressSpace()
631 : ASTCtx.getTargetInfo().getTargetAddressSpace(AddrSpace);
632 return Builder.getPointerType(PointerSize, llvm::Align(Alignment.value() / 8),
633 TargetAddrSpace);
634}
635
636/// Processes the fields of a record (struct/class/union) and populates
637/// the Fields vector with FieldInfo objects containing type, offset,
638/// and bitfield information.
639///
640/// \param RD The RecordDecl whose fields to process
641/// \param Fields Output vector to populate with field information
642/// \param Layout The AST record layout containing field offset information
643void QualTypeMapper::computeFieldInfo(
644 const RecordDecl *RD, SmallVectorImpl<llvm::abi::FieldInfo> &Fields,
645 const ASTRecordLayout &Layout) {
646 unsigned FieldIndex = 0;
647
648 for (const auto *FD : RD->fields()) {
649 const llvm::abi::Type *FieldType = convertType(FD->getType());
650 uint64_t OffsetInBits = Layout.getFieldOffset(FieldIndex);
651
652 bool IsBitField = FD->isBitField();
653 uint64_t BitFieldWidth = 0;
654 bool IsUnnamedBitField = false;
655
656 if (IsBitField) {
657 BitFieldWidth = FD->getBitWidthValue();
658 IsUnnamedBitField = FD->isUnnamedBitField();
659 }
660
661 bool HasNoUniqueAddress = FD->hasAttr<NoUniqueAddressAttr>();
662 Fields.emplace_back(FieldType, OffsetInBits, IsBitField, BitFieldWidth,
663 IsUnnamedBitField, HasNoUniqueAddress);
664 ++FieldIndex;
665 }
666}
667
668} // namespace CodeGen
669} // 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:3831
This class is used for builtin types like 'int'.
Definition TypeBase.h:3244
Kind getKind() const
Definition TypeBase.h:3298
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:585
A (possibly-)qualified type.
Definition TypeBase.h:938
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8571
QualType getCanonicalType() const
Definition TypeBase.h:8497
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8539
bool canPassInRegisters() const
Determine whether this class can be passed in registers.
Definition Decl.h:4597
bool hasFlexibleArrayMember() const
Definition Decl.h:4493
bool isMemberFunctionPointerType() const
Definition TypeBase.h:8767
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:4251
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
Definition TypeBase.h:4254
U cast(CodeGen::Address addr)
Definition Address.h:327
unsigned long uint64_t