clang 23.0.0git
CodeGenTypes.cpp
Go to the documentation of this file.
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
13#include "CodeGenTypes.h"
14#include "CGCXXABI.h"
15#include "CGCall.h"
16#include "CGDebugInfo.h"
17#include "CGHLSLRuntime.h"
18#include "CGOpenCLRuntime.h"
19#include "CGRecordLayout.h"
20#include "TargetInfo.h"
22#include "clang/AST/DeclCXX.h"
23#include "clang/AST/DeclObjC.h"
24#include "clang/AST/Expr.h"
27#include "llvm/IR/DataLayout.h"
28#include "llvm/IR/DerivedTypes.h"
29#include "llvm/IR/Module.h"
30
31using namespace clang;
32using namespace CodeGen;
33
35 : CGM(cgm), Context(cgm.getContext()), TheModule(cgm.getModule()),
36 Target(cgm.getTarget()) {
37 SkippedLayout = false;
38 LongDoubleReferenced = false;
39}
40
42 for (llvm::FoldingSet<CGFunctionInfo>::iterator
43 I = FunctionInfos.begin(), E = FunctionInfos.end(); I != E; )
44 delete &*I++;
45}
46
48
50 return CGM.getCodeGenOpts();
51}
52
54 llvm::StructType *Ty,
55 StringRef suffix) {
57 llvm::raw_svector_ostream OS(TypeName);
58 OS << RD->getKindName() << '.';
59
60 // FIXME: We probably want to make more tweaks to the printing policy. For
61 // example, we should probably enable PrintCanonicalTypes and
62 // FullyQualifiedNames.
66
67 // Name the codegen type after the typedef name
68 // if there is no tag type name available
69 if (RD->getIdentifier()) {
70 // FIXME: We should not have to check for a null decl context here.
71 // Right now we do it because the implicit Obj-C decls don't have one.
72 if (RD->getDeclContext())
73 RD->printQualifiedName(OS, Policy);
74 else
75 RD->printName(OS, Policy);
76 } else if (const TypedefNameDecl *TDD = RD->getTypedefNameForAnonDecl()) {
77 // FIXME: We should not have to check for a null decl context here.
78 // Right now we do it because the implicit Obj-C decls don't have one.
79 if (TDD->getDeclContext())
80 TDD->printQualifiedName(OS, Policy);
81 else
82 TDD->printName(OS);
83 } else
84 OS << "anon";
85
86 if (!suffix.empty())
87 OS << suffix;
88
89 Ty->setName(OS.str());
90}
91
92/// ConvertTypeForMem - Convert type T into a llvm::Type. This differs from
93/// ConvertType in that it is used to convert to the memory representation for
94/// a type. For example, the scalar representation for _Bool is i1, but the
95/// memory representation is usually i8 or i32, depending on the target.
96///
97/// We generally assume that the alloc size of this type under the LLVM
98/// data layout is the same as the size of the AST type. The alignment
99/// does not have to match: Clang should always use explicit alignments
100/// and packed structs as necessary to produce the layout it needs.
101/// But the size does need to be exactly right or else things like struct
102/// layout will break.
104 if (T->isConstantMatrixType()) {
105 const Type *Ty = Context.getCanonicalType(T).getTypePtr();
107 llvm::Type *IRElemTy = ConvertType(MT->getElementType());
108 if (Context.getLangOpts().HLSL) {
109 if (T->isConstantMatrixBoolType())
110 IRElemTy = ConvertTypeForMem(Context.BoolTy);
111
112 unsigned NumRows = MT->getNumRows();
113 unsigned NumCols = MT->getNumColumns();
114 bool IsRowMajor =
115 CGM.getContext().getLangOpts().getDefaultMatrixMemoryLayout() ==
117 unsigned VecLen = IsRowMajor ? NumCols : NumRows;
118 unsigned ArrayLen = IsRowMajor ? NumRows : NumCols;
119 llvm::Type *VecTy = llvm::FixedVectorType::get(IRElemTy, VecLen);
120 return llvm::ArrayType::get(VecTy, ArrayLen);
121 }
122 return llvm::ArrayType::get(IRElemTy, MT->getNumElementsFlattened());
123 }
124
125 llvm::Type *R = ConvertType(T);
126
127 // Check for the boolean vector case.
128 if (T->isExtVectorBoolType()) {
129 auto *FixedVT = cast<llvm::FixedVectorType>(R);
130
131 if (Context.getLangOpts().HLSL) {
132 llvm::Type *IRElemTy = ConvertTypeForMem(Context.BoolTy);
133 return llvm::FixedVectorType::get(IRElemTy, FixedVT->getNumElements());
134 }
135
136 // Pad to at least one byte.
137 uint64_t BytePadded = std::max<uint64_t>(FixedVT->getNumElements(), 8);
138 return llvm::IntegerType::get(FixedVT->getContext(), BytePadded);
139 }
140
141 // If T is _Bool or a _BitInt type, ConvertType will produce an IR type
142 // with the exact semantic bit-width of the AST type; for example,
143 // _BitInt(17) will turn into i17. In memory, however, we need to store
144 // such values extended to their full storage size as decided by AST
145 // layout; this is an ABI requirement. Ideally, we would always use an
146 // integer type that's just the bit-size of the AST type; for example, if
147 // sizeof(_BitInt(17)) == 4, _BitInt(17) would turn into i32. That is what's
148 // returned by convertTypeForLoadStore. However, that type does not
149 // always satisfy the size requirement on memory representation types
150 // describe above. For example, a 32-bit platform might reasonably set
151 // sizeof(_BitInt(65)) == 12, but i96 is likely to have to have an alloc size
152 // of 16 bytes in the LLVM data layout. In these cases, we simply return
153 // a byte array of the appropriate size.
154 if (T->isBitIntType()) {
156 return llvm::ArrayType::get(CGM.Int8Ty,
157 Context.getTypeSizeInChars(T).getQuantity());
158 return llvm::IntegerType::get(getLLVMContext(),
159 (unsigned)Context.getTypeSize(T));
160 }
161
162 if (R->isIntegerTy(1))
163 return llvm::IntegerType::get(getLLVMContext(),
164 (unsigned)Context.getTypeSize(T));
165
166 // Else, don't map it.
167 return R;
168}
169
171 llvm::Type *LLVMTy) {
172 if (!LLVMTy)
173 LLVMTy = ConvertType(ASTTy);
174
175 CharUnits ASTSize = Context.getTypeSizeInChars(ASTTy);
176 CharUnits LLVMSize =
178 return ASTSize != LLVMSize;
179}
180
182 llvm::Type *LLVMTy) {
183 if (!LLVMTy)
184 LLVMTy = ConvertType(T);
185
186 if (T->isBitIntType())
187 return llvm::Type::getIntNTy(
188 getLLVMContext(), Context.getTypeSizeInChars(T).getQuantity() * 8);
189
190 if (LLVMTy->isIntegerTy(1))
191 return llvm::IntegerType::get(getLLVMContext(),
192 (unsigned)Context.getTypeSize(T));
193
194 if (T->isConstantMatrixBoolType()) {
195 // Matrices are loaded and stored atomically as vectors. Therefore we
196 // construct a FixedVectorType here instead of returning
197 // ConvertTypeForMem(T) which would return an ArrayType instead.
198 const Type *Ty = Context.getCanonicalType(T).getTypePtr();
200 llvm::Type *IRElemTy = ConvertTypeForMem(MT->getElementType());
201 return llvm::FixedVectorType::get(IRElemTy, MT->getNumElementsFlattened());
202 }
203
204 if (T->isExtVectorBoolType())
205 return ConvertTypeForMem(T);
206
207 return LLVMTy;
208}
209
210/// isRecordLayoutComplete - Return true if the specified type is already
211/// completely laid out.
213 llvm::DenseMap<const Type*, llvm::StructType *>::const_iterator I =
214 RecordDeclTypes.find(Ty);
215 return I != RecordDeclTypes.end() && !I->second->isOpaque();
216}
217
218/// isFuncParamTypeConvertible - Return true if the specified type in a
219/// function parameter or result position can be converted to an IR type at this
220/// point. This boils down to being whether it is complete.
222 // Some ABIs cannot have their member pointers represented in IR unless
223 // certain circumstances have been reached.
224 if (const auto *MPT = Ty->getAs<MemberPointerType>())
226
227 // If this isn't a tagged type, we can convert it!
228 const TagType *TT = Ty->getAs<TagType>();
229 if (!TT) return true;
230
231 // Incomplete types cannot be converted.
232 return !TT->isIncompleteType();
233}
234
235
236/// Code to verify a given function type is complete, i.e. the return type
237/// and all of the parameter types are complete. Also check to see if we are in
238/// a RS_StructPointer context, and if so whether any struct types have been
239/// pended. If so, we don't want to ask the ABI lowering code to handle a type
240/// that cannot be converted to an IR type.
243 return false;
244
245 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT))
246 for (unsigned i = 0, e = FPT->getNumParams(); i != e; i++)
247 if (!isFuncParamTypeConvertible(FPT->getParamType(i)))
248 return false;
249
250 return true;
251}
252
253/// UpdateCompletedType - When we find the full definition for a TagDecl,
254/// replace the 'opaque' type we previously made for it if applicable.
256 CanQualType T = CGM.getContext().getCanonicalTagType(TD);
257 // If this is an enum being completed, then we flush all non-struct types from
258 // the cache. This allows function types and other things that may be derived
259 // from the enum to be recomputed.
260 if (const EnumDecl *ED = dyn_cast<EnumDecl>(TD)) {
261 // Only flush the cache if we've actually already converted this type.
262 if (TypeCache.count(T->getTypePtr())) {
263 // Okay, we formed some types based on this. We speculated that the enum
264 // would be lowered to i32, so we only need to flush the cache if this
265 // didn't happen.
266 if (!ConvertType(ED->getIntegerType())->isIntegerTy(32))
267 TypeCache.clear();
268 }
269 // If necessary, provide the full definition of a type only used with a
270 // declaration so far.
271 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
272 DI->completeType(ED);
273 return;
274 }
275
276 // If we completed a RecordDecl that we previously used and converted to an
277 // anonymous type, then go ahead and complete it now.
278 const RecordDecl *RD = cast<RecordDecl>(TD);
279 if (RD->isDependentType()) return;
280
281 // Only complete it if we converted it already. If we haven't converted it
282 // yet, we'll just do it lazily.
283 if (RecordDeclTypes.count(T.getTypePtr()))
285
286 // If necessary, provide the full definition of a type only used with a
287 // declaration so far.
288 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
289 DI->completeType(RD);
290}
291
293 CanQualType T = Context.getCanonicalTagType(RD);
294 T = Context.getCanonicalType(T);
295
296 const Type *Ty = T.getTypePtr();
297 if (RecordsWithOpaqueMemberPointers.count(Ty)) {
298 TypeCache.clear();
299 RecordsWithOpaqueMemberPointers.clear();
300 }
301}
302
303static llvm::Type *getTypeForFormat(llvm::LLVMContext &VMContext,
304 const llvm::fltSemantics &format,
305 bool UseNativeHalf = false) {
306 if (&format == &llvm::APFloat::IEEEhalf()) {
307 if (UseNativeHalf)
308 return llvm::Type::getHalfTy(VMContext);
309 else
310 return llvm::Type::getInt16Ty(VMContext);
311 }
312 if (&format == &llvm::APFloat::BFloat())
313 return llvm::Type::getBFloatTy(VMContext);
314 if (&format == &llvm::APFloat::IEEEsingle())
315 return llvm::Type::getFloatTy(VMContext);
316 if (&format == &llvm::APFloat::IEEEdouble())
317 return llvm::Type::getDoubleTy(VMContext);
318 if (&format == &llvm::APFloat::IEEEquad())
319 return llvm::Type::getFP128Ty(VMContext);
320 if (&format == &llvm::APFloat::PPCDoubleDouble())
321 return llvm::Type::getPPC_FP128Ty(VMContext);
322 if (&format == &llvm::APFloat::x87DoubleExtended())
323 return llvm::Type::getX86_FP80Ty(VMContext);
324 llvm_unreachable("Unknown float format!");
325}
326
327llvm::Type *CodeGenTypes::ConvertFunctionTypeInternal(QualType QFT) {
328 assert(QFT.isCanonical());
329 const FunctionType *FT = cast<FunctionType>(QFT.getTypePtr());
330 // First, check whether we can build the full function type. If the
331 // function type depends on an incomplete type (e.g. a struct or enum), we
332 // cannot lower the function type.
333 if (!isFuncTypeConvertible(FT)) {
334 // This function's type depends on an incomplete tag type.
335
336 // Force conversion of all the relevant record types, to make sure
337 // we re-convert the FunctionType when appropriate.
338 if (const auto *RD = FT->getReturnType()->getAsRecordDecl())
340 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT))
341 for (unsigned i = 0, e = FPT->getNumParams(); i != e; i++)
342 if (const auto *RD = FPT->getParamType(i)->getAsRecordDecl())
344
345 SkippedLayout = true;
346
347 // Return a placeholder type.
348 return llvm::StructType::get(getLLVMContext());
349 }
350
351 // The function type can be built; call the appropriate routines to
352 // build it.
353 const CGFunctionInfo *FI;
354 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
357 } else {
358 const FunctionNoProtoType *FNPT = cast<FunctionNoProtoType>(FT);
361 }
362
363 llvm::Type *ResultType = nullptr;
364 // If there is something higher level prodding our CGFunctionInfo, then
365 // don't recurse into it again.
366 if (FunctionsBeingProcessed.count(FI)) {
367
368 ResultType = llvm::StructType::get(getLLVMContext());
369 SkippedLayout = true;
370 } else {
371
372 // Otherwise, we're good to go, go ahead and convert it.
373 ResultType = GetFunctionType(*FI);
374 }
375
376 return ResultType;
377}
378
379/// ConvertType - Convert the specified type to its LLVM form.
381 T = Context.getCanonicalType(T);
382
383 const Type *Ty = T.getTypePtr();
384
385 // For the device-side compilation, CUDA device builtin surface/texture types
386 // may be represented in different types.
387 if (Context.getLangOpts().CUDAIsDevice) {
388 if (T->isCUDADeviceBuiltinSurfaceType()) {
389 if (auto *Ty = CGM.getTargetCodeGenInfo()
390 .getCUDADeviceBuiltinSurfaceDeviceType())
391 return Ty;
392 } else if (T->isCUDADeviceBuiltinTextureType()) {
393 if (auto *Ty = CGM.getTargetCodeGenInfo()
394 .getCUDADeviceBuiltinTextureDeviceType())
395 return Ty;
396 }
397 }
398
399 // RecordTypes are cached and processed specially.
400 if (const auto *RT = dyn_cast<RecordType>(Ty))
401 return ConvertRecordDeclType(RT->getDecl()->getDefinitionOrSelf());
402
403 llvm::Type *CachedType = nullptr;
404 auto TCI = TypeCache.find(Ty);
405 if (TCI != TypeCache.end())
406 CachedType = TCI->second;
407 // With expensive checks, check that the type we compute matches the
408 // cached type.
409#ifndef EXPENSIVE_CHECKS
410 if (CachedType)
411 return CachedType;
412#endif
413
414 // If we don't have it in the cache, convert it now.
415 llvm::Type *ResultType = nullptr;
416 switch (Ty->getTypeClass()) {
417 case Type::Record: // Handled above.
418#define TYPE(Class, Base)
419#define ABSTRACT_TYPE(Class, Base)
420#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
421#define DEPENDENT_TYPE(Class, Base) case Type::Class:
422#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
423#include "clang/AST/TypeNodes.inc"
424 llvm_unreachable("Non-canonical or dependent types aren't possible.");
425
426 case Type::Builtin: {
427 switch (cast<BuiltinType>(Ty)->getKind()) {
428 case BuiltinType::Void:
429 case BuiltinType::ObjCId:
430 case BuiltinType::ObjCClass:
431 case BuiltinType::ObjCSel:
432 // LLVM void type can only be used as the result of a function call. Just
433 // map to the same as char.
434 ResultType = llvm::Type::getInt8Ty(getLLVMContext());
435 break;
436
437 case BuiltinType::Bool:
438 // Note that we always return bool as i1 for use as a scalar type.
439 ResultType = llvm::Type::getInt1Ty(getLLVMContext());
440 break;
441
442 case BuiltinType::Char_S:
443 case BuiltinType::Char_U:
444 case BuiltinType::SChar:
445 case BuiltinType::UChar:
446 case BuiltinType::Short:
447 case BuiltinType::UShort:
448 case BuiltinType::Int:
449 case BuiltinType::UInt:
450 case BuiltinType::Long:
451 case BuiltinType::ULong:
452 case BuiltinType::LongLong:
453 case BuiltinType::ULongLong:
454 case BuiltinType::WChar_S:
455 case BuiltinType::WChar_U:
456 case BuiltinType::Char8:
457 case BuiltinType::Char16:
458 case BuiltinType::Char32:
459 case BuiltinType::ShortAccum:
460 case BuiltinType::Accum:
461 case BuiltinType::LongAccum:
462 case BuiltinType::UShortAccum:
463 case BuiltinType::UAccum:
464 case BuiltinType::ULongAccum:
465 case BuiltinType::ShortFract:
466 case BuiltinType::Fract:
467 case BuiltinType::LongFract:
468 case BuiltinType::UShortFract:
469 case BuiltinType::UFract:
470 case BuiltinType::ULongFract:
471 case BuiltinType::SatShortAccum:
472 case BuiltinType::SatAccum:
473 case BuiltinType::SatLongAccum:
474 case BuiltinType::SatUShortAccum:
475 case BuiltinType::SatUAccum:
476 case BuiltinType::SatULongAccum:
477 case BuiltinType::SatShortFract:
478 case BuiltinType::SatFract:
479 case BuiltinType::SatLongFract:
480 case BuiltinType::SatUShortFract:
481 case BuiltinType::SatUFract:
482 case BuiltinType::SatULongFract:
483 ResultType = llvm::IntegerType::get(getLLVMContext(),
484 static_cast<unsigned>(Context.getTypeSize(T)));
485 break;
486
487 case BuiltinType::Float16:
488 ResultType =
489 getTypeForFormat(getLLVMContext(), Context.getFloatTypeSemantics(T),
490 /* UseNativeHalf = */ true);
491 break;
492
493 case BuiltinType::Half:
494 // Half FP can either be storage-only (lowered to i16) or native.
495 ResultType = getTypeForFormat(
496 getLLVMContext(), Context.getFloatTypeSemantics(T),
497 Context.getLangOpts().NativeHalfType ||
498 !Context.getTargetInfo().useFP16ConversionIntrinsics());
499 break;
500 case BuiltinType::LongDouble:
501 LongDoubleReferenced = true;
502 [[fallthrough]];
503 case BuiltinType::BFloat16:
504 case BuiltinType::Float:
505 case BuiltinType::Double:
506 case BuiltinType::Float128:
507 case BuiltinType::Ibm128:
508 ResultType = getTypeForFormat(getLLVMContext(),
509 Context.getFloatTypeSemantics(T),
510 /* UseNativeHalf = */ false);
511 break;
512
513 case BuiltinType::NullPtr:
514 // Model std::nullptr_t as i8*
515 ResultType = llvm::PointerType::getUnqual(getLLVMContext());
516 break;
517
518 case BuiltinType::UInt128:
519 case BuiltinType::Int128:
520 ResultType = llvm::IntegerType::get(getLLVMContext(), 128);
521 break;
522
523#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
524 case BuiltinType::Id:
525#include "clang/Basic/OpenCLImageTypes.def"
526#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
527 case BuiltinType::Id:
528#include "clang/Basic/OpenCLExtensionTypes.def"
529 case BuiltinType::OCLSampler:
530 case BuiltinType::OCLEvent:
531 case BuiltinType::OCLClkEvent:
532 case BuiltinType::OCLQueue:
533 case BuiltinType::OCLReserveID:
534 ResultType = CGM.getOpenCLRuntime().convertOpenCLSpecificType(Ty);
535 break;
536#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId) \
537 case BuiltinType::Id:
538#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId) \
539 case BuiltinType::Id:
540#include "clang/Basic/AArch64ACLETypes.def"
541 {
543 Context.getBuiltinVectorTypeInfo(cast<BuiltinType>(Ty));
544 // The `__mfp8` type maps to `<1 x i8>` which can't be used to build
545 // a <N x i8> vector type, hence bypass the call to `ConvertType` for
546 // the element type and create the vector type directly.
547 auto *EltTy = Info.ElementType->isMFloat8Type()
548 ? llvm::Type::getInt8Ty(getLLVMContext())
549 : ConvertType(Info.ElementType);
550 auto *VTy = llvm::VectorType::get(EltTy, Info.EC);
551 switch (Info.NumVectors) {
552 default:
553 llvm_unreachable("Expected 1, 2, 3 or 4 vectors!");
554 case 1:
555 return VTy;
556 case 2:
557 return llvm::StructType::get(VTy, VTy);
558 case 3:
559 return llvm::StructType::get(VTy, VTy, VTy);
560 case 4:
561 return llvm::StructType::get(VTy, VTy, VTy, VTy);
562 }
563 }
564 case BuiltinType::SveCount:
565 return llvm::TargetExtType::get(getLLVMContext(), "aarch64.svcount");
566 case BuiltinType::MFloat8:
567 return llvm::VectorType::get(llvm::Type::getInt8Ty(getLLVMContext()), 1,
568 false);
569#define PPC_VECTOR_TYPE(Name, Id, Size) \
570 case BuiltinType::Id: \
571 ResultType = \
572 llvm::FixedVectorType::get(ConvertType(Context.BoolTy), Size); \
573 break;
574#include "clang/Basic/PPCTypes.def"
575#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
576#include "clang/Basic/RISCVVTypes.def"
577 {
579 Context.getBuiltinVectorTypeInfo(cast<BuiltinType>(Ty));
580 if (Info.NumVectors != 1) {
581 unsigned I8EltCount =
582 Info.EC.getKnownMinValue() *
583 ConvertType(Info.ElementType)->getScalarSizeInBits() / 8;
584 return llvm::TargetExtType::get(
585 getLLVMContext(), "riscv.vector.tuple",
586 llvm::ScalableVectorType::get(
587 llvm::Type::getInt8Ty(getLLVMContext()), I8EltCount),
588 Info.NumVectors);
589 }
590 return llvm::ScalableVectorType::get(ConvertType(Info.ElementType),
591 Info.EC.getKnownMinValue());
592 }
593#define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \
594 case BuiltinType::Id: { \
595 if (BuiltinType::Id == BuiltinType::WasmExternRef) \
596 ResultType = CGM.getTargetCodeGenInfo().getWasmExternrefReferenceType(); \
597 else \
598 llvm_unreachable("Unexpected wasm reference builtin type!"); \
599 } break;
600#include "clang/Basic/WebAssemblyReferenceTypes.def"
601#define AMDGPU_OPAQUE_PTR_TYPE(Name, Id, SingletonId, Width, Align, AS) \
602 case BuiltinType::Id: \
603 return llvm::PointerType::get(getLLVMContext(), AS);
604#define AMDGPU_NAMED_BARRIER_TYPE(Name, Id, SingletonId, Width, Align, Scope) \
605 case BuiltinType::Id: \
606 return llvm::TargetExtType::get(getLLVMContext(), "amdgcn.named.barrier", \
607 {}, {Scope});
608#include "clang/Basic/AMDGPUTypes.def"
609#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
610#include "clang/Basic/HLSLIntangibleTypes.def"
611 ResultType = CGM.getHLSLRuntime().convertHLSLSpecificType(Ty);
612 break;
613 case BuiltinType::Dependent:
614#define BUILTIN_TYPE(Id, SingletonId)
615#define PLACEHOLDER_TYPE(Id, SingletonId) \
616 case BuiltinType::Id:
617#include "clang/AST/BuiltinTypes.def"
618 llvm_unreachable("Unexpected placeholder builtin type!");
619 }
620 break;
621 }
622 case Type::Auto:
623 case Type::DeducedTemplateSpecialization:
624 llvm_unreachable("Unexpected undeduced type!");
625 case Type::Complex: {
626 llvm::Type *EltTy = ConvertType(cast<ComplexType>(Ty)->getElementType());
627 ResultType = llvm::StructType::get(EltTy, EltTy);
628 break;
629 }
630 case Type::LValueReference:
631 case Type::RValueReference: {
632 const ReferenceType *RTy = cast<ReferenceType>(Ty);
633 QualType ETy = RTy->getPointeeType();
634 unsigned AS = getTargetAddressSpace(ETy);
635 ResultType = llvm::PointerType::get(getLLVMContext(), AS);
636 break;
637 }
638 case Type::Pointer: {
639 const PointerType *PTy = cast<PointerType>(Ty);
640 QualType ETy = PTy->getPointeeType();
641 unsigned AS = getTargetAddressSpace(ETy);
642 ResultType = llvm::PointerType::get(getLLVMContext(), AS);
643 break;
644 }
645
646 case Type::VariableArray: {
648 assert(A->getIndexTypeCVRQualifiers() == 0 &&
649 "FIXME: We only handle trivial array types so far!");
650 // VLAs resolve to the innermost element type; this matches
651 // the return of alloca, and there isn't any obviously better choice.
652 ResultType = ConvertTypeForMem(A->getElementType());
653 break;
654 }
655 case Type::IncompleteArray: {
657 assert(A->getIndexTypeCVRQualifiers() == 0 &&
658 "FIXME: We only handle trivial array types so far!");
659 // int X[] -> [0 x int], unless the element type is not sized. If it is
660 // unsized (e.g. an incomplete struct) just use [0 x i8].
661 ResultType = ConvertTypeForMem(A->getElementType());
662 if (!ResultType->isSized()) {
663 SkippedLayout = true;
664 ResultType = llvm::Type::getInt8Ty(getLLVMContext());
665 }
666 ResultType = llvm::ArrayType::get(ResultType, 0);
667 break;
668 }
669 case Type::ArrayParameter:
670 case Type::ConstantArray: {
672 llvm::Type *EltTy = ConvertTypeForMem(A->getElementType());
673
674 // Lower arrays of undefined struct type to arrays of i8 just to have a
675 // concrete type.
676 if (!EltTy->isSized()) {
677 SkippedLayout = true;
678 EltTy = llvm::Type::getInt8Ty(getLLVMContext());
679 }
680
681 ResultType = llvm::ArrayType::get(EltTy, A->getZExtSize());
682 break;
683 }
684 case Type::ExtVector:
685 case Type::Vector: {
686 const auto *VT = cast<VectorType>(Ty);
687 // An ext_vector_type of Bool is really a vector of bits.
688 llvm::Type *IRElemTy = VT->isPackedVectorBoolType(Context)
689 ? llvm::Type::getInt1Ty(getLLVMContext())
690 : VT->getElementType()->isMFloat8Type()
691 ? llvm::Type::getInt8Ty(getLLVMContext())
692 : ConvertType(VT->getElementType());
693 ResultType = llvm::FixedVectorType::get(IRElemTy, VT->getNumElements());
694 break;
695 }
696 case Type::ConstantMatrix: {
698 ResultType =
699 llvm::FixedVectorType::get(ConvertType(MT->getElementType()),
700 MT->getNumRows() * MT->getNumColumns());
701 break;
702 }
703 case Type::FunctionNoProto:
704 case Type::FunctionProto:
705 ResultType = ConvertFunctionTypeInternal(T);
706 break;
707 case Type::ObjCObject:
708 ResultType = ConvertType(cast<ObjCObjectType>(Ty)->getBaseType());
709 break;
710
711 case Type::ObjCInterface: {
712 // Objective-C interfaces are always opaque (outside of the
713 // runtime, which can do whatever it likes); we never refine
714 // these.
715 llvm::Type *&T = InterfaceTypes[cast<ObjCInterfaceType>(Ty)];
716 if (!T)
717 T = llvm::StructType::create(getLLVMContext());
718 ResultType = T;
719 break;
720 }
721
722 case Type::ObjCObjectPointer:
723 ResultType = llvm::PointerType::getUnqual(getLLVMContext());
724 break;
725
726 case Type::Enum: {
727 const auto *ED = Ty->castAsEnumDecl();
728 if (ED->isCompleteDefinition() || ED->isFixed())
729 return ConvertType(ED->getIntegerType());
730 // Return a placeholder 'i32' type. This can be changed later when the
731 // type is defined (see UpdateCompletedType), but is likely to be the
732 // "right" answer.
733 ResultType = llvm::Type::getInt32Ty(getLLVMContext());
734 break;
735 }
736
737 case Type::BlockPointer: {
738 // Block pointers lower to function type. For function type,
739 // getTargetAddressSpace() returns default address space for
740 // function pointer i.e. program address space. Therefore, for block
741 // pointers, it is important to pass the pointee AST address space when
742 // calling getTargetAddressSpace(), to ensure that we get the LLVM IR
743 // address space for data pointers and not function pointers.
744 const QualType FTy = cast<BlockPointerType>(Ty)->getPointeeType();
745 unsigned AS = Context.getTargetAddressSpace(FTy.getAddressSpace());
746 ResultType = llvm::PointerType::get(getLLVMContext(), AS);
747 break;
748 }
749
750 case Type::MemberPointer: {
751 auto *MPTy = cast<MemberPointerType>(Ty);
752 if (!getCXXABI().isMemberPointerConvertible(MPTy)) {
753 CanQualType T = CGM.getContext().getCanonicalTagType(
754 MPTy->getMostRecentCXXRecordDecl());
755 auto Insertion =
756 RecordsWithOpaqueMemberPointers.try_emplace(T.getTypePtr());
757 if (Insertion.second)
758 Insertion.first->second = llvm::StructType::create(getLLVMContext());
759 ResultType = Insertion.first->second;
760 } else {
761 ResultType = getCXXABI().ConvertMemberPointerType(MPTy);
762 }
763 break;
764 }
765
766 case Type::Atomic: {
767 QualType valueType = cast<AtomicType>(Ty)->getValueType();
768 ResultType = ConvertTypeForMem(valueType);
769
770 // Pad out to the inflated size if necessary.
771 uint64_t valueSize = Context.getTypeSize(valueType);
772 uint64_t atomicSize = Context.getTypeSize(Ty);
773 if (valueSize != atomicSize) {
774 assert(valueSize < atomicSize);
775 llvm::Type *elts[] = {
776 ResultType,
777 llvm::ArrayType::get(CGM.Int8Ty, (atomicSize - valueSize) / 8)
778 };
779 ResultType =
780 llvm::StructType::get(getLLVMContext(), llvm::ArrayRef(elts));
781 }
782 break;
783 }
784 case Type::Pipe: {
785 ResultType = CGM.getOpenCLRuntime().getPipeType(cast<PipeType>(Ty));
786 break;
787 }
788 case Type::BitInt: {
789 const auto &EIT = cast<BitIntType>(Ty);
790 ResultType = llvm::Type::getIntNTy(getLLVMContext(), EIT->getNumBits());
791 break;
792 }
793 case Type::HLSLAttributedResource:
794 case Type::HLSLInlineSpirv:
795 ResultType = CGM.getHLSLRuntime().convertHLSLSpecificType(Ty);
796 break;
797 case Type::OverflowBehavior:
798 ResultType =
799 ConvertType(dyn_cast<OverflowBehaviorType>(Ty)->getUnderlyingType());
800 break;
801 }
802
803 assert(ResultType && "Didn't convert a type?");
804 assert((!CachedType || CachedType == ResultType) &&
805 "Cached type doesn't match computed type");
806
807 TypeCache[Ty] = ResultType;
808 return ResultType;
809}
810
814
816 return Context.getTypeSize(type) != Context.getTypeSize(type->getValueType());
817}
818
819/// ConvertRecordDeclType - Lay out a tagged decl type like struct or union.
821 // TagDecl's are not necessarily unique, instead use the (clang)
822 // type connected to the decl.
823 const Type *Key = Context.getCanonicalTagType(RD).getTypePtr();
824
825 llvm::StructType *&Entry = RecordDeclTypes[Key];
826
827 // If we don't have a StructType at all yet, create the forward declaration.
828 if (!Entry) {
829 Entry = llvm::StructType::create(getLLVMContext());
830 addRecordTypeName(RD, Entry, "");
831 }
832 llvm::StructType *Ty = Entry;
833
834 // If this is still a forward declaration, or the LLVM type is already
835 // complete, there's nothing more to do.
836 RD = RD->getDefinition();
837 if (!RD || !RD->isCompleteDefinition() || !Ty->isOpaque())
838 return Ty;
839
840 // Force conversion of non-virtual base classes recursively.
841 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
842 for (const auto &I : CRD->bases()) {
843 if (I.isVirtual()) continue;
844 ConvertRecordDeclType(I.getType()->castAsRecordDecl());
845 }
846 }
847
848 // Layout fields.
849 std::unique_ptr<CGRecordLayout> Layout = ComputeRecordLayout(RD, Ty);
850 CGRecordLayouts[Key] = std::move(Layout);
851
852 // If this struct blocked a FunctionType conversion, then recompute whatever
853 // was derived from that.
854 // FIXME: This is hugely overconservative.
855 if (SkippedLayout)
856 TypeCache.clear();
857
858 return Ty;
859}
860
861/// getCGRecordLayout - Return record layout info for the given record decl.
862const CGRecordLayout &
864 const Type *Key = Context.getCanonicalTagType(RD).getTypePtr();
865
866 auto I = CGRecordLayouts.find(Key);
867 if (I != CGRecordLayouts.end())
868 return *I->second;
869 // Compute the type information.
871
872 // Now try again.
873 I = CGRecordLayouts.find(Key);
874
875 assert(I != CGRecordLayouts.end() &&
876 "Unable to find record layout information for type");
877 return *I->second;
878}
879
881 assert((T->isAnyPointerType() || T->isBlockPointerType() ||
882 T->isNullPtrType()) &&
883 "Invalid type");
884 return isZeroInitializable(T);
885}
886
888 if (T->getAs<PointerType>() || T->isNullPtrType())
889 return Context.getTargetNullPointerValue(T) == 0;
890
891 if (const auto *AT = Context.getAsArrayType(T)) {
893 return true;
894 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
895 if (Context.getConstantArrayElementCount(CAT) == 0)
896 return true;
897 T = Context.getBaseElementType(T);
898 }
899
900 // Records are non-zero-initializable if they contain any
901 // non-zero-initializable subobjects.
902 if (const auto *RD = T->getAsRecordDecl())
903 return isZeroInitializable(RD);
904
905 // We have to ask the ABI about member pointers.
906 if (const MemberPointerType *MPT = T->getAs<MemberPointerType>())
907 return getCXXABI().isZeroInitializable(MPT);
908
909 // HLSL Inline SPIR-V types are non-zero-initializable.
910 if (T->getAs<HLSLInlineSpirvType>())
911 return false;
912
913 // Everything else is okay.
914 return true;
915}
916
920
922 // Return the address space for the type. If the type is a
923 // function type without an address space qualifier, the
924 // program address space is used. Otherwise, the target picks
925 // the best address space based on the type information
926 return T->isFunctionType() && !T.hasAddressSpace()
927 ? getDataLayout().getProgramAddressSpace()
928 : getContext().getTargetAddressSpace(T.getAddressSpace());
929}
Defines the clang::ASTContext interface.
static llvm::Type * getTypeForFormat(llvm::LLVMContext &VMContext, const llvm::fltSemantics &format, bool UseNativeHalf=false)
static Decl::Kind getKind(const Decl *D)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
static QualType getUnderlyingType(const SubRegion *R)
static CharUnits getTypeAllocSize(CodeGenModule &CGM, llvm::Type *type)
const clang::PrintingPolicy & getPrintingPolicy() const
Definition ASTContext.h:850
unsigned getTargetAddressSpace(LangAS AS) const
QualType getElementType() const
Definition TypeBase.h:3742
unsigned getIndexTypeCVRQualifiers() const
Definition TypeBase.h:3752
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
static CanQual< T > CreateUnsafe(QualType Other)
Builds a canonical type from a QualType.
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:63
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
Implements C++ ABI-specific code generation functions.
Definition CGCXXABI.h:43
virtual bool isMemberPointerConvertible(const MemberPointerType *MPT) const
Return whether or not a member pointers type is convertible to an IR type.
Definition CGCXXABI.h:213
virtual llvm::Type * ConvertMemberPointerType(const MemberPointerType *MPT)
Find the LLVM type used to represent the given member pointer type.
Definition CGCXXABI.cpp:42
virtual bool isZeroInitializable(const MemberPointerType *MPT)
Return true if the given member pointer can be zero-initialized (in the C++ sense) with an LLVM zeroi...
Definition CGCXXABI.cpp:120
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
Definition CGDebugInfo.h:59
CGRecordLayout - This class handles struct and union layout info while lowering AST types to LLVM typ...
bool isZeroInitializable() const
Check whether this struct can be C++ zero-initialized with a zeroinitializer.
This class organizes the cross-function state that is used while generating LLVM code.
bool isPaddedAtomicType(QualType type)
CodeGenTypes(CodeGenModule &cgm)
llvm::Type * ConvertType(QualType T)
ConvertType - Convert type T into a llvm::Type.
CGCXXABI & getCXXABI() const
bool isPointerZeroInitializable(QualType T)
Check if the pointer type can be zero-initialized (in the C++ sense) with an LLVM zeroinitializer.
const CodeGenOptions & getCodeGenOpts() const
ASTContext & getContext() const
const CGFunctionInfo & arrangeFreeFunctionType(CanQual< FunctionProtoType > Ty)
Arrange the argument and result information for a value of the given freestanding function type.
Definition CGCall.cpp:252
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
Definition CGCall.cpp:1801
bool isFuncTypeConvertible(const FunctionType *FT)
isFuncTypeConvertible - Utility to check whether a function type can be converted to an LLVM type (i....
const TargetInfo & getTarget() const
std::unique_ptr< CGRecordLayout > ComputeRecordLayout(const RecordDecl *D, llvm::StructType *Ty)
Compute a new LLVM record layout object for the given record.
llvm::Type * convertTypeForLoadStore(QualType T, llvm::Type *LLVMTy=nullptr)
Given that T is a scalar type, return the IR type that should be used for load and store operations.
const CGRecordLayout & getCGRecordLayout(const RecordDecl *)
getCGRecordLayout - Return record layout info for the given record decl.
unsigned getTargetAddressSpace(QualType T) const
llvm::StructType * ConvertRecordDeclType(const RecordDecl *TD)
ConvertRecordDeclType - Lay out a tagged decl type like struct or union.
void RefreshTypeCacheForClass(const CXXRecordDecl *RD)
Remove stale types from the type cache when an inheritance model gets assigned to a class.
bool isRecordLayoutComplete(const Type *Ty) const
isRecordLayoutComplete - Return true if the specified type is already completely laid out.
llvm::Type * ConvertTypeForMem(QualType T)
ConvertTypeForMem - Convert type T into a llvm::Type.
CodeGenModule & getCGM() const
void UpdateCompletedType(const TagDecl *TD)
UpdateCompletedType - When we find the full definition for a TagDecl, replace the 'opaque' type we pr...
llvm::LLVMContext & getLLVMContext()
bool typeRequiresSplitIntoByteArray(QualType ASTTy, llvm::Type *LLVMTy=nullptr)
Check whether the given type needs to be laid out in memory using an opaque byte-array type because i...
const llvm::DataLayout & getDataLayout() const
bool isFuncParamTypeConvertible(QualType Ty)
isFuncParamTypeConvertible - Return true if the specified type in a function parameter or result posi...
bool isZeroInitializable(QualType T)
IsZeroInitializable - Return whether a type can be zero-initialized (in the C++ sense) with an LLVM z...
void addRecordTypeName(const RecordDecl *RD, llvm::StructType *Ty, StringRef suffix)
addRecordTypeName - Compute a name from the given record decl with an optional suffix and name the gi...
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3768
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3844
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4395
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4414
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4411
unsigned getNumElementsFlattened() const
Returns the number of elements required to embed the matrix into a vector.
Definition TypeBase.h:4417
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:546
DeclContext * getDeclContext()
Definition DeclBase.h:448
Represents an enum.
Definition Decl.h:4013
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5315
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4511
QualType getReturnType() const
Definition TypeBase.h:4851
Represents a C array with an unspecified size.
Definition TypeBase.h:3917
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4359
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3661
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
void printQualifiedName(raw_ostream &OS) const
Returns a human-readable qualified name for this declaration, like A::B::i, for i being member of nam...
Definition Decl.cpp:1687
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3336
QualType getPointeeType() const
Definition TypeBase.h:3346
A (possibly-)qualified type.
Definition TypeBase.h:937
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8388
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8514
bool isCanonical() const
Definition TypeBase.h:8445
Represents a struct/union/class.
Definition Decl.h:4327
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4511
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3581
QualType getPointeeType() const
Definition TypeBase.h:3599
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3717
StringRef getKindName() const
Definition Decl.h:3913
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3818
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition Decl.h:3954
void printName(raw_ostream &OS, const PrintingPolicy &Policy) const override
Pretty-print the unqualified name of this declaration.
Definition Decl.cpp:5029
bool isDependentType() const
Whether this declaration declares a type that is dependent, i.e., a type that somehow depends on temp...
Definition Decl.h:3863
bool isMFloat8Type() const
Definition TypeBase.h:9016
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
EnumDecl * castAsEnumDecl() const
Definition Type.h:59
TypeClass getTypeClass() const
Definition TypeBase.h:2391
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9218
bool isNullPtrType() const
Definition TypeBase.h:9028
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3562
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:3974
@ Type
The l-value was considered opaque, so the alignment was determined from a type.
Definition CGValue.h:155
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isa(CodeGen::Address addr)
Definition Address.h:330
U cast(CodeGen::Address addr)
Definition Address.h:327
Describes how types, statements, expressions, and declarations should be printed.
unsigned SuppressInlineNamespace
Suppress printing parts of scope specifiers that correspond to inline namespaces.