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