clang 22.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 && T->isConstantMatrixBoolType())
109 IRElemTy = ConvertTypeForMem(Context.BoolTy);
110 return llvm::ArrayType::get(IRElemTy,
111 MT->getNumRows() * MT->getNumColumns());
112 }
113
114 llvm::Type *R = ConvertType(T);
115
116 // Check for the boolean vector case.
117 if (T->isExtVectorBoolType()) {
118 auto *FixedVT = cast<llvm::FixedVectorType>(R);
119
120 if (Context.getLangOpts().HLSL) {
121 llvm::Type *IRElemTy = ConvertTypeForMem(Context.BoolTy);
122 return llvm::FixedVectorType::get(IRElemTy, FixedVT->getNumElements());
123 }
124
125 // Pad to at least one byte.
126 uint64_t BytePadded = std::max<uint64_t>(FixedVT->getNumElements(), 8);
127 return llvm::IntegerType::get(FixedVT->getContext(), BytePadded);
128 }
129
130 // If T is _Bool or a _BitInt type, ConvertType will produce an IR type
131 // with the exact semantic bit-width of the AST type; for example,
132 // _BitInt(17) will turn into i17. In memory, however, we need to store
133 // such values extended to their full storage size as decided by AST
134 // layout; this is an ABI requirement. Ideally, we would always use an
135 // integer type that's just the bit-size of the AST type; for example, if
136 // sizeof(_BitInt(17)) == 4, _BitInt(17) would turn into i32. That is what's
137 // returned by convertTypeForLoadStore. However, that type does not
138 // always satisfy the size requirement on memory representation types
139 // describe above. For example, a 32-bit platform might reasonably set
140 // sizeof(_BitInt(65)) == 12, but i96 is likely to have to have an alloc size
141 // of 16 bytes in the LLVM data layout. In these cases, we simply return
142 // a byte array of the appropriate size.
143 if (T->isBitIntType()) {
145 return llvm::ArrayType::get(CGM.Int8Ty,
146 Context.getTypeSizeInChars(T).getQuantity());
147 return llvm::IntegerType::get(getLLVMContext(),
148 (unsigned)Context.getTypeSize(T));
149 }
150
151 if (R->isIntegerTy(1))
152 return llvm::IntegerType::get(getLLVMContext(),
153 (unsigned)Context.getTypeSize(T));
154
155 // Else, don't map it.
156 return R;
157}
158
160 llvm::Type *LLVMTy) {
161 if (!LLVMTy)
162 LLVMTy = ConvertType(ASTTy);
163
164 CharUnits ASTSize = Context.getTypeSizeInChars(ASTTy);
165 CharUnits LLVMSize =
167 return ASTSize != LLVMSize;
168}
169
171 llvm::Type *LLVMTy) {
172 if (!LLVMTy)
173 LLVMTy = ConvertType(T);
174
175 if (T->isBitIntType())
176 return llvm::Type::getIntNTy(
177 getLLVMContext(), Context.getTypeSizeInChars(T).getQuantity() * 8);
178
179 if (LLVMTy->isIntegerTy(1))
180 return llvm::IntegerType::get(getLLVMContext(),
181 (unsigned)Context.getTypeSize(T));
182
183 if (T->isExtVectorBoolType())
184 return ConvertTypeForMem(T);
185
186 return LLVMTy;
187}
188
189/// isRecordLayoutComplete - Return true if the specified type is already
190/// completely laid out.
192 llvm::DenseMap<const Type*, llvm::StructType *>::const_iterator I =
193 RecordDeclTypes.find(Ty);
194 return I != RecordDeclTypes.end() && !I->second->isOpaque();
195}
196
197/// isFuncParamTypeConvertible - Return true if the specified type in a
198/// function parameter or result position can be converted to an IR type at this
199/// point. This boils down to being whether it is complete.
201 // Some ABIs cannot have their member pointers represented in IR unless
202 // certain circumstances have been reached.
203 if (const auto *MPT = Ty->getAs<MemberPointerType>())
205
206 // If this isn't a tagged type, we can convert it!
207 const TagType *TT = Ty->getAs<TagType>();
208 if (!TT) return true;
209
210 // Incomplete types cannot be converted.
211 return !TT->isIncompleteType();
212}
213
214
215/// Code to verify a given function type is complete, i.e. the return type
216/// and all of the parameter types are complete. Also check to see if we are in
217/// a RS_StructPointer context, and if so whether any struct types have been
218/// pended. If so, we don't want to ask the ABI lowering code to handle a type
219/// that cannot be converted to an IR type.
222 return false;
223
224 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT))
225 for (unsigned i = 0, e = FPT->getNumParams(); i != e; i++)
226 if (!isFuncParamTypeConvertible(FPT->getParamType(i)))
227 return false;
228
229 return true;
230}
231
232/// UpdateCompletedType - When we find the full definition for a TagDecl,
233/// replace the 'opaque' type we previously made for it if applicable.
235 CanQualType T = CGM.getContext().getCanonicalTagType(TD);
236 // If this is an enum being completed, then we flush all non-struct types from
237 // the cache. This allows function types and other things that may be derived
238 // from the enum to be recomputed.
239 if (const EnumDecl *ED = dyn_cast<EnumDecl>(TD)) {
240 // Only flush the cache if we've actually already converted this type.
241 if (TypeCache.count(T->getTypePtr())) {
242 // Okay, we formed some types based on this. We speculated that the enum
243 // would be lowered to i32, so we only need to flush the cache if this
244 // didn't happen.
245 if (!ConvertType(ED->getIntegerType())->isIntegerTy(32))
246 TypeCache.clear();
247 }
248 // If necessary, provide the full definition of a type only used with a
249 // declaration so far.
250 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
251 DI->completeType(ED);
252 return;
253 }
254
255 // If we completed a RecordDecl that we previously used and converted to an
256 // anonymous type, then go ahead and complete it now.
257 const RecordDecl *RD = cast<RecordDecl>(TD);
258 if (RD->isDependentType()) return;
259
260 // Only complete it if we converted it already. If we haven't converted it
261 // yet, we'll just do it lazily.
262 if (RecordDeclTypes.count(T.getTypePtr()))
264
265 // If necessary, provide the full definition of a type only used with a
266 // declaration so far.
267 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
268 DI->completeType(RD);
269}
270
272 CanQualType T = Context.getCanonicalTagType(RD);
273 T = Context.getCanonicalType(T);
274
275 const Type *Ty = T.getTypePtr();
276 if (RecordsWithOpaqueMemberPointers.count(Ty)) {
277 TypeCache.clear();
278 RecordsWithOpaqueMemberPointers.clear();
279 }
280}
281
282static llvm::Type *getTypeForFormat(llvm::LLVMContext &VMContext,
283 const llvm::fltSemantics &format,
284 bool UseNativeHalf = false) {
285 if (&format == &llvm::APFloat::IEEEhalf()) {
286 if (UseNativeHalf)
287 return llvm::Type::getHalfTy(VMContext);
288 else
289 return llvm::Type::getInt16Ty(VMContext);
290 }
291 if (&format == &llvm::APFloat::BFloat())
292 return llvm::Type::getBFloatTy(VMContext);
293 if (&format == &llvm::APFloat::IEEEsingle())
294 return llvm::Type::getFloatTy(VMContext);
295 if (&format == &llvm::APFloat::IEEEdouble())
296 return llvm::Type::getDoubleTy(VMContext);
297 if (&format == &llvm::APFloat::IEEEquad())
298 return llvm::Type::getFP128Ty(VMContext);
299 if (&format == &llvm::APFloat::PPCDoubleDouble())
300 return llvm::Type::getPPC_FP128Ty(VMContext);
301 if (&format == &llvm::APFloat::x87DoubleExtended())
302 return llvm::Type::getX86_FP80Ty(VMContext);
303 llvm_unreachable("Unknown float format!");
304}
305
306llvm::Type *CodeGenTypes::ConvertFunctionTypeInternal(QualType QFT) {
307 assert(QFT.isCanonical());
308 const FunctionType *FT = cast<FunctionType>(QFT.getTypePtr());
309 // First, check whether we can build the full function type. If the
310 // function type depends on an incomplete type (e.g. a struct or enum), we
311 // cannot lower the function type.
312 if (!isFuncTypeConvertible(FT)) {
313 // This function's type depends on an incomplete tag type.
314
315 // Force conversion of all the relevant record types, to make sure
316 // we re-convert the FunctionType when appropriate.
317 if (const auto *RD = FT->getReturnType()->getAsRecordDecl())
319 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT))
320 for (unsigned i = 0, e = FPT->getNumParams(); i != e; i++)
321 if (const auto *RD = FPT->getParamType(i)->getAsRecordDecl())
323
324 SkippedLayout = true;
325
326 // Return a placeholder type.
327 return llvm::StructType::get(getLLVMContext());
328 }
329
330 // The function type can be built; call the appropriate routines to
331 // build it.
332 const CGFunctionInfo *FI;
333 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
336 } else {
337 const FunctionNoProtoType *FNPT = cast<FunctionNoProtoType>(FT);
340 }
341
342 llvm::Type *ResultType = nullptr;
343 // If there is something higher level prodding our CGFunctionInfo, then
344 // don't recurse into it again.
345 if (FunctionsBeingProcessed.count(FI)) {
346
347 ResultType = llvm::StructType::get(getLLVMContext());
348 SkippedLayout = true;
349 } else {
350
351 // Otherwise, we're good to go, go ahead and convert it.
352 ResultType = GetFunctionType(*FI);
353 }
354
355 return ResultType;
356}
357
358/// ConvertType - Convert the specified type to its LLVM form.
360 T = Context.getCanonicalType(T);
361
362 const Type *Ty = T.getTypePtr();
363
364 // For the device-side compilation, CUDA device builtin surface/texture types
365 // may be represented in different types.
366 if (Context.getLangOpts().CUDAIsDevice) {
367 if (T->isCUDADeviceBuiltinSurfaceType()) {
368 if (auto *Ty = CGM.getTargetCodeGenInfo()
369 .getCUDADeviceBuiltinSurfaceDeviceType())
370 return Ty;
371 } else if (T->isCUDADeviceBuiltinTextureType()) {
372 if (auto *Ty = CGM.getTargetCodeGenInfo()
373 .getCUDADeviceBuiltinTextureDeviceType())
374 return Ty;
375 }
376 }
377
378 // RecordTypes are cached and processed specially.
379 if (const auto *RT = dyn_cast<RecordType>(Ty))
380 return ConvertRecordDeclType(RT->getDecl()->getDefinitionOrSelf());
381
382 llvm::Type *CachedType = nullptr;
383 auto TCI = TypeCache.find(Ty);
384 if (TCI != TypeCache.end())
385 CachedType = TCI->second;
386 // With expensive checks, check that the type we compute matches the
387 // cached type.
388#ifndef EXPENSIVE_CHECKS
389 if (CachedType)
390 return CachedType;
391#endif
392
393 // If we don't have it in the cache, convert it now.
394 llvm::Type *ResultType = nullptr;
395 switch (Ty->getTypeClass()) {
396 case Type::Record: // Handled above.
397#define TYPE(Class, Base)
398#define ABSTRACT_TYPE(Class, Base)
399#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
400#define DEPENDENT_TYPE(Class, Base) case Type::Class:
401#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
402#include "clang/AST/TypeNodes.inc"
403 llvm_unreachable("Non-canonical or dependent types aren't possible.");
404
405 case Type::Builtin: {
406 switch (cast<BuiltinType>(Ty)->getKind()) {
407 case BuiltinType::Void:
408 case BuiltinType::ObjCId:
409 case BuiltinType::ObjCClass:
410 case BuiltinType::ObjCSel:
411 // LLVM void type can only be used as the result of a function call. Just
412 // map to the same as char.
413 ResultType = llvm::Type::getInt8Ty(getLLVMContext());
414 break;
415
416 case BuiltinType::Bool:
417 // Note that we always return bool as i1 for use as a scalar type.
418 ResultType = llvm::Type::getInt1Ty(getLLVMContext());
419 break;
420
421 case BuiltinType::Char_S:
422 case BuiltinType::Char_U:
423 case BuiltinType::SChar:
424 case BuiltinType::UChar:
425 case BuiltinType::Short:
426 case BuiltinType::UShort:
427 case BuiltinType::Int:
428 case BuiltinType::UInt:
429 case BuiltinType::Long:
430 case BuiltinType::ULong:
431 case BuiltinType::LongLong:
432 case BuiltinType::ULongLong:
433 case BuiltinType::WChar_S:
434 case BuiltinType::WChar_U:
435 case BuiltinType::Char8:
436 case BuiltinType::Char16:
437 case BuiltinType::Char32:
438 case BuiltinType::ShortAccum:
439 case BuiltinType::Accum:
440 case BuiltinType::LongAccum:
441 case BuiltinType::UShortAccum:
442 case BuiltinType::UAccum:
443 case BuiltinType::ULongAccum:
444 case BuiltinType::ShortFract:
445 case BuiltinType::Fract:
446 case BuiltinType::LongFract:
447 case BuiltinType::UShortFract:
448 case BuiltinType::UFract:
449 case BuiltinType::ULongFract:
450 case BuiltinType::SatShortAccum:
451 case BuiltinType::SatAccum:
452 case BuiltinType::SatLongAccum:
453 case BuiltinType::SatUShortAccum:
454 case BuiltinType::SatUAccum:
455 case BuiltinType::SatULongAccum:
456 case BuiltinType::SatShortFract:
457 case BuiltinType::SatFract:
458 case BuiltinType::SatLongFract:
459 case BuiltinType::SatUShortFract:
460 case BuiltinType::SatUFract:
461 case BuiltinType::SatULongFract:
462 ResultType = llvm::IntegerType::get(getLLVMContext(),
463 static_cast<unsigned>(Context.getTypeSize(T)));
464 break;
465
466 case BuiltinType::Float16:
467 ResultType =
468 getTypeForFormat(getLLVMContext(), Context.getFloatTypeSemantics(T),
469 /* UseNativeHalf = */ true);
470 break;
471
472 case BuiltinType::Half:
473 // Half FP can either be storage-only (lowered to i16) or native.
474 ResultType = getTypeForFormat(
475 getLLVMContext(), Context.getFloatTypeSemantics(T),
476 Context.getLangOpts().NativeHalfType ||
477 !Context.getTargetInfo().useFP16ConversionIntrinsics());
478 break;
479 case BuiltinType::LongDouble:
480 LongDoubleReferenced = true;
481 [[fallthrough]];
482 case BuiltinType::BFloat16:
483 case BuiltinType::Float:
484 case BuiltinType::Double:
485 case BuiltinType::Float128:
486 case BuiltinType::Ibm128:
487 ResultType = getTypeForFormat(getLLVMContext(),
488 Context.getFloatTypeSemantics(T),
489 /* UseNativeHalf = */ false);
490 break;
491
492 case BuiltinType::NullPtr:
493 // Model std::nullptr_t as i8*
494 ResultType = llvm::PointerType::getUnqual(getLLVMContext());
495 break;
496
497 case BuiltinType::UInt128:
498 case BuiltinType::Int128:
499 ResultType = llvm::IntegerType::get(getLLVMContext(), 128);
500 break;
501
502#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
503 case BuiltinType::Id:
504#include "clang/Basic/OpenCLImageTypes.def"
505#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
506 case BuiltinType::Id:
507#include "clang/Basic/OpenCLExtensionTypes.def"
508 case BuiltinType::OCLSampler:
509 case BuiltinType::OCLEvent:
510 case BuiltinType::OCLClkEvent:
511 case BuiltinType::OCLQueue:
512 case BuiltinType::OCLReserveID:
513 ResultType = CGM.getOpenCLRuntime().convertOpenCLSpecificType(Ty);
514 break;
515#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId) \
516 case BuiltinType::Id:
517#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId) \
518 case BuiltinType::Id:
519#include "clang/Basic/AArch64ACLETypes.def"
520 {
522 Context.getBuiltinVectorTypeInfo(cast<BuiltinType>(Ty));
523 // The `__mfp8` type maps to `<1 x i8>` which can't be used to build
524 // a <N x i8> vector type, hence bypass the call to `ConvertType` for
525 // the element type and create the vector type directly.
526 auto *EltTy = Info.ElementType->isMFloat8Type()
527 ? llvm::Type::getInt8Ty(getLLVMContext())
528 : ConvertType(Info.ElementType);
529 auto *VTy = llvm::VectorType::get(EltTy, Info.EC);
530 switch (Info.NumVectors) {
531 default:
532 llvm_unreachable("Expected 1, 2, 3 or 4 vectors!");
533 case 1:
534 return VTy;
535 case 2:
536 return llvm::StructType::get(VTy, VTy);
537 case 3:
538 return llvm::StructType::get(VTy, VTy, VTy);
539 case 4:
540 return llvm::StructType::get(VTy, VTy, VTy, VTy);
541 }
542 }
543 case BuiltinType::SveCount:
544 return llvm::TargetExtType::get(getLLVMContext(), "aarch64.svcount");
545 case BuiltinType::MFloat8:
546 return llvm::VectorType::get(llvm::Type::getInt8Ty(getLLVMContext()), 1,
547 false);
548#define PPC_VECTOR_TYPE(Name, Id, Size) \
549 case BuiltinType::Id: \
550 ResultType = \
551 llvm::FixedVectorType::get(ConvertType(Context.BoolTy), Size); \
552 break;
553#include "clang/Basic/PPCTypes.def"
554#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
555#include "clang/Basic/RISCVVTypes.def"
556 {
558 Context.getBuiltinVectorTypeInfo(cast<BuiltinType>(Ty));
559 if (Info.NumVectors != 1) {
560 unsigned I8EltCount =
561 Info.EC.getKnownMinValue() *
562 ConvertType(Info.ElementType)->getScalarSizeInBits() / 8;
563 return llvm::TargetExtType::get(
564 getLLVMContext(), "riscv.vector.tuple",
565 llvm::ScalableVectorType::get(
566 llvm::Type::getInt8Ty(getLLVMContext()), I8EltCount),
567 Info.NumVectors);
568 }
569 return llvm::ScalableVectorType::get(ConvertType(Info.ElementType),
570 Info.EC.getKnownMinValue());
571 }
572#define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \
573 case BuiltinType::Id: { \
574 if (BuiltinType::Id == BuiltinType::WasmExternRef) \
575 ResultType = CGM.getTargetCodeGenInfo().getWasmExternrefReferenceType(); \
576 else \
577 llvm_unreachable("Unexpected wasm reference builtin type!"); \
578 } break;
579#include "clang/Basic/WebAssemblyReferenceTypes.def"
580#define AMDGPU_OPAQUE_PTR_TYPE(Name, Id, SingletonId, Width, Align, AS) \
581 case BuiltinType::Id: \
582 return llvm::PointerType::get(getLLVMContext(), AS);
583#define AMDGPU_NAMED_BARRIER_TYPE(Name, Id, SingletonId, Width, Align, Scope) \
584 case BuiltinType::Id: \
585 return llvm::TargetExtType::get(getLLVMContext(), "amdgcn.named.barrier", \
586 {}, {Scope});
587#include "clang/Basic/AMDGPUTypes.def"
588#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
589#include "clang/Basic/HLSLIntangibleTypes.def"
590 ResultType = CGM.getHLSLRuntime().convertHLSLSpecificType(Ty);
591 break;
592 case BuiltinType::Dependent:
593#define BUILTIN_TYPE(Id, SingletonId)
594#define PLACEHOLDER_TYPE(Id, SingletonId) \
595 case BuiltinType::Id:
596#include "clang/AST/BuiltinTypes.def"
597 llvm_unreachable("Unexpected placeholder builtin type!");
598 }
599 break;
600 }
601 case Type::Auto:
602 case Type::DeducedTemplateSpecialization:
603 llvm_unreachable("Unexpected undeduced type!");
604 case Type::Complex: {
605 llvm::Type *EltTy = ConvertType(cast<ComplexType>(Ty)->getElementType());
606 ResultType = llvm::StructType::get(EltTy, EltTy);
607 break;
608 }
609 case Type::LValueReference:
610 case Type::RValueReference: {
611 const ReferenceType *RTy = cast<ReferenceType>(Ty);
612 QualType ETy = RTy->getPointeeType();
613 unsigned AS = getTargetAddressSpace(ETy);
614 ResultType = llvm::PointerType::get(getLLVMContext(), AS);
615 break;
616 }
617 case Type::Pointer: {
618 const PointerType *PTy = cast<PointerType>(Ty);
619 QualType ETy = PTy->getPointeeType();
620 unsigned AS = getTargetAddressSpace(ETy);
621 ResultType = llvm::PointerType::get(getLLVMContext(), AS);
622 break;
623 }
624
625 case Type::VariableArray: {
627 assert(A->getIndexTypeCVRQualifiers() == 0 &&
628 "FIXME: We only handle trivial array types so far!");
629 // VLAs resolve to the innermost element type; this matches
630 // the return of alloca, and there isn't any obviously better choice.
631 ResultType = ConvertTypeForMem(A->getElementType());
632 break;
633 }
634 case Type::IncompleteArray: {
636 assert(A->getIndexTypeCVRQualifiers() == 0 &&
637 "FIXME: We only handle trivial array types so far!");
638 // int X[] -> [0 x int], unless the element type is not sized. If it is
639 // unsized (e.g. an incomplete struct) just use [0 x i8].
640 ResultType = ConvertTypeForMem(A->getElementType());
641 if (!ResultType->isSized()) {
642 SkippedLayout = true;
643 ResultType = llvm::Type::getInt8Ty(getLLVMContext());
644 }
645 ResultType = llvm::ArrayType::get(ResultType, 0);
646 break;
647 }
648 case Type::ArrayParameter:
649 case Type::ConstantArray: {
651 llvm::Type *EltTy = ConvertTypeForMem(A->getElementType());
652
653 // Lower arrays of undefined struct type to arrays of i8 just to have a
654 // concrete type.
655 if (!EltTy->isSized()) {
656 SkippedLayout = true;
657 EltTy = llvm::Type::getInt8Ty(getLLVMContext());
658 }
659
660 ResultType = llvm::ArrayType::get(EltTy, A->getZExtSize());
661 break;
662 }
663 case Type::ExtVector:
664 case Type::Vector: {
665 const auto *VT = cast<VectorType>(Ty);
666 // An ext_vector_type of Bool is really a vector of bits.
667 llvm::Type *IRElemTy = VT->isPackedVectorBoolType(Context)
668 ? llvm::Type::getInt1Ty(getLLVMContext())
669 : VT->getElementType()->isMFloat8Type()
670 ? llvm::Type::getInt8Ty(getLLVMContext())
671 : ConvertType(VT->getElementType());
672 ResultType = llvm::FixedVectorType::get(IRElemTy, VT->getNumElements());
673 break;
674 }
675 case Type::ConstantMatrix: {
677 ResultType =
678 llvm::FixedVectorType::get(ConvertType(MT->getElementType()),
679 MT->getNumRows() * MT->getNumColumns());
680 break;
681 }
682 case Type::FunctionNoProto:
683 case Type::FunctionProto:
684 ResultType = ConvertFunctionTypeInternal(T);
685 break;
686 case Type::ObjCObject:
687 ResultType = ConvertType(cast<ObjCObjectType>(Ty)->getBaseType());
688 break;
689
690 case Type::ObjCInterface: {
691 // Objective-C interfaces are always opaque (outside of the
692 // runtime, which can do whatever it likes); we never refine
693 // these.
694 llvm::Type *&T = InterfaceTypes[cast<ObjCInterfaceType>(Ty)];
695 if (!T)
696 T = llvm::StructType::create(getLLVMContext());
697 ResultType = T;
698 break;
699 }
700
701 case Type::ObjCObjectPointer:
702 ResultType = llvm::PointerType::getUnqual(getLLVMContext());
703 break;
704
705 case Type::Enum: {
706 const auto *ED = Ty->castAsEnumDecl();
707 if (ED->isCompleteDefinition() || ED->isFixed())
708 return ConvertType(ED->getIntegerType());
709 // Return a placeholder 'i32' type. This can be changed later when the
710 // type is defined (see UpdateCompletedType), but is likely to be the
711 // "right" answer.
712 ResultType = llvm::Type::getInt32Ty(getLLVMContext());
713 break;
714 }
715
716 case Type::BlockPointer: {
717 // Block pointers lower to function type. For function type,
718 // getTargetAddressSpace() returns default address space for
719 // function pointer i.e. program address space. Therefore, for block
720 // pointers, it is important to pass the pointee AST address space when
721 // calling getTargetAddressSpace(), to ensure that we get the LLVM IR
722 // address space for data pointers and not function pointers.
723 const QualType FTy = cast<BlockPointerType>(Ty)->getPointeeType();
724 unsigned AS = Context.getTargetAddressSpace(FTy.getAddressSpace());
725 ResultType = llvm::PointerType::get(getLLVMContext(), AS);
726 break;
727 }
728
729 case Type::MemberPointer: {
730 auto *MPTy = cast<MemberPointerType>(Ty);
731 if (!getCXXABI().isMemberPointerConvertible(MPTy)) {
732 CanQualType T = CGM.getContext().getCanonicalTagType(
733 MPTy->getMostRecentCXXRecordDecl());
734 auto Insertion =
735 RecordsWithOpaqueMemberPointers.try_emplace(T.getTypePtr());
736 if (Insertion.second)
737 Insertion.first->second = llvm::StructType::create(getLLVMContext());
738 ResultType = Insertion.first->second;
739 } else {
740 ResultType = getCXXABI().ConvertMemberPointerType(MPTy);
741 }
742 break;
743 }
744
745 case Type::Atomic: {
746 QualType valueType = cast<AtomicType>(Ty)->getValueType();
747 ResultType = ConvertTypeForMem(valueType);
748
749 // Pad out to the inflated size if necessary.
750 uint64_t valueSize = Context.getTypeSize(valueType);
751 uint64_t atomicSize = Context.getTypeSize(Ty);
752 if (valueSize != atomicSize) {
753 assert(valueSize < atomicSize);
754 llvm::Type *elts[] = {
755 ResultType,
756 llvm::ArrayType::get(CGM.Int8Ty, (atomicSize - valueSize) / 8)
757 };
758 ResultType =
759 llvm::StructType::get(getLLVMContext(), llvm::ArrayRef(elts));
760 }
761 break;
762 }
763 case Type::Pipe: {
764 ResultType = CGM.getOpenCLRuntime().getPipeType(cast<PipeType>(Ty));
765 break;
766 }
767 case Type::BitInt: {
768 const auto &EIT = cast<BitIntType>(Ty);
769 ResultType = llvm::Type::getIntNTy(getLLVMContext(), EIT->getNumBits());
770 break;
771 }
772 case Type::HLSLAttributedResource:
773 case Type::HLSLInlineSpirv:
774 ResultType = CGM.getHLSLRuntime().convertHLSLSpecificType(Ty);
775 break;
776 }
777
778 assert(ResultType && "Didn't convert a type?");
779 assert((!CachedType || CachedType == ResultType) &&
780 "Cached type doesn't match computed type");
781
782 TypeCache[Ty] = ResultType;
783 return ResultType;
784}
785
789
791 return Context.getTypeSize(type) != Context.getTypeSize(type->getValueType());
792}
793
794/// ConvertRecordDeclType - Lay out a tagged decl type like struct or union.
796 // TagDecl's are not necessarily unique, instead use the (clang)
797 // type connected to the decl.
798 const Type *Key = Context.getCanonicalTagType(RD).getTypePtr();
799
800 llvm::StructType *&Entry = RecordDeclTypes[Key];
801
802 // If we don't have a StructType at all yet, create the forward declaration.
803 if (!Entry) {
804 Entry = llvm::StructType::create(getLLVMContext());
805 addRecordTypeName(RD, Entry, "");
806 }
807 llvm::StructType *Ty = Entry;
808
809 // If this is still a forward declaration, or the LLVM type is already
810 // complete, there's nothing more to do.
811 RD = RD->getDefinition();
812 if (!RD || !RD->isCompleteDefinition() || !Ty->isOpaque())
813 return Ty;
814
815 // Force conversion of non-virtual base classes recursively.
816 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
817 for (const auto &I : CRD->bases()) {
818 if (I.isVirtual()) continue;
819 ConvertRecordDeclType(I.getType()->castAsRecordDecl());
820 }
821 }
822
823 // Layout fields.
824 std::unique_ptr<CGRecordLayout> Layout = ComputeRecordLayout(RD, Ty);
825 CGRecordLayouts[Key] = std::move(Layout);
826
827 // If this struct blocked a FunctionType conversion, then recompute whatever
828 // was derived from that.
829 // FIXME: This is hugely overconservative.
830 if (SkippedLayout)
831 TypeCache.clear();
832
833 return Ty;
834}
835
836/// getCGRecordLayout - Return record layout info for the given record decl.
837const CGRecordLayout &
839 const Type *Key = Context.getCanonicalTagType(RD).getTypePtr();
840
841 auto I = CGRecordLayouts.find(Key);
842 if (I != CGRecordLayouts.end())
843 return *I->second;
844 // Compute the type information.
846
847 // Now try again.
848 I = CGRecordLayouts.find(Key);
849
850 assert(I != CGRecordLayouts.end() &&
851 "Unable to find record layout information for type");
852 return *I->second;
853}
854
856 assert((T->isAnyPointerType() || T->isBlockPointerType() ||
857 T->isNullPtrType()) &&
858 "Invalid type");
859 return isZeroInitializable(T);
860}
861
863 if (T->getAs<PointerType>() || T->isNullPtrType())
864 return Context.getTargetNullPointerValue(T) == 0;
865
866 if (const auto *AT = Context.getAsArrayType(T)) {
868 return true;
869 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
870 if (Context.getConstantArrayElementCount(CAT) == 0)
871 return true;
872 T = Context.getBaseElementType(T);
873 }
874
875 // Records are non-zero-initializable if they contain any
876 // non-zero-initializable subobjects.
877 if (const auto *RD = T->getAsRecordDecl())
878 return isZeroInitializable(RD);
879
880 // We have to ask the ABI about member pointers.
881 if (const MemberPointerType *MPT = T->getAs<MemberPointerType>())
882 return getCXXABI().isZeroInitializable(MPT);
883
884 // HLSL Inline SPIR-V types are non-zero-initializable.
885 if (T->getAs<HLSLInlineSpirvType>())
886 return false;
887
888 // Everything else is okay.
889 return true;
890}
891
895
897 // Return the address space for the type. If the type is a
898 // function type without an address space qualifier, the
899 // program address space is used. Otherwise, the target picks
900 // the best address space based on the type information
901 return T->isFunctionType() && !T.hasAddressSpace()
902 ? getDataLayout().getProgramAddressSpace()
903 : getContext().getTargetAddressSpace(T.getAddressSpace());
904}
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 CharUnits getTypeAllocSize(CodeGenModule &CGM, llvm::Type *type)
const clang::PrintingPolicy & getPrintingPolicy() const
Definition ASTContext.h:843
unsigned getTargetAddressSpace(LangAS AS) const
QualType getElementType() const
Definition TypeBase.h:3735
unsigned getIndexTypeCVRQualifiers() const
Definition TypeBase.h:3745
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:43
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:121
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:250
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
Definition CGCall.cpp:1702
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:3761
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3837
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4388
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4407
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4404
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:546
DeclContext * getDeclContext()
Definition DeclBase.h:448
Represents an enum.
Definition Decl.h:4007
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5269
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4465
QualType getReturnType() const
Definition TypeBase.h:4805
Represents a C array with an unspecified size.
Definition TypeBase.h:3910
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4352
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3654
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:3329
QualType getPointeeType() const
Definition TypeBase.h:3339
A (possibly-)qualified type.
Definition TypeBase.h:937
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8293
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8419
bool isCanonical() const
Definition TypeBase.h:8350
Represents a struct/union/class.
Definition Decl.h:4321
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4505
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3574
QualType getPointeeType() const
Definition TypeBase.h:3592
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3717
StringRef getKindName() const
Definition Decl.h:3907
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3812
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition Decl.h:3948
void printName(raw_ostream &OS, const PrintingPolicy &Policy) const override
Pretty-print the unqualified name of this declaration.
Definition Decl.cpp:4959
bool isDependentType() const
Whether this declaration declares a type that is dependent, i.e., a type that somehow depends on temp...
Definition Decl.h:3857
bool isMFloat8Type() const
Definition TypeBase.h:8917
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:2385
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9112
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:3967
@ 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
const FunctionProtoType * T
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.