clang 24.0.0git
CIRGenTypes.cpp
Go to the documentation of this file.
1#include "CIRGenTypes.h"
2
3#include "CIRGenCXXABI.h"
4#include "CIRGenCall.h"
6#include "CIRGenModule.h"
7#include "mlir/IR/BuiltinTypes.h"
8
11#include "clang/AST/Type.h"
15
16#include <cassert>
17
18using namespace clang;
19using namespace clang::CIRGen;
20
22 : cgm(genModule), astContext(genModule.getASTContext()),
23 builder(cgm.getBuilder()), theCXXABI(cgm.getCXXABI()),
24 theABIInfo(cgm.getTargetCIRGenInfo().getABIInfo()) {}
25
27 for (auto i = functionInfos.begin(), e = functionInfos.end(); i != e;)
28 delete &*i++;
29}
30
31mlir::MLIRContext &CIRGenTypes::getMLIRContext() const {
32 return *builder.getContext();
33}
34
35/// Return true if the specified type in a function parameter or result position
36/// can be converted to a CIR type at this point. This boils down to being
37/// whether it is complete, as well as whether we've temporarily deferred
38/// expanding the type because we're in a recursive context.
40 // Some ABIs cannot have their member pointers represented in LLVM IR unless
41 // certain circumstances have been reached, but in CIR we represent member
42 // pointer types abstractly at this point so they are always convertible.
43 if (type->getAs<MemberPointerType>())
44 return true;
45
46 // If this isn't a tag type, we can convert it.
47 const TagType *tagType = type->getAs<TagType>();
48 if (!tagType)
49 return true;
50
51 // Function types involving incomplete class types are problematic in MLIR.
52 return !tagType->isIncompleteType();
53}
54
55/// Code to verify a given function type is complete, i.e. the return type and
56/// all of the parameter types are complete. Also check to see if we are in a
57/// RS_StructPointer context, and if so whether any struct types have been
58/// pended. If so, we don't want to ask the ABI lowering code to handle a type
59/// that cannot be converted to a CIR type.
62 return false;
63
64 if (const auto *fpt = dyn_cast<FunctionProtoType>(ft))
65 for (unsigned i = 0, e = fpt->getNumParams(); i != e; i++)
66 if (!isFuncParamTypeConvertible(fpt->getParamType(i)))
67 return false;
68
69 return true;
70}
71
72mlir::Type CIRGenTypes::convertFunctionTypeInternal(QualType qft) {
73 assert(qft.isCanonical());
75
76 // In classic codegen, if the function type depends on an incomplete type
77 // (e.g. a struct or enum), it cannot lower the function type due to ABI
78 // handling requirements and returns a placeholder. In CIR, ABI handling is
79 // deferred until after codegen, and record types are identified by name, so
80 // incomplete record type references in the function type will automatically
81 // see the complete type once the record is defined. We can always produce a
82 // proper function type here.
83
84 const CIRGenFunctionInfo *fi;
85 if (const auto *fpt = dyn_cast<FunctionProtoType>(ft)) {
88 } else {
92 }
93
94 mlir::Type resultType = getFunctionType(*fi);
95
96 return resultType;
97}
98
99// This is CIR's version of CodeGenTypes::addRecordTypeName. It isn't shareable
100// because CIR has different uniquing requirements.
102 StringRef suffix) {
103 llvm::SmallString<256> typeName;
104 llvm::raw_svector_ostream outStream(typeName);
105
106 PrintingPolicy policy = recordDecl->getASTContext().getPrintingPolicy();
110 policy.PrintAsCanonical = true;
111 policy.SuppressTagKeyword = true;
112
113 if (recordDecl->getIdentifier())
114 QualType(astContext.getCanonicalTagType(recordDecl))
115 .print(outStream, policy);
116 else if (auto *typedefNameDecl = recordDecl->getTypedefNameForAnonDecl())
117 typedefNameDecl->printQualifiedName(outStream, policy);
118 else
119 outStream << builder.getUniqueAnonRecordName();
120
121 if (!suffix.empty())
122 outStream << suffix;
123
124 return builder.getUniqueRecordName(std::string(typeName));
125}
126
127/// Return true if the specified type is already completely laid out.
129 const auto it = recordDeclTypes.find(ty);
130 return it != recordDeclTypes.end() && it->second.isComplete();
131}
132
133// We have multiple forms of this function that call each other, so we need to
134// declare one in advance.
135static bool
137 llvm::SmallPtrSetImpl<const RecordDecl *> &alreadyChecked);
138
139/// Return true if it is safe to convert the specified record decl to CIR and
140/// lay it out, false if doing so would cause us to get into a recursive
141/// compilation mess.
142static bool
144 llvm::SmallPtrSetImpl<const RecordDecl *> &alreadyChecked) {
145 // If we have already checked this type (maybe the same type is used by-value
146 // multiple times in multiple record fields, don't check again.
147 if (!alreadyChecked.insert(rd).second)
148 return true;
149
150 assert(rd->isCompleteDefinition() &&
151 "Expect RecordDecl to be CompleteDefinition");
152 const Type *key = cgt.getASTContext().getCanonicalTagType(rd).getTypePtr();
153
154 // If this type is already laid out, converting it is a noop.
155 if (cgt.isRecordLayoutComplete(key))
156 return true;
157
158 // Check the cross-call cache. This avoids redundant recursive field walks
159 // for the same record types across different convertRecordDeclType calls
160 // during a single layout phase.
161 if (cgt.isCachedSafeToConvert(key))
162 return true;
163
164 // If this type is currently being laid out, we can't recursively compile it.
165 if (cgt.isRecordBeingLaidOut(key))
166 return false;
167
168 // If this type would require laying out bases that are currently being laid
169 // out, don't do it. This includes virtual base classes which get laid out
170 // when a class is translated, even though they aren't embedded by-value into
171 // the class.
172 if (const CXXRecordDecl *crd = dyn_cast<CXXRecordDecl>(rd)) {
173 for (const clang::CXXBaseSpecifier &i : crd->bases())
174 if (!isSafeToConvert(i.getType()
175 ->castAs<RecordType>()
176 ->getDecl()
177 ->getDefinitionOrSelf(),
178 cgt, alreadyChecked))
179 return false;
180 }
181
182 // If this type would require laying out members that are currently being laid
183 // out, don't do it.
184 for (const FieldDecl *field : rd->fields())
185 if (!isSafeToConvert(field->getType(), cgt, alreadyChecked))
186 return false;
187
188 // Cache the positive result. This will be cleared when recordsBeingLaidOut
189 // changes.
190 cgt.cacheSafeToConvert(key);
191
192 // If there are no problems, lets do it.
193 return true;
194}
195
196/// Return true if it is safe to convert this field type, which requires the
197/// record elements contained by-value to all be recursively safe to convert.
198static bool
200 llvm::SmallPtrSetImpl<const RecordDecl *> &alreadyChecked) {
201 // Strip off atomic type sugar.
202 if (const auto *at = qt->getAs<AtomicType>())
203 qt = at->getValueType();
204
205 // If this is a record, check it.
206 if (const auto *rd = qt->getAsRecordDecl())
207 return isSafeToConvert(rd, cgt, alreadyChecked);
208
209 // If this is an array, check the elements, which are embedded inline.
210 if (const auto *at = cgt.getASTContext().getAsArrayType(qt))
211 return isSafeToConvert(at->getElementType(), cgt, alreadyChecked);
212
213 // Otherwise, there is no concern about transforming this. We only care about
214 // things that are contained by-value in a record that can have another
215 // record as a member.
216 return true;
217}
218
219// Return true if it is safe to convert the specified record decl to CIR and lay
220// it out, false if doing so would cause us to get into a recursive compilation
221// mess.
222static bool isSafeToConvert(const RecordDecl *rd, CIRGenTypes &cgt) {
223 // If no records are being laid out, we can certainly do this one.
224 if (cgt.noRecordsBeingLaidOut())
225 return true;
226
228 return isSafeToConvert(rd, cgt, alreadyChecked);
229}
230
234
236 return astContext.getTypeSize(type) !=
237 astContext.getTypeSize(type->getValueType());
238}
239
240/// Lay out a tagged decl type like struct or union.
242 // TagDecl's are not necessarily unique, instead use the (clang) type
243 // connected to the decl.
244 const Type *key = astContext.getCanonicalTagType(rd).getTypePtr();
245 cir::RecordType entry = recordDeclTypes[key];
246
247 // If we don't have an entry for this record yet, create one.
248 // We create an incomplete type initially. If `rd` is complete, we will
249 // add the members below.
250 if (!entry) {
251 auto name = getRecordTypeName(rd, "");
252 entry = builder.getIncompleteRecordTy(name, rd);
253 recordDeclTypes[key] = entry;
254 }
255
256 rd = rd->getDefinition();
257 if (!rd || !rd->isCompleteDefinition() || entry.isComplete())
258 return entry;
259
260 // If converting this type would cause us to infinitely loop, don't do it!
261 if (!isSafeToConvert(rd, *this)) {
262 deferredRecords.push_back(rd);
263 return entry;
264 }
265
266 // Okay, this is a definition of a type. Compile the implementation now.
267 bool insertResult = recordsBeingLaidOut.insert(key).second;
268 (void)insertResult;
269 assert(insertResult && "isSafeToCovert() should have caught this.");
270
271 // Invalidate the safety cache since recordsBeingLaidOut changed.
272 safeToConvertCache.clear();
273
274 // Force conversion of non-virtual base classes recursively.
275 if (const auto *cxxRecordDecl = dyn_cast<CXXRecordDecl>(rd)) {
276 for (const auto &base : cxxRecordDecl->bases()) {
277 if (base.isVirtual())
278 continue;
279 convertRecordDeclType(base.getType()->castAsRecordDecl());
280 }
281 }
282
283 // Layout fields.
284 std::unique_ptr<CIRGenRecordLayout> layout = computeRecordLayout(rd, &entry);
285 recordDeclTypes[key] = entry;
286 cirGenRecordLayouts[key] = std::move(layout);
287
288 // We're done laying out this record.
289 bool eraseResult = recordsBeingLaidOut.erase(key);
290 (void)eraseResult;
291 assert(eraseResult && "record not in RecordsBeingLaidOut set?");
292
293 // Invalidate the safety cache since recordsBeingLaidOut changed.
294 safeToConvertCache.clear();
295
296 // If we're done converting the outer-most record, then convert any deferred
297 // records as well.
298 if (recordsBeingLaidOut.empty())
299 while (!deferredRecords.empty())
300 convertRecordDeclType(deferredRecords.pop_back_val());
301
302 return entry;
303}
304
306 type = astContext.getCanonicalType(type);
307 const Type *ty = type.getTypePtr();
308
309 if (astContext.getLangOpts().CUDAIsDevice) {
310 if (type->isCUDADeviceBuiltinSurfaceType()) {
311 if (mlir::Type ty =
312 cgm.getTargetCIRGenInfo().getCUDADeviceBuiltinSurfaceDeviceType())
313 return ty;
314 } else if (type->isCUDADeviceBuiltinTextureType()) {
316 }
317 }
318
319 // Process record types before the type cache lookup.
320 if (const auto *recordType = dyn_cast<RecordType>(type))
321 return convertRecordDeclType(recordType->getDecl()->getDefinitionOrSelf());
322
323 // Has the type already been processed?
324 TypeCacheTy::iterator tci = typeCache.find(ty);
325 if (tci != typeCache.end())
326 return tci->second;
327
328 // For types that haven't been implemented yet or are otherwise unsupported,
329 // report an error and return 'int'.
330
331 mlir::Type resultType = nullptr;
332 switch (ty->getTypeClass()) {
333 case Type::Record:
334 llvm_unreachable("Should have been handled above");
335
336 case Type::Builtin: {
337 switch (cast<BuiltinType>(ty)->getKind()) {
338 // void
339 case BuiltinType::Void:
340 resultType = cgm.voidTy;
341 break;
342
343 // bool
344 case BuiltinType::Bool:
345 resultType = cir::BoolType::get(&getMLIRContext());
346 break;
347
348 // Signed integral types.
349 case BuiltinType::Char_S:
350 case BuiltinType::Int:
351 case BuiltinType::Int128:
352 case BuiltinType::Long:
353 case BuiltinType::LongLong:
354 case BuiltinType::SChar:
355 case BuiltinType::Short:
356 case BuiltinType::WChar_S:
357 case BuiltinType::Accum:
358 case BuiltinType::Fract:
359 case BuiltinType::LongAccum:
360 case BuiltinType::LongFract:
361 case BuiltinType::ShortAccum:
362 case BuiltinType::ShortFract:
363 // Saturated signed types.
364 case BuiltinType::SatAccum:
365 case BuiltinType::SatFract:
366 case BuiltinType::SatLongAccum:
367 case BuiltinType::SatLongFract:
368 case BuiltinType::SatShortAccum:
369 case BuiltinType::SatShortFract:
370 resultType =
371 cir::IntType::get(&getMLIRContext(), astContext.getTypeSize(ty),
372 /*isSigned=*/true);
373 break;
374
375 // SVE types
376 case BuiltinType::SveInt8:
377 resultType =
378 cir::VectorType::get(builder.getSInt8Ty(), 16, /*is_scalable=*/true);
379 break;
380 case BuiltinType::SveUint8:
381 resultType =
382 cir::VectorType::get(builder.getUInt8Ty(), 16, /*is_scalable=*/true);
383 break;
384 case BuiltinType::SveInt16:
385 resultType =
386 cir::VectorType::get(builder.getSInt16Ty(), 8, /*is_scalable=*/true);
387 break;
388 case BuiltinType::SveUint16:
389 resultType =
390 cir::VectorType::get(builder.getUInt16Ty(), 8, /*is_scalable=*/true);
391 break;
392 case BuiltinType::SveFloat16:
393 resultType = cir::VectorType::get(builder.getFp16Ty(), 8,
394 /*is_scalable=*/true);
395 break;
396 case BuiltinType::SveBFloat16:
397 resultType = cir::VectorType::get(builder.getFp16Ty(), 8,
398 /*is_scalable=*/true);
399 break;
400 case BuiltinType::SveInt32:
401 resultType =
402 cir::VectorType::get(builder.getSInt32Ty(), 4, /*is_scalable=*/true);
403 break;
404 case BuiltinType::SveUint32:
405 resultType =
406 cir::VectorType::get(builder.getUInt32Ty(), 4, /*is_scalable=*/true);
407 break;
408 case BuiltinType::SveFloat32:
409 resultType = cir::VectorType::get(builder.getSingleTy(), 4,
410 /*is_scalable=*/true);
411 break;
412 case BuiltinType::SveInt64:
413 resultType =
414 cir::VectorType::get(builder.getSInt64Ty(), 2, /*is_scalable=*/true);
415 break;
416 case BuiltinType::SveUint64:
417 resultType =
418 cir::VectorType::get(builder.getUInt64Ty(), 2, /*is_scalable=*/true);
419 break;
420 case BuiltinType::SveFloat64:
421 resultType = cir::VectorType::get(builder.getDoubleTy(), 2,
422 /*is_scalable=*/true);
423 break;
424 case BuiltinType::SveBool:
425 resultType = cir::VectorType::get(builder.getUIntNTy(1), 16,
426 /*is_scalable=*/true);
427 break;
428
429 // Unsigned integral types.
430 case BuiltinType::Char8:
431 case BuiltinType::Char16:
432 case BuiltinType::Char32:
433 case BuiltinType::Char_U:
434 case BuiltinType::UChar:
435 case BuiltinType::UInt:
436 case BuiltinType::UInt128:
437 case BuiltinType::ULong:
438 case BuiltinType::ULongLong:
439 case BuiltinType::UShort:
440 case BuiltinType::WChar_U:
441 case BuiltinType::UAccum:
442 case BuiltinType::UFract:
443 case BuiltinType::ULongAccum:
444 case BuiltinType::ULongFract:
445 case BuiltinType::UShortAccum:
446 case BuiltinType::UShortFract:
447 // Saturated unsigned types.
448 case BuiltinType::SatUAccum:
449 case BuiltinType::SatUFract:
450 case BuiltinType::SatULongAccum:
451 case BuiltinType::SatULongFract:
452 case BuiltinType::SatUShortAccum:
453 case BuiltinType::SatUShortFract:
454 resultType =
455 cir::IntType::get(&getMLIRContext(), astContext.getTypeSize(ty),
456 /*isSigned=*/false);
457 break;
458
459 // Floating-point types
460 case BuiltinType::Float16:
461 resultType = cgm.fP16Ty;
462 break;
463 case BuiltinType::Half:
464 resultType = cgm.fP16Ty;
465 break;
466 case BuiltinType::BFloat16:
467 resultType = cgm.bFloat16Ty;
468 break;
469 case BuiltinType::MFloat8:
470 resultType = cgm.uInt8Ty;
471 break;
472 case BuiltinType::Float:
473 assert(&astContext.getFloatTypeSemantics(type) ==
474 &llvm::APFloat::IEEEsingle() &&
475 "ClangIR NYI: 'float' in a format other than IEEE 32-bit");
476 resultType = cgm.floatTy;
477 break;
478 case BuiltinType::Double:
479 assert(&astContext.getFloatTypeSemantics(type) ==
480 &llvm::APFloat::IEEEdouble() &&
481 "ClangIR NYI: 'double' in a format other than IEEE 64-bit");
482 resultType = cgm.doubleTy;
483 break;
484 case BuiltinType::LongDouble:
485 resultType =
486 builder.getLongDoubleTy(astContext.getFloatTypeSemantics(type));
487 break;
488 case BuiltinType::Float128:
489 resultType = cgm.fP128Ty;
490 break;
491 case BuiltinType::Ibm128:
492 cgm.errorNYI(SourceLocation(), "processing of built-in type", type);
493 resultType = cgm.sInt32Ty;
494 break;
495
496 case BuiltinType::NullPtr:
497 // Add proper CIR type for it? this looks mostly useful for sema related
498 // things (like for overloads accepting void), for now, given that
499 // `sizeof(std::nullptr_t)` is equal to `sizeof(void *)`, model
500 // std::nullptr_t as !cir.ptr<!void>
501 resultType = builder.getVoidPtrTy();
502 break;
503
504#define AMDGPU_OPAQUE_PTR_TYPE(Name, Id, SingletonId, Width, Align, AS) \
505 case BuiltinType::Id: { \
506 if (BuiltinType::Id == BuiltinType::AMDGPUTexture) { \
507 resultType = cir::VectorType::get(builder.getSInt32Ty(), 8); \
508 } else { \
509 resultType = builder.getPointerTo( \
510 cgm.voidTy, \
511 cir::TargetAddressSpaceAttr::get(&getMLIRContext(), AS)); \
512 } \
513 break; \
514 }
515#define AMDGPU_NAMED_BARRIER_TYPE(Name, Id, SingletonId, Width, Align, Scope) \
516 case BuiltinType::Id: \
517 llvm_unreachable("NYI");
518#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
519 case BuiltinType::Id: \
520 llvm_unreachable("NYI");
521#include "clang/Basic/AMDGPUTypes.def"
522
523 default:
524 cgm.errorNYI(SourceLocation(), "processing of built-in type", type);
525 resultType = cgm.sInt32Ty;
526 break;
527 }
528 break;
529 }
530
531 case Type::Complex: {
532 const auto *ct = cast<clang::ComplexType>(ty);
533 mlir::Type elementTy = convertType(ct->getElementType());
534 resultType = cir::ComplexType::get(elementTy);
535 break;
536 }
537
538 case Type::LValueReference:
539 case Type::RValueReference: {
540 const ReferenceType *refTy = cast<ReferenceType>(ty);
541 QualType elemTy = refTy->getPointeeType();
542 auto pointeeType = convertTypeForMem(elemTy);
543 resultType = builder.getPointerTo(pointeeType, elemTy.getAddressSpace());
544 assert(resultType && "Cannot get pointer type?");
545 break;
546 }
547
548 case Type::Pointer: {
549 const PointerType *ptrTy = cast<PointerType>(ty);
550 QualType elemTy = ptrTy->getPointeeType();
551 assert(!elemTy->isConstantMatrixType() && "not implemented");
552
553 mlir::Type pointeeType = convertType(elemTy);
554
555 resultType = builder.getPointerTo(pointeeType, elemTy.getAddressSpace());
556 break;
557 }
558
559 case Type::VariableArray: {
561 if (a->getIndexTypeCVRQualifiers() != 0)
562 cgm.errorNYI(SourceLocation(), "non trivial array types", type);
563 // VLAs resolve to the innermost element type; this matches
564 // the return of alloca, and there isn't any obviously better choice.
565 resultType = convertTypeForMem(a->getElementType());
566 break;
567 }
568
569 case Type::IncompleteArray: {
571 if (arrTy->getIndexTypeCVRQualifiers() != 0)
572 cgm.errorNYI(SourceLocation(), "non trivial array types", type);
573
574 mlir::Type elemTy = convertTypeForMem(arrTy->getElementType());
575 // int X[] -> [0 x int], unless the element type is not sized. If it is
576 // unsized (e.g. an incomplete record) just use [0 x i8].
577 if (!cir::isSized(elemTy)) {
578 elemTy = cgm.sInt8Ty;
579 }
580
581 resultType = cir::ArrayType::get(elemTy, 0);
582 break;
583 }
584
585 case Type::ConstantArray: {
587 mlir::Type elemTy = convertTypeForMem(arrTy->getElementType());
588 // In classic codegen, arrays of unsized types which it assumes are "arrays
589 // of undefined struct type" are lowered to arrays of i8 "just to have a
590 // concrete type", but in CIR, we can get here with abstract types like
591 // !cir.method and !cir.data_member, so we just create an array of the type
592 // and handle it during lowering if we still don't have a sized type.
593 resultType = cir::ArrayType::get(elemTy, arrTy->getSize().getZExtValue());
594 break;
595 }
596
597 case Type::ExtVector:
598 case Type::Vector: {
599 const VectorType *vec = cast<VectorType>(ty);
600 const mlir::Type elemTy = convertType(vec->getElementType());
601 resultType = cir::VectorType::get(elemTy, vec->getNumElements());
602 break;
603 }
604
605 case Type::Enum: {
606 const auto *ed = ty->castAsEnumDecl();
607 if (auto integerType = ed->getIntegerType(); !integerType.isNull())
608 return convertType(integerType);
609 // Return a placeholder 'i32' type. This can be changed later when the
610 // type is defined (see UpdateCompletedType), but is likely to be the
611 // "right" answer.
612 resultType = cgm.uInt32Ty;
613 break;
614 }
615
616 case Type::MemberPointer: {
617 const auto *mpt = cast<MemberPointerType>(ty);
618
619 NestedNameSpecifier mptNNS = mpt->getQualifier();
620 auto clsTy = mlir::cast<cir::RecordType>(
621 convertType(QualType(mptNNS.getAsType(), 0)));
622 if (mpt->isMemberDataPointer()) {
623 mlir::Type memberTy = convertType(mpt->getPointeeType());
624 resultType = cir::DataMemberType::get(memberTy, clsTy);
625 } else {
626 auto memberFuncTy = getFunctionType(cgm.getTypes().arrangeCXXMethodType(
627 mptNNS.getAsRecordDecl(),
628 mpt->getPointeeType()->getAs<clang::FunctionProtoType>(),
629 /*methodDecl=*/nullptr));
630 resultType = cir::MethodType::get(memberFuncTy, clsTy);
631 }
632 break;
633 }
634
635 case Type::FunctionNoProto:
636 case Type::FunctionProto:
637 resultType = convertFunctionTypeInternal(type);
638 break;
639
640 case Type::BitInt: {
641 const auto *bitIntTy = cast<BitIntType>(type);
642 unsigned numBits = bitIntTy->getNumBits();
643 assert(numBits <= cir::IntType::maxBitwidth() &&
644 "_BitInt width exceeds CIR IntType maximum");
645 resultType =
646 cir::IntType::get(&getMLIRContext(), numBits, bitIntTy->isSigned(),
647 /*isBitInt=*/true);
648 break;
649 }
650
651 case Type::Atomic: {
652 QualType valueType = cast<AtomicType>(ty)->getValueType();
653 resultType = convertTypeForMem(valueType);
654
655 // Pad out to the inflated size if necessary.
656 uint64_t valueSize = astContext.getTypeSize(valueType);
657 uint64_t atomicSize = astContext.getTypeSize(ty);
658 if (valueSize != atomicSize) {
659 assert(valueSize < atomicSize);
660 auto paddingArray =
661 cir::ArrayType::get(cgm.sInt8Ty, (atomicSize - valueSize) / 8);
662 mlir::Type elements[] = {resultType, paddingArray};
663 cir::RecordMemberKind kinds[] = {cir::RecordMemberKind::Data,
664 cir::RecordMemberKind::Pad};
665 resultType =
666 cir::StructType::get(&getMLIRContext(), /*members=*/elements,
667 /*packed=*/false, /*is_class=*/false, kinds);
668 }
669
670 break;
671 }
672
673 default:
674 cgm.errorNYI(SourceLocation(), "processing of type",
675 type->getTypeClassName());
676 resultType = cgm.sInt32Ty;
677 break;
678 }
679
680 assert(resultType && "Type conversion not yet implemented");
681
682 typeCache[ty] = resultType;
683 return resultType;
684}
685
687 bool forBitField) {
688 if (qualType->isConstantMatrixType()) {
689 cgm.errorNYI("Matrix type conversion");
690 return cgm.sInt32Ty;
691 }
692
693 mlir::Type convertedType = convertType(qualType);
694
695 assert(!forBitField && "Bit fields NYI");
696
697 // If this is a bit-precise integer type in a bitfield representation, map
698 // this integer to the target-specified size.
699 if (forBitField && qualType->isBitIntType())
700 assert(!qualType->isBitIntType() && "Bit field with type _BitInt NYI");
701
702 return convertedType;
703}
704
705/// Return record layout info for the given record decl.
706const CIRGenRecordLayout &
708 const auto *key = astContext.getCanonicalTagType(rd).getTypePtr();
709
710 // If we have already computed the layout, return it.
711 auto it = cirGenRecordLayouts.find(key);
712 if (it != cirGenRecordLayouts.end())
713 return *it->second;
714
715 // Compute the type information.
717
718 // Now try again.
719 it = cirGenRecordLayouts.find(key);
720
721 assert(it != cirGenRecordLayouts.end() &&
722 "Unable to find record layout information for type");
723 return *it->second;
724}
725
727 if (t->getAs<PointerType>())
728 return astContext.getTargetNullPointerValue(t) == 0;
729
730 if (const auto *at = astContext.getAsArrayType(t)) {
732 return true;
733
734 if (const auto *cat = dyn_cast<ConstantArrayType>(at))
735 if (astContext.getConstantArrayElementCount(cat) == 0)
736 return true;
737 }
738
739 if (const auto *rd = t->getAsRecordDecl())
740 return isZeroInitializable(rd);
741
742 if (const auto *mpt = t->getAs<MemberPointerType>())
743 return theCXXABI.isZeroInitializable(mpt);
744
745 if (t->getAs<HLSLInlineSpirvType>())
746 cgm.errorNYI(SourceLocation(),
747 "isZeroInitializable for HLSLInlineSpirvType");
748
749 return true;
750}
751
755
757 CanQualType returnType, bool isInstanceMethod,
759 RequiredArgs required) {
760 assert(llvm::all_of(argTypes,
761 [](CanQualType t) { return t.isCanonicalAsParam(); }));
762 // Lookup or create unique function info.
763 llvm::FoldingSetNodeID id;
764 CIRGenFunctionInfo::Profile(id, isInstanceMethod, info, required, returnType,
765 argTypes);
766
767 void *insertPos = nullptr;
768 CIRGenFunctionInfo *fi = functionInfos.FindNodeOrInsertPos(id, insertPos);
769 if (fi) {
770 // We found a matching function info based on id. These asserts verify that
771 // it really is a match.
772 assert(
773 fi->getReturnType() == returnType &&
774 std::equal(fi->argTypesBegin(), fi->argTypesEnd(), argTypes.begin()) &&
775 "Bad match based on CIRGenFunctionInfo folding set id");
776 return *fi;
777 }
778
780
781 // Construction the function info. We co-allocate the ArgInfos.
782 fi = CIRGenFunctionInfo::create(info, isInstanceMethod, returnType, argTypes,
783 required);
784 functionInfos.InsertNode(fi, insertPos);
785
786 return *fi;
787}
788
789const CIRGenFunctionInfo &
791 const FunctionArgList &args) {
793 for (const VarDecl *arg : args)
794 argTypes.push_back(astContext.getCanonicalParamType(arg->getType()));
795
796 // Classic CodeGen passes FnInfoOpts::None here; that is the no-op case, so
797 // nothing is needed even once CIR models FnInfoOpts.
799 resultType->getCanonicalTypeUnqualified(), /*isInstanceMethod=*/false,
801}
802
804 assert(!dyn_cast<ObjCMethodDecl>(gd.getDecl()) &&
805 "This is reported as a FIXME in LLVM codegen");
806 const auto *fd = cast<FunctionDecl>(gd.getDecl());
807
811
813}
814
815// When we find the full definition for a TagDecl, replace the 'opaque' type we
816// previously made for it if applicable.
818 // If this is an enum being completed, then we flush all non-struct types
819 // from the cache. This allows function types and other things that may be
820 // derived from the enum to be recomputed.
821 if ([[maybe_unused]] const auto *ed = dyn_cast<EnumDecl>(td)) {
822 // Classic codegen clears the type cache if it contains an entry for this
823 // enum type that doesn't use i32 as the underlying type, but I can't find
824 // a test case that meets that condition. C++ doesn't allow forward
825 // declaration of enums, and C doesn't allow an incomplete forward
826 // declaration with a non-default type.
827 assert(
828 !typeCache.count(
829 ed->getASTContext().getCanonicalTagType(ed)->getTypePtr()) ||
830 (convertType(ed->getIntegerType()) ==
831 typeCache[ed->getASTContext().getCanonicalTagType(ed)->getTypePtr()]));
832 // If necessary, provide the full definition of a type only used with a
833 // declaration so far.
835 return;
836 }
837
838 // If we completed a RecordDecl that we previously used and converted to an
839 // anonymous type, then go ahead and complete it now.
840 const auto *rd = cast<RecordDecl>(td);
841 if (rd->isDependentType())
842 return;
843
844 // Only complete if we converted it already. If we haven't converted it yet,
845 // we'll just do it lazily.
846 if (recordDeclTypes.count(astContext.getCanonicalTagType(rd).getTypePtr()))
848
849 // If necessary, provide the full definition of a type only used with a
850 // declaration so far.
852}
853
855 // Return the address space for the type. If the type is a
856 // function type without an address space qualifier, the
857 // program address space is used. Otherwise, the target picks
858 // the best address space based on the type information
859 return ty->isFunctionType() && !ty.hasAddressSpace()
860 ? cgm.getDataLayout().getProgramAddressSpace()
862}
Defines the clang::ASTContext interface.
static bool isSafeToConvert(QualType qt, CIRGenTypes &cgt, llvm::SmallPtrSetImpl< const RecordDecl * > &alreadyChecked)
Return true if it is safe to convert this field type, which requires the record elements contained by...
static Decl::Kind getKind(const Decl *D)
C Language Family Type Representation.
C++ view class that accepts both !cir.struct and !cir.union types.
Definition CIRTypes.h:120
bool isComplete() const
Definition CIRTypes.h:139
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
CanQualType getCanonicalTagType(const TagDecl *TD) const
unsigned getTargetAddressSpace(LangAS AS) const
QualType getElementType() const
Definition TypeBase.h:3848
unsigned getIndexTypeCVRQualifiers() const
Definition TypeBase.h:3858
const_arg_iterator argTypesEnd() const
static CIRGenFunctionInfo * create(FunctionType::ExtInfo info, bool instanceMethod, CanQualType resultType, llvm::ArrayRef< CanQualType > argTypes, RequiredArgs required)
static void Profile(llvm::FoldingSetNodeID &id, bool instanceMethod, FunctionType::ExtInfo info, RequiredArgs required, CanQualType resultType, llvm::ArrayRef< CanQualType > argTypes)
const_arg_iterator argTypesBegin() const
This class organizes the cross-function state that is used while generating CIR code.
bool isPaddedAtomicType(QualType type)
This class handles record and union layout info while lowering AST types to CIR types.
bool isZeroInitializable() const
Check whether this struct can be C++ zero-initialized with a zeroinitializer.
This class organizes the cross-module state that is used while lowering AST types to CIR types.
Definition CIRGenTypes.h:51
const CIRGenFunctionInfo & arrangeGlobalDeclaration(GlobalDecl gd)
unsigned getTargetAddressSpace(QualType ty) const
const CIRGenFunctionInfo & arrangeCXXStructorDeclaration(clang::GlobalDecl gd)
const CIRGenFunctionInfo & arrangeCIRFunctionInfo(CanQualType returnType, bool isInstanceMethod, llvm::ArrayRef< CanQualType > argTypes, FunctionType::ExtInfo info, RequiredArgs required)
const CIRGenFunctionInfo & arrangeFreeFunctionType(CanQual< FunctionProtoType > fpt)
bool isZeroInitializable(clang::QualType ty)
Return whether a type can be zero-initialized (in the C++ sense) with an LLVM zeroinitializer.
bool isFuncTypeConvertible(const clang::FunctionType *ft)
Utility to check whether a function type can be converted to a CIR type (i.e.
CIRGenTypes(CIRGenModule &cgm)
bool isRecordBeingLaidOut(const clang::Type *ty) const
CIRGenBuilderTy & getBuilder() const
Definition CIRGenTypes.h:90
mlir::MLIRContext & getMLIRContext() const
bool isCachedSafeToConvert(const clang::Type *key) const
Check if a record type key is in the safe-to-convert cache.
cir::FuncType getFunctionType(const CIRGenFunctionInfo &info)
Get the CIR function type for.
bool isFuncParamTypeConvertible(clang::QualType type)
Return true if the specified type in a function parameter or result position can be converted to a CI...
void updateCompletedType(const clang::TagDecl *td)
UpdateCompletedType - when we find the full definition for a TagDecl, replace the 'opaque' type we pr...
std::string getRecordTypeName(const clang::RecordDecl *, llvm::StringRef suffix)
bool noRecordsBeingLaidOut() const
const ABIInfo & getABIInfo() const
const CIRGenFunctionInfo & arrangeFunctionDeclaration(const clang::FunctionDecl *fd)
Free functions are functions that are compatible with an ordinary C function pointer type.
clang::ASTContext & getASTContext() const
bool isRecordLayoutComplete(const clang::Type *ty) const
Return true if the specified type is already completely laid out.
const CIRGenFunctionInfo & arrangeDeviceKernelCallerDeclaration(clang::QualType resultType, const FunctionArgList &args)
Arrange the function info for a device kernel caller entry point (e.g.
mlir::Type convertType(clang::QualType type)
Convert a Clang type into a mlir::Type.
const CIRGenRecordLayout & getCIRGenRecordLayout(const clang::RecordDecl *rd)
Return record layout info for the given record decl.
std::unique_ptr< CIRGenRecordLayout > computeRecordLayout(const clang::RecordDecl *rd, cir::RecordType *ty)
mlir::Type convertRecordDeclType(const clang::RecordDecl *recordDecl)
Lay out a tagged decl type like struct or union.
void cacheSafeToConvert(const clang::Type *key)
Add a record type key to the safe-to-convert cache.
mlir::Type convertTypeForMem(clang::QualType, bool forBitField=false)
Convert type T into an mlir::Type.
Type for representing both the decl and type of parameters to a function.
Definition CIRGenCall.h:193
A class for recording the number of arguments that a function signature requires.
Represents a base class of a C++ class.
Definition DeclCXX.h:146
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
static CanQual< T > CreateUnsafe(QualType Other)
Builds a canonical type from a QualType.
bool isCanonicalAsParam() const
Determines if this canonical type is furthermore canonical as a parameter.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3874
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3930
Represents a member of a struct/union/class.
Definition Decl.h:3294
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition TypeBase.h:4999
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5421
A class which abstracts out some details necessary for making a call.
Definition TypeBase.h:4728
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4617
QualType getReturnType() const
Definition TypeBase.h:4957
GlobalDecl - represents a global declaration.
Definition GlobalDecl.h:57
const Decl * getDecl() const
Definition GlobalDecl.h:106
Represents a C array with an unspecified size.
Definition TypeBase.h:4023
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3767
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
CXXRecordDecl * getAsRecordDecl() const
Retrieve the record declaration stored in this nested name specifier, or null.
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3408
QualType getPointeeType() const
Definition TypeBase.h:3418
A (possibly-)qualified type.
Definition TypeBase.h:938
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8502
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8628
void print(raw_ostream &OS, const PrintingPolicy &Policy, const Twine &PlaceHolder=Twine(), unsigned Indentation=0) const
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8623
bool isCanonical() const
Definition TypeBase.h:8559
Represents a struct/union/class.
Definition Decl.h:4459
field_range fields() const
Definition Decl.h:4662
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4643
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3687
QualType getPointeeType() const
Definition TypeBase.h:3705
Encodes a location in the source.
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3851
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3952
The base class of the type hierarchy.
Definition TypeBase.h:1879
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isConstantMatrixType() const
Definition TypeBase.h:8906
CanQualType getCanonicalTypeUnqualified() const
EnumDecl * castAsEnumDecl() const
Definition Type.h:59
bool isFunctionType() const
Definition TypeBase.h:8735
TypeClass getTypeClass() const
Definition TypeBase.h:2449
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9338
Represents a variable declaration or definition.
Definition Decl.h:932
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:4080
Represents a GCC generic vector type.
Definition TypeBase.h:4289
unsigned getNumElements() const
Definition TypeBase.h:4304
QualType getElementType() const
Definition TypeBase.h:4303
Defines the clang::TargetInfo interface.
bool isSized(mlir::Type ty)
Returns true if the type is a CIR sized type.
Definition CIRTypes.cpp:35
@ Type
The l-value was considered opaque, so the alignment was determined from a type.
const internal::VariadicDynCastAllOfMatcher< Decl, TypedefNameDecl > typedefNameDecl
Matches typedef name declarations.
const AstTypeMatcher< TagType > tagType
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< RecordType > recordType
const internal::VariadicDynCastAllOfMatcher< Decl, CXXRecordDecl > cxxRecordDecl
Matches C++ class declarations.
const internal::VariadicDynCastAllOfMatcher< Decl, RecordDecl > recordDecl
Matches class, struct, and union declarations.
const internal::VariadicAllOfMatcher< QualType > qualType
Matches QualTypes in the clang AST.
Top level wrappers for InstallAPI frontend operations.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isa(CodeGen::Address addr)
Definition Address.h:330
bool isInstanceMethod(const Decl *D)
Definition Attr.h:152
@ CC_DeviceKernel
Definition Specifiers.h:292
U cast(CodeGen::Address addr)
Definition Address.h:327
static bool opCallCallConv()
static bool cudaTextureType()
static bool generateDebugInfo()
Describes how types, statements, expressions, and declarations should be printed.
unsigned SuppressTagKeyword
Whether type printing should skip printing the tag keyword.
unsigned AlwaysIncludeTypeForTemplateArgument
Whether to use type suffixes (eg: 1U) on integral non-type template parameters.
unsigned SuppressInlineNamespace
Suppress printing parts of scope specifiers that correspond to inline namespaces.
unsigned PrintAsCanonical
Whether to print entities as written or canonically.