1 //===- Type.cpp - Type representation and manipulation --------------------===// 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 file implements type-related functionality. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/AST/Type.h" 14 #include "Linkage.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/Attr.h" 17 #include "clang/AST/CharUnits.h" 18 #include "clang/AST/Decl.h" 19 #include "clang/AST/DeclBase.h" 20 #include "clang/AST/DeclCXX.h" 21 #include "clang/AST/DeclObjC.h" 22 #include "clang/AST/DeclTemplate.h" 23 #include "clang/AST/DependenceFlags.h" 24 #include "clang/AST/Expr.h" 25 #include "clang/AST/NestedNameSpecifier.h" 26 #include "clang/AST/NonTrivialTypeVisitor.h" 27 #include "clang/AST/PrettyPrinter.h" 28 #include "clang/AST/TemplateBase.h" 29 #include "clang/AST/TemplateName.h" 30 #include "clang/AST/TypeVisitor.h" 31 #include "clang/Basic/AddressSpaces.h" 32 #include "clang/Basic/ExceptionSpecificationType.h" 33 #include "clang/Basic/IdentifierTable.h" 34 #include "clang/Basic/LLVM.h" 35 #include "clang/Basic/LangOptions.h" 36 #include "clang/Basic/Linkage.h" 37 #include "clang/Basic/Specifiers.h" 38 #include "clang/Basic/TargetCXXABI.h" 39 #include "clang/Basic/TargetInfo.h" 40 #include "clang/Basic/Visibility.h" 41 #include "llvm/ADT/APInt.h" 42 #include "llvm/ADT/APSInt.h" 43 #include "llvm/ADT/ArrayRef.h" 44 #include "llvm/ADT/FoldingSet.h" 45 #include "llvm/ADT/None.h" 46 #include "llvm/ADT/SmallVector.h" 47 #include "llvm/Support/Casting.h" 48 #include "llvm/Support/ErrorHandling.h" 49 #include "llvm/Support/MathExtras.h" 50 #include <algorithm> 51 #include <cassert> 52 #include <cstdint> 53 #include <cstring> 54 #include <type_traits> 55 56 using namespace clang; 57 58 bool Qualifiers::isStrictSupersetOf(Qualifiers Other) const { 59 return (*this != Other) && 60 // CVR qualifiers superset 61 (((Mask & CVRMask) | (Other.Mask & CVRMask)) == (Mask & CVRMask)) && 62 // ObjC GC qualifiers superset 63 ((getObjCGCAttr() == Other.getObjCGCAttr()) || 64 (hasObjCGCAttr() && !Other.hasObjCGCAttr())) && 65 // Address space superset. 66 ((getAddressSpace() == Other.getAddressSpace()) || 67 (hasAddressSpace()&& !Other.hasAddressSpace())) && 68 // Lifetime qualifier superset. 69 ((getObjCLifetime() == Other.getObjCLifetime()) || 70 (hasObjCLifetime() && !Other.hasObjCLifetime())); 71 } 72 73 const IdentifierInfo* QualType::getBaseTypeIdentifier() const { 74 const Type* ty = getTypePtr(); 75 NamedDecl *ND = nullptr; 76 if (ty->isPointerType() || ty->isReferenceType()) 77 return ty->getPointeeType().getBaseTypeIdentifier(); 78 else if (ty->isRecordType()) 79 ND = ty->castAs<RecordType>()->getDecl(); 80 else if (ty->isEnumeralType()) 81 ND = ty->castAs<EnumType>()->getDecl(); 82 else if (ty->getTypeClass() == Type::Typedef) 83 ND = ty->castAs<TypedefType>()->getDecl(); 84 else if (ty->isArrayType()) 85 return ty->castAsArrayTypeUnsafe()-> 86 getElementType().getBaseTypeIdentifier(); 87 88 if (ND) 89 return ND->getIdentifier(); 90 return nullptr; 91 } 92 93 bool QualType::mayBeDynamicClass() const { 94 const auto *ClassDecl = getTypePtr()->getPointeeCXXRecordDecl(); 95 return ClassDecl && ClassDecl->mayBeDynamicClass(); 96 } 97 98 bool QualType::mayBeNotDynamicClass() const { 99 const auto *ClassDecl = getTypePtr()->getPointeeCXXRecordDecl(); 100 return !ClassDecl || ClassDecl->mayBeNonDynamicClass(); 101 } 102 103 bool QualType::isConstant(QualType T, const ASTContext &Ctx) { 104 if (T.isConstQualified()) 105 return true; 106 107 if (const ArrayType *AT = Ctx.getAsArrayType(T)) 108 return AT->getElementType().isConstant(Ctx); 109 110 return T.getAddressSpace() == LangAS::opencl_constant; 111 } 112 113 // C++ [temp.dep.type]p1: 114 // A type is dependent if it is... 115 // - an array type constructed from any dependent type or whose 116 // size is specified by a constant expression that is 117 // value-dependent, 118 ArrayType::ArrayType(TypeClass tc, QualType et, QualType can, 119 ArraySizeModifier sm, unsigned tq, const Expr *sz) 120 // Note, we need to check for DependentSizedArrayType explicitly here 121 // because we use a DependentSizedArrayType with no size expression as the 122 // type of a dependent array of unknown bound with a dependent braced 123 // initializer: 124 // 125 // template<int ...N> int arr[] = {N...}; 126 : Type(tc, can, 127 et->getDependence() | 128 (sz ? toTypeDependence(sz->getDependence()) 129 : TypeDependence::None) | 130 (tc == VariableArray ? TypeDependence::VariablyModified 131 : TypeDependence::None) | 132 (tc == DependentSizedArray 133 ? TypeDependence::DependentInstantiation 134 : TypeDependence::None)), 135 ElementType(et) { 136 ArrayTypeBits.IndexTypeQuals = tq; 137 ArrayTypeBits.SizeModifier = sm; 138 } 139 140 unsigned ConstantArrayType::getNumAddressingBits(const ASTContext &Context, 141 QualType ElementType, 142 const llvm::APInt &NumElements) { 143 uint64_t ElementSize = Context.getTypeSizeInChars(ElementType).getQuantity(); 144 145 // Fast path the common cases so we can avoid the conservative computation 146 // below, which in common cases allocates "large" APSInt values, which are 147 // slow. 148 149 // If the element size is a power of 2, we can directly compute the additional 150 // number of addressing bits beyond those required for the element count. 151 if (llvm::isPowerOf2_64(ElementSize)) { 152 return NumElements.getActiveBits() + llvm::Log2_64(ElementSize); 153 } 154 155 // If both the element count and element size fit in 32-bits, we can do the 156 // computation directly in 64-bits. 157 if ((ElementSize >> 32) == 0 && NumElements.getBitWidth() <= 64 && 158 (NumElements.getZExtValue() >> 32) == 0) { 159 uint64_t TotalSize = NumElements.getZExtValue() * ElementSize; 160 return 64 - llvm::countLeadingZeros(TotalSize); 161 } 162 163 // Otherwise, use APSInt to handle arbitrary sized values. 164 llvm::APSInt SizeExtended(NumElements, true); 165 unsigned SizeTypeBits = Context.getTypeSize(Context.getSizeType()); 166 SizeExtended = SizeExtended.extend(std::max(SizeTypeBits, 167 SizeExtended.getBitWidth()) * 2); 168 169 llvm::APSInt TotalSize(llvm::APInt(SizeExtended.getBitWidth(), ElementSize)); 170 TotalSize *= SizeExtended; 171 172 return TotalSize.getActiveBits(); 173 } 174 175 unsigned ConstantArrayType::getMaxSizeBits(const ASTContext &Context) { 176 unsigned Bits = Context.getTypeSize(Context.getSizeType()); 177 178 // Limit the number of bits in size_t so that maximal bit size fits 64 bit 179 // integer (see PR8256). We can do this as currently there is no hardware 180 // that supports full 64-bit virtual space. 181 if (Bits > 61) 182 Bits = 61; 183 184 return Bits; 185 } 186 187 void ConstantArrayType::Profile(llvm::FoldingSetNodeID &ID, 188 const ASTContext &Context, QualType ET, 189 const llvm::APInt &ArraySize, 190 const Expr *SizeExpr, ArraySizeModifier SizeMod, 191 unsigned TypeQuals) { 192 ID.AddPointer(ET.getAsOpaquePtr()); 193 ID.AddInteger(ArraySize.getZExtValue()); 194 ID.AddInteger(SizeMod); 195 ID.AddInteger(TypeQuals); 196 ID.AddBoolean(SizeExpr != 0); 197 if (SizeExpr) 198 SizeExpr->Profile(ID, Context, true); 199 } 200 201 DependentSizedArrayType::DependentSizedArrayType(const ASTContext &Context, 202 QualType et, QualType can, 203 Expr *e, ArraySizeModifier sm, 204 unsigned tq, 205 SourceRange brackets) 206 : ArrayType(DependentSizedArray, et, can, sm, tq, e), 207 Context(Context), SizeExpr((Stmt*) e), Brackets(brackets) {} 208 209 void DependentSizedArrayType::Profile(llvm::FoldingSetNodeID &ID, 210 const ASTContext &Context, 211 QualType ET, 212 ArraySizeModifier SizeMod, 213 unsigned TypeQuals, 214 Expr *E) { 215 ID.AddPointer(ET.getAsOpaquePtr()); 216 ID.AddInteger(SizeMod); 217 ID.AddInteger(TypeQuals); 218 E->Profile(ID, Context, true); 219 } 220 221 DependentVectorType::DependentVectorType(const ASTContext &Context, 222 QualType ElementType, 223 QualType CanonType, Expr *SizeExpr, 224 SourceLocation Loc, 225 VectorType::VectorKind VecKind) 226 : Type(DependentVector, CanonType, 227 TypeDependence::DependentInstantiation | 228 ElementType->getDependence() | 229 (SizeExpr ? toTypeDependence(SizeExpr->getDependence()) 230 : TypeDependence::None)), 231 Context(Context), ElementType(ElementType), SizeExpr(SizeExpr), Loc(Loc) { 232 VectorTypeBits.VecKind = VecKind; 233 } 234 235 void DependentVectorType::Profile(llvm::FoldingSetNodeID &ID, 236 const ASTContext &Context, 237 QualType ElementType, const Expr *SizeExpr, 238 VectorType::VectorKind VecKind) { 239 ID.AddPointer(ElementType.getAsOpaquePtr()); 240 ID.AddInteger(VecKind); 241 SizeExpr->Profile(ID, Context, true); 242 } 243 244 DependentSizedExtVectorType::DependentSizedExtVectorType( 245 const ASTContext &Context, QualType ElementType, QualType can, 246 Expr *SizeExpr, SourceLocation loc) 247 : Type(DependentSizedExtVector, can, 248 TypeDependence::DependentInstantiation | 249 ElementType->getDependence() | 250 (SizeExpr ? toTypeDependence(SizeExpr->getDependence()) 251 : TypeDependence::None)), 252 Context(Context), SizeExpr(SizeExpr), ElementType(ElementType), loc(loc) { 253 } 254 255 void 256 DependentSizedExtVectorType::Profile(llvm::FoldingSetNodeID &ID, 257 const ASTContext &Context, 258 QualType ElementType, Expr *SizeExpr) { 259 ID.AddPointer(ElementType.getAsOpaquePtr()); 260 SizeExpr->Profile(ID, Context, true); 261 } 262 263 DependentAddressSpaceType::DependentAddressSpaceType(const ASTContext &Context, 264 QualType PointeeType, 265 QualType can, 266 Expr *AddrSpaceExpr, 267 SourceLocation loc) 268 : Type(DependentAddressSpace, can, 269 TypeDependence::DependentInstantiation | 270 PointeeType->getDependence() | 271 (AddrSpaceExpr ? toTypeDependence(AddrSpaceExpr->getDependence()) 272 : TypeDependence::None)), 273 Context(Context), AddrSpaceExpr(AddrSpaceExpr), PointeeType(PointeeType), 274 loc(loc) {} 275 276 void DependentAddressSpaceType::Profile(llvm::FoldingSetNodeID &ID, 277 const ASTContext &Context, 278 QualType PointeeType, 279 Expr *AddrSpaceExpr) { 280 ID.AddPointer(PointeeType.getAsOpaquePtr()); 281 AddrSpaceExpr->Profile(ID, Context, true); 282 } 283 284 MatrixType::MatrixType(TypeClass tc, QualType matrixType, QualType canonType, 285 const Expr *RowExpr, const Expr *ColumnExpr) 286 : Type(tc, canonType, 287 (RowExpr ? (matrixType->getDependence() | TypeDependence::Dependent | 288 TypeDependence::Instantiation | 289 (matrixType->isVariablyModifiedType() 290 ? TypeDependence::VariablyModified 291 : TypeDependence::None) | 292 (matrixType->containsUnexpandedParameterPack() || 293 (RowExpr && 294 RowExpr->containsUnexpandedParameterPack()) || 295 (ColumnExpr && 296 ColumnExpr->containsUnexpandedParameterPack()) 297 ? TypeDependence::UnexpandedPack 298 : TypeDependence::None)) 299 : matrixType->getDependence())), 300 ElementType(matrixType) {} 301 302 ConstantMatrixType::ConstantMatrixType(QualType matrixType, unsigned nRows, 303 unsigned nColumns, QualType canonType) 304 : ConstantMatrixType(ConstantMatrix, matrixType, nRows, nColumns, 305 canonType) {} 306 307 ConstantMatrixType::ConstantMatrixType(TypeClass tc, QualType matrixType, 308 unsigned nRows, unsigned nColumns, 309 QualType canonType) 310 : MatrixType(tc, matrixType, canonType), NumRows(nRows), 311 NumColumns(nColumns) {} 312 313 DependentSizedMatrixType::DependentSizedMatrixType( 314 const ASTContext &CTX, QualType ElementType, QualType CanonicalType, 315 Expr *RowExpr, Expr *ColumnExpr, SourceLocation loc) 316 : MatrixType(DependentSizedMatrix, ElementType, CanonicalType, RowExpr, 317 ColumnExpr), 318 Context(CTX), RowExpr(RowExpr), ColumnExpr(ColumnExpr), loc(loc) {} 319 320 void DependentSizedMatrixType::Profile(llvm::FoldingSetNodeID &ID, 321 const ASTContext &CTX, 322 QualType ElementType, Expr *RowExpr, 323 Expr *ColumnExpr) { 324 ID.AddPointer(ElementType.getAsOpaquePtr()); 325 RowExpr->Profile(ID, CTX, true); 326 ColumnExpr->Profile(ID, CTX, true); 327 } 328 329 VectorType::VectorType(QualType vecType, unsigned nElements, QualType canonType, 330 VectorKind vecKind) 331 : VectorType(Vector, vecType, nElements, canonType, vecKind) {} 332 333 VectorType::VectorType(TypeClass tc, QualType vecType, unsigned nElements, 334 QualType canonType, VectorKind vecKind) 335 : Type(tc, canonType, vecType->getDependence()), ElementType(vecType) { 336 VectorTypeBits.VecKind = vecKind; 337 VectorTypeBits.NumElements = nElements; 338 } 339 340 ExtIntType::ExtIntType(bool IsUnsigned, unsigned NumBits) 341 : Type(ExtInt, QualType{}, TypeDependence::None), IsUnsigned(IsUnsigned), 342 NumBits(NumBits) {} 343 344 DependentExtIntType::DependentExtIntType(const ASTContext &Context, 345 bool IsUnsigned, Expr *NumBitsExpr) 346 : Type(DependentExtInt, QualType{}, 347 toTypeDependence(NumBitsExpr->getDependence())), 348 Context(Context), ExprAndUnsigned(NumBitsExpr, IsUnsigned) {} 349 350 bool DependentExtIntType::isUnsigned() const { 351 return ExprAndUnsigned.getInt(); 352 } 353 354 clang::Expr *DependentExtIntType::getNumBitsExpr() const { 355 return ExprAndUnsigned.getPointer(); 356 } 357 358 void DependentExtIntType::Profile(llvm::FoldingSetNodeID &ID, 359 const ASTContext &Context, bool IsUnsigned, 360 Expr *NumBitsExpr) { 361 ID.AddBoolean(IsUnsigned); 362 NumBitsExpr->Profile(ID, Context, true); 363 } 364 365 /// getArrayElementTypeNoTypeQual - If this is an array type, return the 366 /// element type of the array, potentially with type qualifiers missing. 367 /// This method should never be used when type qualifiers are meaningful. 368 const Type *Type::getArrayElementTypeNoTypeQual() const { 369 // If this is directly an array type, return it. 370 if (const auto *ATy = dyn_cast<ArrayType>(this)) 371 return ATy->getElementType().getTypePtr(); 372 373 // If the canonical form of this type isn't the right kind, reject it. 374 if (!isa<ArrayType>(CanonicalType)) 375 return nullptr; 376 377 // If this is a typedef for an array type, strip the typedef off without 378 // losing all typedef information. 379 return cast<ArrayType>(getUnqualifiedDesugaredType()) 380 ->getElementType().getTypePtr(); 381 } 382 383 /// getDesugaredType - Return the specified type with any "sugar" removed from 384 /// the type. This takes off typedefs, typeof's etc. If the outer level of 385 /// the type is already concrete, it returns it unmodified. This is similar 386 /// to getting the canonical type, but it doesn't remove *all* typedefs. For 387 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is 388 /// concrete. 389 QualType QualType::getDesugaredType(QualType T, const ASTContext &Context) { 390 SplitQualType split = getSplitDesugaredType(T); 391 return Context.getQualifiedType(split.Ty, split.Quals); 392 } 393 394 QualType QualType::getSingleStepDesugaredTypeImpl(QualType type, 395 const ASTContext &Context) { 396 SplitQualType split = type.split(); 397 QualType desugar = split.Ty->getLocallyUnqualifiedSingleStepDesugaredType(); 398 return Context.getQualifiedType(desugar, split.Quals); 399 } 400 401 // Check that no type class is polymorphic. LLVM style RTTI should be used 402 // instead. If absolutely needed an exception can still be added here by 403 // defining the appropriate macro (but please don't do this). 404 #define TYPE(CLASS, BASE) \ 405 static_assert(!std::is_polymorphic<CLASS##Type>::value, \ 406 #CLASS "Type should not be polymorphic!"); 407 #include "clang/AST/TypeNodes.inc" 408 409 // Check that no type class has a non-trival destructor. Types are 410 // allocated with the BumpPtrAllocator from ASTContext and therefore 411 // their destructor is not executed. 412 // 413 // FIXME: ConstantArrayType is not trivially destructible because of its 414 // APInt member. It should be replaced in favor of ASTContext allocation. 415 #define TYPE(CLASS, BASE) \ 416 static_assert(std::is_trivially_destructible<CLASS##Type>::value || \ 417 std::is_same<CLASS##Type, ConstantArrayType>::value, \ 418 #CLASS "Type should be trivially destructible!"); 419 #include "clang/AST/TypeNodes.inc" 420 421 QualType Type::getLocallyUnqualifiedSingleStepDesugaredType() const { 422 switch (getTypeClass()) { 423 #define ABSTRACT_TYPE(Class, Parent) 424 #define TYPE(Class, Parent) \ 425 case Type::Class: { \ 426 const auto *ty = cast<Class##Type>(this); \ 427 if (!ty->isSugared()) return QualType(ty, 0); \ 428 return ty->desugar(); \ 429 } 430 #include "clang/AST/TypeNodes.inc" 431 } 432 llvm_unreachable("bad type kind!"); 433 } 434 435 SplitQualType QualType::getSplitDesugaredType(QualType T) { 436 QualifierCollector Qs; 437 438 QualType Cur = T; 439 while (true) { 440 const Type *CurTy = Qs.strip(Cur); 441 switch (CurTy->getTypeClass()) { 442 #define ABSTRACT_TYPE(Class, Parent) 443 #define TYPE(Class, Parent) \ 444 case Type::Class: { \ 445 const auto *Ty = cast<Class##Type>(CurTy); \ 446 if (!Ty->isSugared()) \ 447 return SplitQualType(Ty, Qs); \ 448 Cur = Ty->desugar(); \ 449 break; \ 450 } 451 #include "clang/AST/TypeNodes.inc" 452 } 453 } 454 } 455 456 SplitQualType QualType::getSplitUnqualifiedTypeImpl(QualType type) { 457 SplitQualType split = type.split(); 458 459 // All the qualifiers we've seen so far. 460 Qualifiers quals = split.Quals; 461 462 // The last type node we saw with any nodes inside it. 463 const Type *lastTypeWithQuals = split.Ty; 464 465 while (true) { 466 QualType next; 467 468 // Do a single-step desugar, aborting the loop if the type isn't 469 // sugared. 470 switch (split.Ty->getTypeClass()) { 471 #define ABSTRACT_TYPE(Class, Parent) 472 #define TYPE(Class, Parent) \ 473 case Type::Class: { \ 474 const auto *ty = cast<Class##Type>(split.Ty); \ 475 if (!ty->isSugared()) goto done; \ 476 next = ty->desugar(); \ 477 break; \ 478 } 479 #include "clang/AST/TypeNodes.inc" 480 } 481 482 // Otherwise, split the underlying type. If that yields qualifiers, 483 // update the information. 484 split = next.split(); 485 if (!split.Quals.empty()) { 486 lastTypeWithQuals = split.Ty; 487 quals.addConsistentQualifiers(split.Quals); 488 } 489 } 490 491 done: 492 return SplitQualType(lastTypeWithQuals, quals); 493 } 494 495 QualType QualType::IgnoreParens(QualType T) { 496 // FIXME: this seems inherently un-qualifiers-safe. 497 while (const auto *PT = T->getAs<ParenType>()) 498 T = PT->getInnerType(); 499 return T; 500 } 501 502 /// This will check for a T (which should be a Type which can act as 503 /// sugar, such as a TypedefType) by removing any existing sugar until it 504 /// reaches a T or a non-sugared type. 505 template<typename T> static const T *getAsSugar(const Type *Cur) { 506 while (true) { 507 if (const auto *Sugar = dyn_cast<T>(Cur)) 508 return Sugar; 509 switch (Cur->getTypeClass()) { 510 #define ABSTRACT_TYPE(Class, Parent) 511 #define TYPE(Class, Parent) \ 512 case Type::Class: { \ 513 const auto *Ty = cast<Class##Type>(Cur); \ 514 if (!Ty->isSugared()) return 0; \ 515 Cur = Ty->desugar().getTypePtr(); \ 516 break; \ 517 } 518 #include "clang/AST/TypeNodes.inc" 519 } 520 } 521 } 522 523 template <> const TypedefType *Type::getAs() const { 524 return getAsSugar<TypedefType>(this); 525 } 526 527 template <> const TemplateSpecializationType *Type::getAs() const { 528 return getAsSugar<TemplateSpecializationType>(this); 529 } 530 531 template <> const AttributedType *Type::getAs() const { 532 return getAsSugar<AttributedType>(this); 533 } 534 535 /// getUnqualifiedDesugaredType - Pull any qualifiers and syntactic 536 /// sugar off the given type. This should produce an object of the 537 /// same dynamic type as the canonical type. 538 const Type *Type::getUnqualifiedDesugaredType() const { 539 const Type *Cur = this; 540 541 while (true) { 542 switch (Cur->getTypeClass()) { 543 #define ABSTRACT_TYPE(Class, Parent) 544 #define TYPE(Class, Parent) \ 545 case Class: { \ 546 const auto *Ty = cast<Class##Type>(Cur); \ 547 if (!Ty->isSugared()) return Cur; \ 548 Cur = Ty->desugar().getTypePtr(); \ 549 break; \ 550 } 551 #include "clang/AST/TypeNodes.inc" 552 } 553 } 554 } 555 556 bool Type::isClassType() const { 557 if (const auto *RT = getAs<RecordType>()) 558 return RT->getDecl()->isClass(); 559 return false; 560 } 561 562 bool Type::isStructureType() const { 563 if (const auto *RT = getAs<RecordType>()) 564 return RT->getDecl()->isStruct(); 565 return false; 566 } 567 568 bool Type::isObjCBoxableRecordType() const { 569 if (const auto *RT = getAs<RecordType>()) 570 return RT->getDecl()->hasAttr<ObjCBoxableAttr>(); 571 return false; 572 } 573 574 bool Type::isInterfaceType() const { 575 if (const auto *RT = getAs<RecordType>()) 576 return RT->getDecl()->isInterface(); 577 return false; 578 } 579 580 bool Type::isStructureOrClassType() const { 581 if (const auto *RT = getAs<RecordType>()) { 582 RecordDecl *RD = RT->getDecl(); 583 return RD->isStruct() || RD->isClass() || RD->isInterface(); 584 } 585 return false; 586 } 587 588 bool Type::isVoidPointerType() const { 589 if (const auto *PT = getAs<PointerType>()) 590 return PT->getPointeeType()->isVoidType(); 591 return false; 592 } 593 594 bool Type::isUnionType() const { 595 if (const auto *RT = getAs<RecordType>()) 596 return RT->getDecl()->isUnion(); 597 return false; 598 } 599 600 bool Type::isComplexType() const { 601 if (const auto *CT = dyn_cast<ComplexType>(CanonicalType)) 602 return CT->getElementType()->isFloatingType(); 603 return false; 604 } 605 606 bool Type::isComplexIntegerType() const { 607 // Check for GCC complex integer extension. 608 return getAsComplexIntegerType(); 609 } 610 611 bool Type::isScopedEnumeralType() const { 612 if (const auto *ET = getAs<EnumType>()) 613 return ET->getDecl()->isScoped(); 614 return false; 615 } 616 617 const ComplexType *Type::getAsComplexIntegerType() const { 618 if (const auto *Complex = getAs<ComplexType>()) 619 if (Complex->getElementType()->isIntegerType()) 620 return Complex; 621 return nullptr; 622 } 623 624 QualType Type::getPointeeType() const { 625 if (const auto *PT = getAs<PointerType>()) 626 return PT->getPointeeType(); 627 if (const auto *OPT = getAs<ObjCObjectPointerType>()) 628 return OPT->getPointeeType(); 629 if (const auto *BPT = getAs<BlockPointerType>()) 630 return BPT->getPointeeType(); 631 if (const auto *RT = getAs<ReferenceType>()) 632 return RT->getPointeeType(); 633 if (const auto *MPT = getAs<MemberPointerType>()) 634 return MPT->getPointeeType(); 635 if (const auto *DT = getAs<DecayedType>()) 636 return DT->getPointeeType(); 637 return {}; 638 } 639 640 const RecordType *Type::getAsStructureType() const { 641 // If this is directly a structure type, return it. 642 if (const auto *RT = dyn_cast<RecordType>(this)) { 643 if (RT->getDecl()->isStruct()) 644 return RT; 645 } 646 647 // If the canonical form of this type isn't the right kind, reject it. 648 if (const auto *RT = dyn_cast<RecordType>(CanonicalType)) { 649 if (!RT->getDecl()->isStruct()) 650 return nullptr; 651 652 // If this is a typedef for a structure type, strip the typedef off without 653 // losing all typedef information. 654 return cast<RecordType>(getUnqualifiedDesugaredType()); 655 } 656 return nullptr; 657 } 658 659 const RecordType *Type::getAsUnionType() const { 660 // If this is directly a union type, return it. 661 if (const auto *RT = dyn_cast<RecordType>(this)) { 662 if (RT->getDecl()->isUnion()) 663 return RT; 664 } 665 666 // If the canonical form of this type isn't the right kind, reject it. 667 if (const auto *RT = dyn_cast<RecordType>(CanonicalType)) { 668 if (!RT->getDecl()->isUnion()) 669 return nullptr; 670 671 // If this is a typedef for a union type, strip the typedef off without 672 // losing all typedef information. 673 return cast<RecordType>(getUnqualifiedDesugaredType()); 674 } 675 676 return nullptr; 677 } 678 679 bool Type::isObjCIdOrObjectKindOfType(const ASTContext &ctx, 680 const ObjCObjectType *&bound) const { 681 bound = nullptr; 682 683 const auto *OPT = getAs<ObjCObjectPointerType>(); 684 if (!OPT) 685 return false; 686 687 // Easy case: id. 688 if (OPT->isObjCIdType()) 689 return true; 690 691 // If it's not a __kindof type, reject it now. 692 if (!OPT->isKindOfType()) 693 return false; 694 695 // If it's Class or qualified Class, it's not an object type. 696 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) 697 return false; 698 699 // Figure out the type bound for the __kindof type. 700 bound = OPT->getObjectType()->stripObjCKindOfTypeAndQuals(ctx) 701 ->getAs<ObjCObjectType>(); 702 return true; 703 } 704 705 bool Type::isObjCClassOrClassKindOfType() const { 706 const auto *OPT = getAs<ObjCObjectPointerType>(); 707 if (!OPT) 708 return false; 709 710 // Easy case: Class. 711 if (OPT->isObjCClassType()) 712 return true; 713 714 // If it's not a __kindof type, reject it now. 715 if (!OPT->isKindOfType()) 716 return false; 717 718 // If it's Class or qualified Class, it's a class __kindof type. 719 return OPT->isObjCClassType() || OPT->isObjCQualifiedClassType(); 720 } 721 722 ObjCTypeParamType::ObjCTypeParamType(const ObjCTypeParamDecl *D, QualType can, 723 ArrayRef<ObjCProtocolDecl *> protocols) 724 : Type(ObjCTypeParam, can, 725 can->getDependence() & ~TypeDependence::UnexpandedPack), 726 OTPDecl(const_cast<ObjCTypeParamDecl *>(D)) { 727 initialize(protocols); 728 } 729 730 ObjCObjectType::ObjCObjectType(QualType Canonical, QualType Base, 731 ArrayRef<QualType> typeArgs, 732 ArrayRef<ObjCProtocolDecl *> protocols, 733 bool isKindOf) 734 : Type(ObjCObject, Canonical, Base->getDependence()), BaseType(Base) { 735 ObjCObjectTypeBits.IsKindOf = isKindOf; 736 737 ObjCObjectTypeBits.NumTypeArgs = typeArgs.size(); 738 assert(getTypeArgsAsWritten().size() == typeArgs.size() && 739 "bitfield overflow in type argument count"); 740 if (!typeArgs.empty()) 741 memcpy(getTypeArgStorage(), typeArgs.data(), 742 typeArgs.size() * sizeof(QualType)); 743 744 for (auto typeArg : typeArgs) { 745 addDependence(typeArg->getDependence() & ~TypeDependence::VariablyModified); 746 } 747 // Initialize the protocol qualifiers. The protocol storage is known 748 // after we set number of type arguments. 749 initialize(protocols); 750 } 751 752 bool ObjCObjectType::isSpecialized() const { 753 // If we have type arguments written here, the type is specialized. 754 if (ObjCObjectTypeBits.NumTypeArgs > 0) 755 return true; 756 757 // Otherwise, check whether the base type is specialized. 758 if (const auto objcObject = getBaseType()->getAs<ObjCObjectType>()) { 759 // Terminate when we reach an interface type. 760 if (isa<ObjCInterfaceType>(objcObject)) 761 return false; 762 763 return objcObject->isSpecialized(); 764 } 765 766 // Not specialized. 767 return false; 768 } 769 770 ArrayRef<QualType> ObjCObjectType::getTypeArgs() const { 771 // We have type arguments written on this type. 772 if (isSpecializedAsWritten()) 773 return getTypeArgsAsWritten(); 774 775 // Look at the base type, which might have type arguments. 776 if (const auto objcObject = getBaseType()->getAs<ObjCObjectType>()) { 777 // Terminate when we reach an interface type. 778 if (isa<ObjCInterfaceType>(objcObject)) 779 return {}; 780 781 return objcObject->getTypeArgs(); 782 } 783 784 // No type arguments. 785 return {}; 786 } 787 788 bool ObjCObjectType::isKindOfType() const { 789 if (isKindOfTypeAsWritten()) 790 return true; 791 792 // Look at the base type, which might have type arguments. 793 if (const auto objcObject = getBaseType()->getAs<ObjCObjectType>()) { 794 // Terminate when we reach an interface type. 795 if (isa<ObjCInterfaceType>(objcObject)) 796 return false; 797 798 return objcObject->isKindOfType(); 799 } 800 801 // Not a "__kindof" type. 802 return false; 803 } 804 805 QualType ObjCObjectType::stripObjCKindOfTypeAndQuals( 806 const ASTContext &ctx) const { 807 if (!isKindOfType() && qual_empty()) 808 return QualType(this, 0); 809 810 // Recursively strip __kindof. 811 SplitQualType splitBaseType = getBaseType().split(); 812 QualType baseType(splitBaseType.Ty, 0); 813 if (const auto *baseObj = splitBaseType.Ty->getAs<ObjCObjectType>()) 814 baseType = baseObj->stripObjCKindOfTypeAndQuals(ctx); 815 816 return ctx.getObjCObjectType(ctx.getQualifiedType(baseType, 817 splitBaseType.Quals), 818 getTypeArgsAsWritten(), 819 /*protocols=*/{}, 820 /*isKindOf=*/false); 821 } 822 823 const ObjCObjectPointerType *ObjCObjectPointerType::stripObjCKindOfTypeAndQuals( 824 const ASTContext &ctx) const { 825 if (!isKindOfType() && qual_empty()) 826 return this; 827 828 QualType obj = getObjectType()->stripObjCKindOfTypeAndQuals(ctx); 829 return ctx.getObjCObjectPointerType(obj)->castAs<ObjCObjectPointerType>(); 830 } 831 832 namespace { 833 834 /// Visitor used to perform a simple type transformation that does not change 835 /// the semantics of the type. 836 template <typename Derived> 837 struct SimpleTransformVisitor : public TypeVisitor<Derived, QualType> { 838 ASTContext &Ctx; 839 840 QualType recurse(QualType type) { 841 // Split out the qualifiers from the type. 842 SplitQualType splitType = type.split(); 843 844 // Visit the type itself. 845 QualType result = static_cast<Derived *>(this)->Visit(splitType.Ty); 846 if (result.isNull()) 847 return result; 848 849 // Reconstruct the transformed type by applying the local qualifiers 850 // from the split type. 851 return Ctx.getQualifiedType(result, splitType.Quals); 852 } 853 854 public: 855 explicit SimpleTransformVisitor(ASTContext &ctx) : Ctx(ctx) {} 856 857 // None of the clients of this transformation can occur where 858 // there are dependent types, so skip dependent types. 859 #define TYPE(Class, Base) 860 #define DEPENDENT_TYPE(Class, Base) \ 861 QualType Visit##Class##Type(const Class##Type *T) { return QualType(T, 0); } 862 #include "clang/AST/TypeNodes.inc" 863 864 #define TRIVIAL_TYPE_CLASS(Class) \ 865 QualType Visit##Class##Type(const Class##Type *T) { return QualType(T, 0); } 866 #define SUGARED_TYPE_CLASS(Class) \ 867 QualType Visit##Class##Type(const Class##Type *T) { \ 868 if (!T->isSugared()) \ 869 return QualType(T, 0); \ 870 QualType desugaredType = recurse(T->desugar()); \ 871 if (desugaredType.isNull()) \ 872 return {}; \ 873 if (desugaredType.getAsOpaquePtr() == T->desugar().getAsOpaquePtr()) \ 874 return QualType(T, 0); \ 875 return desugaredType; \ 876 } 877 878 TRIVIAL_TYPE_CLASS(Builtin) 879 880 QualType VisitComplexType(const ComplexType *T) { 881 QualType elementType = recurse(T->getElementType()); 882 if (elementType.isNull()) 883 return {}; 884 885 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr()) 886 return QualType(T, 0); 887 888 return Ctx.getComplexType(elementType); 889 } 890 891 QualType VisitPointerType(const PointerType *T) { 892 QualType pointeeType = recurse(T->getPointeeType()); 893 if (pointeeType.isNull()) 894 return {}; 895 896 if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr()) 897 return QualType(T, 0); 898 899 return Ctx.getPointerType(pointeeType); 900 } 901 902 QualType VisitBlockPointerType(const BlockPointerType *T) { 903 QualType pointeeType = recurse(T->getPointeeType()); 904 if (pointeeType.isNull()) 905 return {}; 906 907 if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr()) 908 return QualType(T, 0); 909 910 return Ctx.getBlockPointerType(pointeeType); 911 } 912 913 QualType VisitLValueReferenceType(const LValueReferenceType *T) { 914 QualType pointeeType = recurse(T->getPointeeTypeAsWritten()); 915 if (pointeeType.isNull()) 916 return {}; 917 918 if (pointeeType.getAsOpaquePtr() 919 == T->getPointeeTypeAsWritten().getAsOpaquePtr()) 920 return QualType(T, 0); 921 922 return Ctx.getLValueReferenceType(pointeeType, T->isSpelledAsLValue()); 923 } 924 925 QualType VisitRValueReferenceType(const RValueReferenceType *T) { 926 QualType pointeeType = recurse(T->getPointeeTypeAsWritten()); 927 if (pointeeType.isNull()) 928 return {}; 929 930 if (pointeeType.getAsOpaquePtr() 931 == T->getPointeeTypeAsWritten().getAsOpaquePtr()) 932 return QualType(T, 0); 933 934 return Ctx.getRValueReferenceType(pointeeType); 935 } 936 937 QualType VisitMemberPointerType(const MemberPointerType *T) { 938 QualType pointeeType = recurse(T->getPointeeType()); 939 if (pointeeType.isNull()) 940 return {}; 941 942 if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr()) 943 return QualType(T, 0); 944 945 return Ctx.getMemberPointerType(pointeeType, T->getClass()); 946 } 947 948 QualType VisitConstantArrayType(const ConstantArrayType *T) { 949 QualType elementType = recurse(T->getElementType()); 950 if (elementType.isNull()) 951 return {}; 952 953 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr()) 954 return QualType(T, 0); 955 956 return Ctx.getConstantArrayType(elementType, T->getSize(), T->getSizeExpr(), 957 T->getSizeModifier(), 958 T->getIndexTypeCVRQualifiers()); 959 } 960 961 QualType VisitVariableArrayType(const VariableArrayType *T) { 962 QualType elementType = recurse(T->getElementType()); 963 if (elementType.isNull()) 964 return {}; 965 966 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr()) 967 return QualType(T, 0); 968 969 return Ctx.getVariableArrayType(elementType, T->getSizeExpr(), 970 T->getSizeModifier(), 971 T->getIndexTypeCVRQualifiers(), 972 T->getBracketsRange()); 973 } 974 975 QualType VisitIncompleteArrayType(const IncompleteArrayType *T) { 976 QualType elementType = recurse(T->getElementType()); 977 if (elementType.isNull()) 978 return {}; 979 980 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr()) 981 return QualType(T, 0); 982 983 return Ctx.getIncompleteArrayType(elementType, T->getSizeModifier(), 984 T->getIndexTypeCVRQualifiers()); 985 } 986 987 QualType VisitVectorType(const VectorType *T) { 988 QualType elementType = recurse(T->getElementType()); 989 if (elementType.isNull()) 990 return {}; 991 992 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr()) 993 return QualType(T, 0); 994 995 return Ctx.getVectorType(elementType, T->getNumElements(), 996 T->getVectorKind()); 997 } 998 999 QualType VisitExtVectorType(const ExtVectorType *T) { 1000 QualType elementType = recurse(T->getElementType()); 1001 if (elementType.isNull()) 1002 return {}; 1003 1004 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr()) 1005 return QualType(T, 0); 1006 1007 return Ctx.getExtVectorType(elementType, T->getNumElements()); 1008 } 1009 1010 QualType VisitConstantMatrixType(const ConstantMatrixType *T) { 1011 QualType elementType = recurse(T->getElementType()); 1012 if (elementType.isNull()) 1013 return {}; 1014 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr()) 1015 return QualType(T, 0); 1016 1017 return Ctx.getConstantMatrixType(elementType, T->getNumRows(), 1018 T->getNumColumns()); 1019 } 1020 1021 QualType VisitFunctionNoProtoType(const FunctionNoProtoType *T) { 1022 QualType returnType = recurse(T->getReturnType()); 1023 if (returnType.isNull()) 1024 return {}; 1025 1026 if (returnType.getAsOpaquePtr() == T->getReturnType().getAsOpaquePtr()) 1027 return QualType(T, 0); 1028 1029 return Ctx.getFunctionNoProtoType(returnType, T->getExtInfo()); 1030 } 1031 1032 QualType VisitFunctionProtoType(const FunctionProtoType *T) { 1033 QualType returnType = recurse(T->getReturnType()); 1034 if (returnType.isNull()) 1035 return {}; 1036 1037 // Transform parameter types. 1038 SmallVector<QualType, 4> paramTypes; 1039 bool paramChanged = false; 1040 for (auto paramType : T->getParamTypes()) { 1041 QualType newParamType = recurse(paramType); 1042 if (newParamType.isNull()) 1043 return {}; 1044 1045 if (newParamType.getAsOpaquePtr() != paramType.getAsOpaquePtr()) 1046 paramChanged = true; 1047 1048 paramTypes.push_back(newParamType); 1049 } 1050 1051 // Transform extended info. 1052 FunctionProtoType::ExtProtoInfo info = T->getExtProtoInfo(); 1053 bool exceptionChanged = false; 1054 if (info.ExceptionSpec.Type == EST_Dynamic) { 1055 SmallVector<QualType, 4> exceptionTypes; 1056 for (auto exceptionType : info.ExceptionSpec.Exceptions) { 1057 QualType newExceptionType = recurse(exceptionType); 1058 if (newExceptionType.isNull()) 1059 return {}; 1060 1061 if (newExceptionType.getAsOpaquePtr() != exceptionType.getAsOpaquePtr()) 1062 exceptionChanged = true; 1063 1064 exceptionTypes.push_back(newExceptionType); 1065 } 1066 1067 if (exceptionChanged) { 1068 info.ExceptionSpec.Exceptions = 1069 llvm::makeArrayRef(exceptionTypes).copy(Ctx); 1070 } 1071 } 1072 1073 if (returnType.getAsOpaquePtr() == T->getReturnType().getAsOpaquePtr() && 1074 !paramChanged && !exceptionChanged) 1075 return QualType(T, 0); 1076 1077 return Ctx.getFunctionType(returnType, paramTypes, info); 1078 } 1079 1080 QualType VisitParenType(const ParenType *T) { 1081 QualType innerType = recurse(T->getInnerType()); 1082 if (innerType.isNull()) 1083 return {}; 1084 1085 if (innerType.getAsOpaquePtr() == T->getInnerType().getAsOpaquePtr()) 1086 return QualType(T, 0); 1087 1088 return Ctx.getParenType(innerType); 1089 } 1090 1091 SUGARED_TYPE_CLASS(Typedef) 1092 SUGARED_TYPE_CLASS(ObjCTypeParam) 1093 SUGARED_TYPE_CLASS(MacroQualified) 1094 1095 QualType VisitAdjustedType(const AdjustedType *T) { 1096 QualType originalType = recurse(T->getOriginalType()); 1097 if (originalType.isNull()) 1098 return {}; 1099 1100 QualType adjustedType = recurse(T->getAdjustedType()); 1101 if (adjustedType.isNull()) 1102 return {}; 1103 1104 if (originalType.getAsOpaquePtr() 1105 == T->getOriginalType().getAsOpaquePtr() && 1106 adjustedType.getAsOpaquePtr() == T->getAdjustedType().getAsOpaquePtr()) 1107 return QualType(T, 0); 1108 1109 return Ctx.getAdjustedType(originalType, adjustedType); 1110 } 1111 1112 QualType VisitDecayedType(const DecayedType *T) { 1113 QualType originalType = recurse(T->getOriginalType()); 1114 if (originalType.isNull()) 1115 return {}; 1116 1117 if (originalType.getAsOpaquePtr() 1118 == T->getOriginalType().getAsOpaquePtr()) 1119 return QualType(T, 0); 1120 1121 return Ctx.getDecayedType(originalType); 1122 } 1123 1124 SUGARED_TYPE_CLASS(TypeOfExpr) 1125 SUGARED_TYPE_CLASS(TypeOf) 1126 SUGARED_TYPE_CLASS(Decltype) 1127 SUGARED_TYPE_CLASS(UnaryTransform) 1128 TRIVIAL_TYPE_CLASS(Record) 1129 TRIVIAL_TYPE_CLASS(Enum) 1130 1131 // FIXME: Non-trivial to implement, but important for C++ 1132 SUGARED_TYPE_CLASS(Elaborated) 1133 1134 QualType VisitAttributedType(const AttributedType *T) { 1135 QualType modifiedType = recurse(T->getModifiedType()); 1136 if (modifiedType.isNull()) 1137 return {}; 1138 1139 QualType equivalentType = recurse(T->getEquivalentType()); 1140 if (equivalentType.isNull()) 1141 return {}; 1142 1143 if (modifiedType.getAsOpaquePtr() 1144 == T->getModifiedType().getAsOpaquePtr() && 1145 equivalentType.getAsOpaquePtr() 1146 == T->getEquivalentType().getAsOpaquePtr()) 1147 return QualType(T, 0); 1148 1149 return Ctx.getAttributedType(T->getAttrKind(), modifiedType, 1150 equivalentType); 1151 } 1152 1153 QualType VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) { 1154 QualType replacementType = recurse(T->getReplacementType()); 1155 if (replacementType.isNull()) 1156 return {}; 1157 1158 if (replacementType.getAsOpaquePtr() 1159 == T->getReplacementType().getAsOpaquePtr()) 1160 return QualType(T, 0); 1161 1162 return Ctx.getSubstTemplateTypeParmType(T->getReplacedParameter(), 1163 replacementType); 1164 } 1165 1166 // FIXME: Non-trivial to implement, but important for C++ 1167 SUGARED_TYPE_CLASS(TemplateSpecialization) 1168 1169 QualType VisitAutoType(const AutoType *T) { 1170 if (!T->isDeduced()) 1171 return QualType(T, 0); 1172 1173 QualType deducedType = recurse(T->getDeducedType()); 1174 if (deducedType.isNull()) 1175 return {}; 1176 1177 if (deducedType.getAsOpaquePtr() 1178 == T->getDeducedType().getAsOpaquePtr()) 1179 return QualType(T, 0); 1180 1181 return Ctx.getAutoType(deducedType, T->getKeyword(), 1182 T->isDependentType(), /*IsPack=*/false, 1183 T->getTypeConstraintConcept(), 1184 T->getTypeConstraintArguments()); 1185 } 1186 1187 QualType VisitObjCObjectType(const ObjCObjectType *T) { 1188 QualType baseType = recurse(T->getBaseType()); 1189 if (baseType.isNull()) 1190 return {}; 1191 1192 // Transform type arguments. 1193 bool typeArgChanged = false; 1194 SmallVector<QualType, 4> typeArgs; 1195 for (auto typeArg : T->getTypeArgsAsWritten()) { 1196 QualType newTypeArg = recurse(typeArg); 1197 if (newTypeArg.isNull()) 1198 return {}; 1199 1200 if (newTypeArg.getAsOpaquePtr() != typeArg.getAsOpaquePtr()) 1201 typeArgChanged = true; 1202 1203 typeArgs.push_back(newTypeArg); 1204 } 1205 1206 if (baseType.getAsOpaquePtr() == T->getBaseType().getAsOpaquePtr() && 1207 !typeArgChanged) 1208 return QualType(T, 0); 1209 1210 return Ctx.getObjCObjectType(baseType, typeArgs, 1211 llvm::makeArrayRef(T->qual_begin(), 1212 T->getNumProtocols()), 1213 T->isKindOfTypeAsWritten()); 1214 } 1215 1216 TRIVIAL_TYPE_CLASS(ObjCInterface) 1217 1218 QualType VisitObjCObjectPointerType(const ObjCObjectPointerType *T) { 1219 QualType pointeeType = recurse(T->getPointeeType()); 1220 if (pointeeType.isNull()) 1221 return {}; 1222 1223 if (pointeeType.getAsOpaquePtr() 1224 == T->getPointeeType().getAsOpaquePtr()) 1225 return QualType(T, 0); 1226 1227 return Ctx.getObjCObjectPointerType(pointeeType); 1228 } 1229 1230 QualType VisitAtomicType(const AtomicType *T) { 1231 QualType valueType = recurse(T->getValueType()); 1232 if (valueType.isNull()) 1233 return {}; 1234 1235 if (valueType.getAsOpaquePtr() 1236 == T->getValueType().getAsOpaquePtr()) 1237 return QualType(T, 0); 1238 1239 return Ctx.getAtomicType(valueType); 1240 } 1241 1242 #undef TRIVIAL_TYPE_CLASS 1243 #undef SUGARED_TYPE_CLASS 1244 }; 1245 1246 struct SubstObjCTypeArgsVisitor 1247 : public SimpleTransformVisitor<SubstObjCTypeArgsVisitor> { 1248 using BaseType = SimpleTransformVisitor<SubstObjCTypeArgsVisitor>; 1249 1250 ArrayRef<QualType> TypeArgs; 1251 ObjCSubstitutionContext SubstContext; 1252 1253 SubstObjCTypeArgsVisitor(ASTContext &ctx, ArrayRef<QualType> typeArgs, 1254 ObjCSubstitutionContext context) 1255 : BaseType(ctx), TypeArgs(typeArgs), SubstContext(context) {} 1256 1257 QualType VisitObjCTypeParamType(const ObjCTypeParamType *OTPTy) { 1258 // Replace an Objective-C type parameter reference with the corresponding 1259 // type argument. 1260 ObjCTypeParamDecl *typeParam = OTPTy->getDecl(); 1261 // If we have type arguments, use them. 1262 if (!TypeArgs.empty()) { 1263 QualType argType = TypeArgs[typeParam->getIndex()]; 1264 if (OTPTy->qual_empty()) 1265 return argType; 1266 1267 // Apply protocol lists if exists. 1268 bool hasError; 1269 SmallVector<ObjCProtocolDecl *, 8> protocolsVec; 1270 protocolsVec.append(OTPTy->qual_begin(), OTPTy->qual_end()); 1271 ArrayRef<ObjCProtocolDecl *> protocolsToApply = protocolsVec; 1272 return Ctx.applyObjCProtocolQualifiers( 1273 argType, protocolsToApply, hasError, true/*allowOnPointerType*/); 1274 } 1275 1276 switch (SubstContext) { 1277 case ObjCSubstitutionContext::Ordinary: 1278 case ObjCSubstitutionContext::Parameter: 1279 case ObjCSubstitutionContext::Superclass: 1280 // Substitute the bound. 1281 return typeParam->getUnderlyingType(); 1282 1283 case ObjCSubstitutionContext::Result: 1284 case ObjCSubstitutionContext::Property: { 1285 // Substitute the __kindof form of the underlying type. 1286 const auto *objPtr = 1287 typeParam->getUnderlyingType()->castAs<ObjCObjectPointerType>(); 1288 1289 // __kindof types, id, and Class don't need an additional 1290 // __kindof. 1291 if (objPtr->isKindOfType() || objPtr->isObjCIdOrClassType()) 1292 return typeParam->getUnderlyingType(); 1293 1294 // Add __kindof. 1295 const auto *obj = objPtr->getObjectType(); 1296 QualType resultTy = Ctx.getObjCObjectType( 1297 obj->getBaseType(), obj->getTypeArgsAsWritten(), obj->getProtocols(), 1298 /*isKindOf=*/true); 1299 1300 // Rebuild object pointer type. 1301 return Ctx.getObjCObjectPointerType(resultTy); 1302 } 1303 } 1304 llvm_unreachable("Unexpected ObjCSubstitutionContext!"); 1305 } 1306 1307 QualType VisitFunctionType(const FunctionType *funcType) { 1308 // If we have a function type, update the substitution context 1309 // appropriately. 1310 1311 //Substitute result type. 1312 QualType returnType = funcType->getReturnType().substObjCTypeArgs( 1313 Ctx, TypeArgs, ObjCSubstitutionContext::Result); 1314 if (returnType.isNull()) 1315 return {}; 1316 1317 // Handle non-prototyped functions, which only substitute into the result 1318 // type. 1319 if (isa<FunctionNoProtoType>(funcType)) { 1320 // If the return type was unchanged, do nothing. 1321 if (returnType.getAsOpaquePtr() == 1322 funcType->getReturnType().getAsOpaquePtr()) 1323 return BaseType::VisitFunctionType(funcType); 1324 1325 // Otherwise, build a new type. 1326 return Ctx.getFunctionNoProtoType(returnType, funcType->getExtInfo()); 1327 } 1328 1329 const auto *funcProtoType = cast<FunctionProtoType>(funcType); 1330 1331 // Transform parameter types. 1332 SmallVector<QualType, 4> paramTypes; 1333 bool paramChanged = false; 1334 for (auto paramType : funcProtoType->getParamTypes()) { 1335 QualType newParamType = paramType.substObjCTypeArgs( 1336 Ctx, TypeArgs, ObjCSubstitutionContext::Parameter); 1337 if (newParamType.isNull()) 1338 return {}; 1339 1340 if (newParamType.getAsOpaquePtr() != paramType.getAsOpaquePtr()) 1341 paramChanged = true; 1342 1343 paramTypes.push_back(newParamType); 1344 } 1345 1346 // Transform extended info. 1347 FunctionProtoType::ExtProtoInfo info = funcProtoType->getExtProtoInfo(); 1348 bool exceptionChanged = false; 1349 if (info.ExceptionSpec.Type == EST_Dynamic) { 1350 SmallVector<QualType, 4> exceptionTypes; 1351 for (auto exceptionType : info.ExceptionSpec.Exceptions) { 1352 QualType newExceptionType = exceptionType.substObjCTypeArgs( 1353 Ctx, TypeArgs, ObjCSubstitutionContext::Ordinary); 1354 if (newExceptionType.isNull()) 1355 return {}; 1356 1357 if (newExceptionType.getAsOpaquePtr() != exceptionType.getAsOpaquePtr()) 1358 exceptionChanged = true; 1359 1360 exceptionTypes.push_back(newExceptionType); 1361 } 1362 1363 if (exceptionChanged) { 1364 info.ExceptionSpec.Exceptions = 1365 llvm::makeArrayRef(exceptionTypes).copy(Ctx); 1366 } 1367 } 1368 1369 if (returnType.getAsOpaquePtr() == 1370 funcProtoType->getReturnType().getAsOpaquePtr() && 1371 !paramChanged && !exceptionChanged) 1372 return BaseType::VisitFunctionType(funcType); 1373 1374 return Ctx.getFunctionType(returnType, paramTypes, info); 1375 } 1376 1377 QualType VisitObjCObjectType(const ObjCObjectType *objcObjectType) { 1378 // Substitute into the type arguments of a specialized Objective-C object 1379 // type. 1380 if (objcObjectType->isSpecializedAsWritten()) { 1381 SmallVector<QualType, 4> newTypeArgs; 1382 bool anyChanged = false; 1383 for (auto typeArg : objcObjectType->getTypeArgsAsWritten()) { 1384 QualType newTypeArg = typeArg.substObjCTypeArgs( 1385 Ctx, TypeArgs, ObjCSubstitutionContext::Ordinary); 1386 if (newTypeArg.isNull()) 1387 return {}; 1388 1389 if (newTypeArg.getAsOpaquePtr() != typeArg.getAsOpaquePtr()) { 1390 // If we're substituting based on an unspecialized context type, 1391 // produce an unspecialized type. 1392 ArrayRef<ObjCProtocolDecl *> protocols( 1393 objcObjectType->qual_begin(), objcObjectType->getNumProtocols()); 1394 if (TypeArgs.empty() && 1395 SubstContext != ObjCSubstitutionContext::Superclass) { 1396 return Ctx.getObjCObjectType( 1397 objcObjectType->getBaseType(), {}, protocols, 1398 objcObjectType->isKindOfTypeAsWritten()); 1399 } 1400 1401 anyChanged = true; 1402 } 1403 1404 newTypeArgs.push_back(newTypeArg); 1405 } 1406 1407 if (anyChanged) { 1408 ArrayRef<ObjCProtocolDecl *> protocols( 1409 objcObjectType->qual_begin(), objcObjectType->getNumProtocols()); 1410 return Ctx.getObjCObjectType(objcObjectType->getBaseType(), newTypeArgs, 1411 protocols, 1412 objcObjectType->isKindOfTypeAsWritten()); 1413 } 1414 } 1415 1416 return BaseType::VisitObjCObjectType(objcObjectType); 1417 } 1418 1419 QualType VisitAttributedType(const AttributedType *attrType) { 1420 QualType newType = BaseType::VisitAttributedType(attrType); 1421 if (newType.isNull()) 1422 return {}; 1423 1424 const auto *newAttrType = dyn_cast<AttributedType>(newType.getTypePtr()); 1425 if (!newAttrType || newAttrType->getAttrKind() != attr::ObjCKindOf) 1426 return newType; 1427 1428 // Find out if it's an Objective-C object or object pointer type; 1429 QualType newEquivType = newAttrType->getEquivalentType(); 1430 const ObjCObjectPointerType *ptrType = 1431 newEquivType->getAs<ObjCObjectPointerType>(); 1432 const ObjCObjectType *objType = ptrType 1433 ? ptrType->getObjectType() 1434 : newEquivType->getAs<ObjCObjectType>(); 1435 if (!objType) 1436 return newType; 1437 1438 // Rebuild the "equivalent" type, which pushes __kindof down into 1439 // the object type. 1440 newEquivType = Ctx.getObjCObjectType( 1441 objType->getBaseType(), objType->getTypeArgsAsWritten(), 1442 objType->getProtocols(), 1443 // There is no need to apply kindof on an unqualified id type. 1444 /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true); 1445 1446 // If we started with an object pointer type, rebuild it. 1447 if (ptrType) 1448 newEquivType = Ctx.getObjCObjectPointerType(newEquivType); 1449 1450 // Rebuild the attributed type. 1451 return Ctx.getAttributedType(newAttrType->getAttrKind(), 1452 newAttrType->getModifiedType(), newEquivType); 1453 } 1454 }; 1455 1456 struct StripObjCKindOfTypeVisitor 1457 : public SimpleTransformVisitor<StripObjCKindOfTypeVisitor> { 1458 using BaseType = SimpleTransformVisitor<StripObjCKindOfTypeVisitor>; 1459 1460 explicit StripObjCKindOfTypeVisitor(ASTContext &ctx) : BaseType(ctx) {} 1461 1462 QualType VisitObjCObjectType(const ObjCObjectType *objType) { 1463 if (!objType->isKindOfType()) 1464 return BaseType::VisitObjCObjectType(objType); 1465 1466 QualType baseType = objType->getBaseType().stripObjCKindOfType(Ctx); 1467 return Ctx.getObjCObjectType(baseType, objType->getTypeArgsAsWritten(), 1468 objType->getProtocols(), 1469 /*isKindOf=*/false); 1470 } 1471 }; 1472 1473 } // namespace 1474 1475 /// Substitute the given type arguments for Objective-C type 1476 /// parameters within the given type, recursively. 1477 QualType QualType::substObjCTypeArgs(ASTContext &ctx, 1478 ArrayRef<QualType> typeArgs, 1479 ObjCSubstitutionContext context) const { 1480 SubstObjCTypeArgsVisitor visitor(ctx, typeArgs, context); 1481 return visitor.recurse(*this); 1482 } 1483 1484 QualType QualType::substObjCMemberType(QualType objectType, 1485 const DeclContext *dc, 1486 ObjCSubstitutionContext context) const { 1487 if (auto subs = objectType->getObjCSubstitutions(dc)) 1488 return substObjCTypeArgs(dc->getParentASTContext(), *subs, context); 1489 1490 return *this; 1491 } 1492 1493 QualType QualType::stripObjCKindOfType(const ASTContext &constCtx) const { 1494 // FIXME: Because ASTContext::getAttributedType() is non-const. 1495 auto &ctx = const_cast<ASTContext &>(constCtx); 1496 StripObjCKindOfTypeVisitor visitor(ctx); 1497 return visitor.recurse(*this); 1498 } 1499 1500 QualType QualType::getAtomicUnqualifiedType() const { 1501 if (const auto AT = getTypePtr()->getAs<AtomicType>()) 1502 return AT->getValueType().getUnqualifiedType(); 1503 return getUnqualifiedType(); 1504 } 1505 1506 Optional<ArrayRef<QualType>> Type::getObjCSubstitutions( 1507 const DeclContext *dc) const { 1508 // Look through method scopes. 1509 if (const auto method = dyn_cast<ObjCMethodDecl>(dc)) 1510 dc = method->getDeclContext(); 1511 1512 // Find the class or category in which the type we're substituting 1513 // was declared. 1514 const auto *dcClassDecl = dyn_cast<ObjCInterfaceDecl>(dc); 1515 const ObjCCategoryDecl *dcCategoryDecl = nullptr; 1516 ObjCTypeParamList *dcTypeParams = nullptr; 1517 if (dcClassDecl) { 1518 // If the class does not have any type parameters, there's no 1519 // substitution to do. 1520 dcTypeParams = dcClassDecl->getTypeParamList(); 1521 if (!dcTypeParams) 1522 return None; 1523 } else { 1524 // If we are in neither a class nor a category, there's no 1525 // substitution to perform. 1526 dcCategoryDecl = dyn_cast<ObjCCategoryDecl>(dc); 1527 if (!dcCategoryDecl) 1528 return None; 1529 1530 // If the category does not have any type parameters, there's no 1531 // substitution to do. 1532 dcTypeParams = dcCategoryDecl->getTypeParamList(); 1533 if (!dcTypeParams) 1534 return None; 1535 1536 dcClassDecl = dcCategoryDecl->getClassInterface(); 1537 if (!dcClassDecl) 1538 return None; 1539 } 1540 assert(dcTypeParams && "No substitutions to perform"); 1541 assert(dcClassDecl && "No class context"); 1542 1543 // Find the underlying object type. 1544 const ObjCObjectType *objectType; 1545 if (const auto *objectPointerType = getAs<ObjCObjectPointerType>()) { 1546 objectType = objectPointerType->getObjectType(); 1547 } else if (getAs<BlockPointerType>()) { 1548 ASTContext &ctx = dc->getParentASTContext(); 1549 objectType = ctx.getObjCObjectType(ctx.ObjCBuiltinIdTy, {}, {}) 1550 ->castAs<ObjCObjectType>(); 1551 } else { 1552 objectType = getAs<ObjCObjectType>(); 1553 } 1554 1555 /// Extract the class from the receiver object type. 1556 ObjCInterfaceDecl *curClassDecl = objectType ? objectType->getInterface() 1557 : nullptr; 1558 if (!curClassDecl) { 1559 // If we don't have a context type (e.g., this is "id" or some 1560 // variant thereof), substitute the bounds. 1561 return llvm::ArrayRef<QualType>(); 1562 } 1563 1564 // Follow the superclass chain until we've mapped the receiver type 1565 // to the same class as the context. 1566 while (curClassDecl != dcClassDecl) { 1567 // Map to the superclass type. 1568 QualType superType = objectType->getSuperClassType(); 1569 if (superType.isNull()) { 1570 objectType = nullptr; 1571 break; 1572 } 1573 1574 objectType = superType->castAs<ObjCObjectType>(); 1575 curClassDecl = objectType->getInterface(); 1576 } 1577 1578 // If we don't have a receiver type, or the receiver type does not 1579 // have type arguments, substitute in the defaults. 1580 if (!objectType || objectType->isUnspecialized()) { 1581 return llvm::ArrayRef<QualType>(); 1582 } 1583 1584 // The receiver type has the type arguments we want. 1585 return objectType->getTypeArgs(); 1586 } 1587 1588 bool Type::acceptsObjCTypeParams() const { 1589 if (auto *IfaceT = getAsObjCInterfaceType()) { 1590 if (auto *ID = IfaceT->getInterface()) { 1591 if (ID->getTypeParamList()) 1592 return true; 1593 } 1594 } 1595 1596 return false; 1597 } 1598 1599 void ObjCObjectType::computeSuperClassTypeSlow() const { 1600 // Retrieve the class declaration for this type. If there isn't one 1601 // (e.g., this is some variant of "id" or "Class"), then there is no 1602 // superclass type. 1603 ObjCInterfaceDecl *classDecl = getInterface(); 1604 if (!classDecl) { 1605 CachedSuperClassType.setInt(true); 1606 return; 1607 } 1608 1609 // Extract the superclass type. 1610 const ObjCObjectType *superClassObjTy = classDecl->getSuperClassType(); 1611 if (!superClassObjTy) { 1612 CachedSuperClassType.setInt(true); 1613 return; 1614 } 1615 1616 ObjCInterfaceDecl *superClassDecl = superClassObjTy->getInterface(); 1617 if (!superClassDecl) { 1618 CachedSuperClassType.setInt(true); 1619 return; 1620 } 1621 1622 // If the superclass doesn't have type parameters, then there is no 1623 // substitution to perform. 1624 QualType superClassType(superClassObjTy, 0); 1625 ObjCTypeParamList *superClassTypeParams = superClassDecl->getTypeParamList(); 1626 if (!superClassTypeParams) { 1627 CachedSuperClassType.setPointerAndInt( 1628 superClassType->castAs<ObjCObjectType>(), true); 1629 return; 1630 } 1631 1632 // If the superclass reference is unspecialized, return it. 1633 if (superClassObjTy->isUnspecialized()) { 1634 CachedSuperClassType.setPointerAndInt(superClassObjTy, true); 1635 return; 1636 } 1637 1638 // If the subclass is not parameterized, there aren't any type 1639 // parameters in the superclass reference to substitute. 1640 ObjCTypeParamList *typeParams = classDecl->getTypeParamList(); 1641 if (!typeParams) { 1642 CachedSuperClassType.setPointerAndInt( 1643 superClassType->castAs<ObjCObjectType>(), true); 1644 return; 1645 } 1646 1647 // If the subclass type isn't specialized, return the unspecialized 1648 // superclass. 1649 if (isUnspecialized()) { 1650 QualType unspecializedSuper 1651 = classDecl->getASTContext().getObjCInterfaceType( 1652 superClassObjTy->getInterface()); 1653 CachedSuperClassType.setPointerAndInt( 1654 unspecializedSuper->castAs<ObjCObjectType>(), 1655 true); 1656 return; 1657 } 1658 1659 // Substitute the provided type arguments into the superclass type. 1660 ArrayRef<QualType> typeArgs = getTypeArgs(); 1661 assert(typeArgs.size() == typeParams->size()); 1662 CachedSuperClassType.setPointerAndInt( 1663 superClassType.substObjCTypeArgs(classDecl->getASTContext(), typeArgs, 1664 ObjCSubstitutionContext::Superclass) 1665 ->castAs<ObjCObjectType>(), 1666 true); 1667 } 1668 1669 const ObjCInterfaceType *ObjCObjectPointerType::getInterfaceType() const { 1670 if (auto interfaceDecl = getObjectType()->getInterface()) { 1671 return interfaceDecl->getASTContext().getObjCInterfaceType(interfaceDecl) 1672 ->castAs<ObjCInterfaceType>(); 1673 } 1674 1675 return nullptr; 1676 } 1677 1678 QualType ObjCObjectPointerType::getSuperClassType() const { 1679 QualType superObjectType = getObjectType()->getSuperClassType(); 1680 if (superObjectType.isNull()) 1681 return superObjectType; 1682 1683 ASTContext &ctx = getInterfaceDecl()->getASTContext(); 1684 return ctx.getObjCObjectPointerType(superObjectType); 1685 } 1686 1687 const ObjCObjectType *Type::getAsObjCQualifiedInterfaceType() const { 1688 // There is no sugar for ObjCObjectType's, just return the canonical 1689 // type pointer if it is the right class. There is no typedef information to 1690 // return and these cannot be Address-space qualified. 1691 if (const auto *T = getAs<ObjCObjectType>()) 1692 if (T->getNumProtocols() && T->getInterface()) 1693 return T; 1694 return nullptr; 1695 } 1696 1697 bool Type::isObjCQualifiedInterfaceType() const { 1698 return getAsObjCQualifiedInterfaceType() != nullptr; 1699 } 1700 1701 const ObjCObjectPointerType *Type::getAsObjCQualifiedIdType() const { 1702 // There is no sugar for ObjCQualifiedIdType's, just return the canonical 1703 // type pointer if it is the right class. 1704 if (const auto *OPT = getAs<ObjCObjectPointerType>()) { 1705 if (OPT->isObjCQualifiedIdType()) 1706 return OPT; 1707 } 1708 return nullptr; 1709 } 1710 1711 const ObjCObjectPointerType *Type::getAsObjCQualifiedClassType() const { 1712 // There is no sugar for ObjCQualifiedClassType's, just return the canonical 1713 // type pointer if it is the right class. 1714 if (const auto *OPT = getAs<ObjCObjectPointerType>()) { 1715 if (OPT->isObjCQualifiedClassType()) 1716 return OPT; 1717 } 1718 return nullptr; 1719 } 1720 1721 const ObjCObjectType *Type::getAsObjCInterfaceType() const { 1722 if (const auto *OT = getAs<ObjCObjectType>()) { 1723 if (OT->getInterface()) 1724 return OT; 1725 } 1726 return nullptr; 1727 } 1728 1729 const ObjCObjectPointerType *Type::getAsObjCInterfacePointerType() const { 1730 if (const auto *OPT = getAs<ObjCObjectPointerType>()) { 1731 if (OPT->getInterfaceType()) 1732 return OPT; 1733 } 1734 return nullptr; 1735 } 1736 1737 const CXXRecordDecl *Type::getPointeeCXXRecordDecl() const { 1738 QualType PointeeType; 1739 if (const auto *PT = getAs<PointerType>()) 1740 PointeeType = PT->getPointeeType(); 1741 else if (const auto *RT = getAs<ReferenceType>()) 1742 PointeeType = RT->getPointeeType(); 1743 else 1744 return nullptr; 1745 1746 if (const auto *RT = PointeeType->getAs<RecordType>()) 1747 return dyn_cast<CXXRecordDecl>(RT->getDecl()); 1748 1749 return nullptr; 1750 } 1751 1752 CXXRecordDecl *Type::getAsCXXRecordDecl() const { 1753 return dyn_cast_or_null<CXXRecordDecl>(getAsTagDecl()); 1754 } 1755 1756 RecordDecl *Type::getAsRecordDecl() const { 1757 return dyn_cast_or_null<RecordDecl>(getAsTagDecl()); 1758 } 1759 1760 TagDecl *Type::getAsTagDecl() const { 1761 if (const auto *TT = getAs<TagType>()) 1762 return TT->getDecl(); 1763 if (const auto *Injected = getAs<InjectedClassNameType>()) 1764 return Injected->getDecl(); 1765 1766 return nullptr; 1767 } 1768 1769 bool Type::hasAttr(attr::Kind AK) const { 1770 const Type *Cur = this; 1771 while (const auto *AT = Cur->getAs<AttributedType>()) { 1772 if (AT->getAttrKind() == AK) 1773 return true; 1774 Cur = AT->getEquivalentType().getTypePtr(); 1775 } 1776 return false; 1777 } 1778 1779 namespace { 1780 1781 class GetContainedDeducedTypeVisitor : 1782 public TypeVisitor<GetContainedDeducedTypeVisitor, Type*> { 1783 bool Syntactic; 1784 1785 public: 1786 GetContainedDeducedTypeVisitor(bool Syntactic = false) 1787 : Syntactic(Syntactic) {} 1788 1789 using TypeVisitor<GetContainedDeducedTypeVisitor, Type*>::Visit; 1790 1791 Type *Visit(QualType T) { 1792 if (T.isNull()) 1793 return nullptr; 1794 return Visit(T.getTypePtr()); 1795 } 1796 1797 // The deduced type itself. 1798 Type *VisitDeducedType(const DeducedType *AT) { 1799 return const_cast<DeducedType*>(AT); 1800 } 1801 1802 // Only these types can contain the desired 'auto' type. 1803 1804 Type *VisitElaboratedType(const ElaboratedType *T) { 1805 return Visit(T->getNamedType()); 1806 } 1807 1808 Type *VisitPointerType(const PointerType *T) { 1809 return Visit(T->getPointeeType()); 1810 } 1811 1812 Type *VisitBlockPointerType(const BlockPointerType *T) { 1813 return Visit(T->getPointeeType()); 1814 } 1815 1816 Type *VisitReferenceType(const ReferenceType *T) { 1817 return Visit(T->getPointeeTypeAsWritten()); 1818 } 1819 1820 Type *VisitMemberPointerType(const MemberPointerType *T) { 1821 return Visit(T->getPointeeType()); 1822 } 1823 1824 Type *VisitArrayType(const ArrayType *T) { 1825 return Visit(T->getElementType()); 1826 } 1827 1828 Type *VisitDependentSizedExtVectorType( 1829 const DependentSizedExtVectorType *T) { 1830 return Visit(T->getElementType()); 1831 } 1832 1833 Type *VisitVectorType(const VectorType *T) { 1834 return Visit(T->getElementType()); 1835 } 1836 1837 Type *VisitDependentSizedMatrixType(const DependentSizedMatrixType *T) { 1838 return Visit(T->getElementType()); 1839 } 1840 1841 Type *VisitConstantMatrixType(const ConstantMatrixType *T) { 1842 return Visit(T->getElementType()); 1843 } 1844 1845 Type *VisitFunctionProtoType(const FunctionProtoType *T) { 1846 if (Syntactic && T->hasTrailingReturn()) 1847 return const_cast<FunctionProtoType*>(T); 1848 return VisitFunctionType(T); 1849 } 1850 1851 Type *VisitFunctionType(const FunctionType *T) { 1852 return Visit(T->getReturnType()); 1853 } 1854 1855 Type *VisitParenType(const ParenType *T) { 1856 return Visit(T->getInnerType()); 1857 } 1858 1859 Type *VisitAttributedType(const AttributedType *T) { 1860 return Visit(T->getModifiedType()); 1861 } 1862 1863 Type *VisitMacroQualifiedType(const MacroQualifiedType *T) { 1864 return Visit(T->getUnderlyingType()); 1865 } 1866 1867 Type *VisitAdjustedType(const AdjustedType *T) { 1868 return Visit(T->getOriginalType()); 1869 } 1870 1871 Type *VisitPackExpansionType(const PackExpansionType *T) { 1872 return Visit(T->getPattern()); 1873 } 1874 }; 1875 1876 } // namespace 1877 1878 DeducedType *Type::getContainedDeducedType() const { 1879 return cast_or_null<DeducedType>( 1880 GetContainedDeducedTypeVisitor().Visit(this)); 1881 } 1882 1883 bool Type::hasAutoForTrailingReturnType() const { 1884 return dyn_cast_or_null<FunctionType>( 1885 GetContainedDeducedTypeVisitor(true).Visit(this)); 1886 } 1887 1888 bool Type::hasIntegerRepresentation() const { 1889 if (const auto *VT = dyn_cast<VectorType>(CanonicalType)) 1890 return VT->getElementType()->isIntegerType(); 1891 else 1892 return isIntegerType(); 1893 } 1894 1895 /// Determine whether this type is an integral type. 1896 /// 1897 /// This routine determines whether the given type is an integral type per 1898 /// C++ [basic.fundamental]p7. Although the C standard does not define the 1899 /// term "integral type", it has a similar term "integer type", and in C++ 1900 /// the two terms are equivalent. However, C's "integer type" includes 1901 /// enumeration types, while C++'s "integer type" does not. The \c ASTContext 1902 /// parameter is used to determine whether we should be following the C or 1903 /// C++ rules when determining whether this type is an integral/integer type. 1904 /// 1905 /// For cases where C permits "an integer type" and C++ permits "an integral 1906 /// type", use this routine. 1907 /// 1908 /// For cases where C permits "an integer type" and C++ permits "an integral 1909 /// or enumeration type", use \c isIntegralOrEnumerationType() instead. 1910 /// 1911 /// \param Ctx The context in which this type occurs. 1912 /// 1913 /// \returns true if the type is considered an integral type, false otherwise. 1914 bool Type::isIntegralType(const ASTContext &Ctx) const { 1915 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) 1916 return BT->getKind() >= BuiltinType::Bool && 1917 BT->getKind() <= BuiltinType::Int128; 1918 1919 // Complete enum types are integral in C. 1920 if (!Ctx.getLangOpts().CPlusPlus) 1921 if (const auto *ET = dyn_cast<EnumType>(CanonicalType)) 1922 return ET->getDecl()->isComplete(); 1923 1924 return isExtIntType(); 1925 } 1926 1927 bool Type::isIntegralOrUnscopedEnumerationType() const { 1928 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) 1929 return BT->getKind() >= BuiltinType::Bool && 1930 BT->getKind() <= BuiltinType::Int128; 1931 1932 if (isExtIntType()) 1933 return true; 1934 1935 return isUnscopedEnumerationType(); 1936 } 1937 1938 bool Type::isUnscopedEnumerationType() const { 1939 if (const auto *ET = dyn_cast<EnumType>(CanonicalType)) 1940 return !ET->getDecl()->isScoped(); 1941 1942 return false; 1943 } 1944 1945 bool Type::isCharType() const { 1946 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) 1947 return BT->getKind() == BuiltinType::Char_U || 1948 BT->getKind() == BuiltinType::UChar || 1949 BT->getKind() == BuiltinType::Char_S || 1950 BT->getKind() == BuiltinType::SChar; 1951 return false; 1952 } 1953 1954 bool Type::isWideCharType() const { 1955 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) 1956 return BT->getKind() == BuiltinType::WChar_S || 1957 BT->getKind() == BuiltinType::WChar_U; 1958 return false; 1959 } 1960 1961 bool Type::isChar8Type() const { 1962 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) 1963 return BT->getKind() == BuiltinType::Char8; 1964 return false; 1965 } 1966 1967 bool Type::isChar16Type() const { 1968 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) 1969 return BT->getKind() == BuiltinType::Char16; 1970 return false; 1971 } 1972 1973 bool Type::isChar32Type() const { 1974 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) 1975 return BT->getKind() == BuiltinType::Char32; 1976 return false; 1977 } 1978 1979 /// Determine whether this type is any of the built-in character 1980 /// types. 1981 bool Type::isAnyCharacterType() const { 1982 const auto *BT = dyn_cast<BuiltinType>(CanonicalType); 1983 if (!BT) return false; 1984 switch (BT->getKind()) { 1985 default: return false; 1986 case BuiltinType::Char_U: 1987 case BuiltinType::UChar: 1988 case BuiltinType::WChar_U: 1989 case BuiltinType::Char8: 1990 case BuiltinType::Char16: 1991 case BuiltinType::Char32: 1992 case BuiltinType::Char_S: 1993 case BuiltinType::SChar: 1994 case BuiltinType::WChar_S: 1995 return true; 1996 } 1997 } 1998 1999 /// isSignedIntegerType - Return true if this is an integer type that is 2000 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..], 2001 /// an enum decl which has a signed representation 2002 bool Type::isSignedIntegerType() const { 2003 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) { 2004 return BT->getKind() >= BuiltinType::Char_S && 2005 BT->getKind() <= BuiltinType::Int128; 2006 } 2007 2008 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) { 2009 // Incomplete enum types are not treated as integer types. 2010 // FIXME: In C++, enum types are never integer types. 2011 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped()) 2012 return ET->getDecl()->getIntegerType()->isSignedIntegerType(); 2013 } 2014 2015 if (const ExtIntType *IT = dyn_cast<ExtIntType>(CanonicalType)) 2016 return IT->isSigned(); 2017 2018 return false; 2019 } 2020 2021 bool Type::isSignedIntegerOrEnumerationType() const { 2022 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) { 2023 return BT->getKind() >= BuiltinType::Char_S && 2024 BT->getKind() <= BuiltinType::Int128; 2025 } 2026 2027 if (const auto *ET = dyn_cast<EnumType>(CanonicalType)) { 2028 if (ET->getDecl()->isComplete()) 2029 return ET->getDecl()->getIntegerType()->isSignedIntegerType(); 2030 } 2031 2032 if (const ExtIntType *IT = dyn_cast<ExtIntType>(CanonicalType)) 2033 return IT->isSigned(); 2034 2035 2036 return false; 2037 } 2038 2039 bool Type::hasSignedIntegerRepresentation() const { 2040 if (const auto *VT = dyn_cast<VectorType>(CanonicalType)) 2041 return VT->getElementType()->isSignedIntegerOrEnumerationType(); 2042 else 2043 return isSignedIntegerOrEnumerationType(); 2044 } 2045 2046 /// isUnsignedIntegerType - Return true if this is an integer type that is 2047 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum 2048 /// decl which has an unsigned representation 2049 bool Type::isUnsignedIntegerType() const { 2050 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) { 2051 return BT->getKind() >= BuiltinType::Bool && 2052 BT->getKind() <= BuiltinType::UInt128; 2053 } 2054 2055 if (const auto *ET = dyn_cast<EnumType>(CanonicalType)) { 2056 // Incomplete enum types are not treated as integer types. 2057 // FIXME: In C++, enum types are never integer types. 2058 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped()) 2059 return ET->getDecl()->getIntegerType()->isUnsignedIntegerType(); 2060 } 2061 2062 if (const ExtIntType *IT = dyn_cast<ExtIntType>(CanonicalType)) 2063 return IT->isUnsigned(); 2064 2065 return false; 2066 } 2067 2068 bool Type::isUnsignedIntegerOrEnumerationType() const { 2069 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) { 2070 return BT->getKind() >= BuiltinType::Bool && 2071 BT->getKind() <= BuiltinType::UInt128; 2072 } 2073 2074 if (const auto *ET = dyn_cast<EnumType>(CanonicalType)) { 2075 if (ET->getDecl()->isComplete()) 2076 return ET->getDecl()->getIntegerType()->isUnsignedIntegerType(); 2077 } 2078 2079 if (const ExtIntType *IT = dyn_cast<ExtIntType>(CanonicalType)) 2080 return IT->isUnsigned(); 2081 2082 return false; 2083 } 2084 2085 bool Type::hasUnsignedIntegerRepresentation() const { 2086 if (const auto *VT = dyn_cast<VectorType>(CanonicalType)) 2087 return VT->getElementType()->isUnsignedIntegerOrEnumerationType(); 2088 else 2089 return isUnsignedIntegerOrEnumerationType(); 2090 } 2091 2092 bool Type::isFloatingType() const { 2093 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) 2094 return BT->getKind() >= BuiltinType::Half && 2095 BT->getKind() <= BuiltinType::Float128; 2096 if (const auto *CT = dyn_cast<ComplexType>(CanonicalType)) 2097 return CT->getElementType()->isFloatingType(); 2098 return false; 2099 } 2100 2101 bool Type::hasFloatingRepresentation() const { 2102 if (const auto *VT = dyn_cast<VectorType>(CanonicalType)) 2103 return VT->getElementType()->isFloatingType(); 2104 else 2105 return isFloatingType(); 2106 } 2107 2108 bool Type::isRealFloatingType() const { 2109 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) 2110 return BT->isFloatingPoint(); 2111 return false; 2112 } 2113 2114 bool Type::isRealType() const { 2115 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) 2116 return BT->getKind() >= BuiltinType::Bool && 2117 BT->getKind() <= BuiltinType::Float128; 2118 if (const auto *ET = dyn_cast<EnumType>(CanonicalType)) 2119 return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped(); 2120 return isExtIntType(); 2121 } 2122 2123 bool Type::isArithmeticType() const { 2124 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) 2125 return BT->getKind() >= BuiltinType::Bool && 2126 BT->getKind() <= BuiltinType::Float128 && 2127 BT->getKind() != BuiltinType::BFloat16; 2128 if (const auto *ET = dyn_cast<EnumType>(CanonicalType)) 2129 // GCC allows forward declaration of enum types (forbid by C99 6.7.2.3p2). 2130 // If a body isn't seen by the time we get here, return false. 2131 // 2132 // C++0x: Enumerations are not arithmetic types. For now, just return 2133 // false for scoped enumerations since that will disable any 2134 // unwanted implicit conversions. 2135 return !ET->getDecl()->isScoped() && ET->getDecl()->isComplete(); 2136 return isa<ComplexType>(CanonicalType) || isExtIntType(); 2137 } 2138 2139 Type::ScalarTypeKind Type::getScalarTypeKind() const { 2140 assert(isScalarType()); 2141 2142 const Type *T = CanonicalType.getTypePtr(); 2143 if (const auto *BT = dyn_cast<BuiltinType>(T)) { 2144 if (BT->getKind() == BuiltinType::Bool) return STK_Bool; 2145 if (BT->getKind() == BuiltinType::NullPtr) return STK_CPointer; 2146 if (BT->isInteger()) return STK_Integral; 2147 if (BT->isFloatingPoint()) return STK_Floating; 2148 if (BT->isFixedPointType()) return STK_FixedPoint; 2149 llvm_unreachable("unknown scalar builtin type"); 2150 } else if (isa<PointerType>(T)) { 2151 return STK_CPointer; 2152 } else if (isa<BlockPointerType>(T)) { 2153 return STK_BlockPointer; 2154 } else if (isa<ObjCObjectPointerType>(T)) { 2155 return STK_ObjCObjectPointer; 2156 } else if (isa<MemberPointerType>(T)) { 2157 return STK_MemberPointer; 2158 } else if (isa<EnumType>(T)) { 2159 assert(cast<EnumType>(T)->getDecl()->isComplete()); 2160 return STK_Integral; 2161 } else if (const auto *CT = dyn_cast<ComplexType>(T)) { 2162 if (CT->getElementType()->isRealFloatingType()) 2163 return STK_FloatingComplex; 2164 return STK_IntegralComplex; 2165 } else if (isExtIntType()) { 2166 return STK_Integral; 2167 } 2168 2169 llvm_unreachable("unknown scalar type"); 2170 } 2171 2172 /// Determines whether the type is a C++ aggregate type or C 2173 /// aggregate or union type. 2174 /// 2175 /// An aggregate type is an array or a class type (struct, union, or 2176 /// class) that has no user-declared constructors, no private or 2177 /// protected non-static data members, no base classes, and no virtual 2178 /// functions (C++ [dcl.init.aggr]p1). The notion of an aggregate type 2179 /// subsumes the notion of C aggregates (C99 6.2.5p21) because it also 2180 /// includes union types. 2181 bool Type::isAggregateType() const { 2182 if (const auto *Record = dyn_cast<RecordType>(CanonicalType)) { 2183 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(Record->getDecl())) 2184 return ClassDecl->isAggregate(); 2185 2186 return true; 2187 } 2188 2189 return isa<ArrayType>(CanonicalType); 2190 } 2191 2192 /// isConstantSizeType - Return true if this is not a variable sized type, 2193 /// according to the rules of C99 6.7.5p3. It is not legal to call this on 2194 /// incomplete types or dependent types. 2195 bool Type::isConstantSizeType() const { 2196 assert(!isIncompleteType() && "This doesn't make sense for incomplete types"); 2197 assert(!isDependentType() && "This doesn't make sense for dependent types"); 2198 // The VAT must have a size, as it is known to be complete. 2199 return !isa<VariableArrayType>(CanonicalType); 2200 } 2201 2202 /// isIncompleteType - Return true if this is an incomplete type (C99 6.2.5p1) 2203 /// - a type that can describe objects, but which lacks information needed to 2204 /// determine its size. 2205 bool Type::isIncompleteType(NamedDecl **Def) const { 2206 if (Def) 2207 *Def = nullptr; 2208 2209 switch (CanonicalType->getTypeClass()) { 2210 default: return false; 2211 case Builtin: 2212 // Void is the only incomplete builtin type. Per C99 6.2.5p19, it can never 2213 // be completed. 2214 return isVoidType(); 2215 case Enum: { 2216 EnumDecl *EnumD = cast<EnumType>(CanonicalType)->getDecl(); 2217 if (Def) 2218 *Def = EnumD; 2219 return !EnumD->isComplete(); 2220 } 2221 case Record: { 2222 // A tagged type (struct/union/enum/class) is incomplete if the decl is a 2223 // forward declaration, but not a full definition (C99 6.2.5p22). 2224 RecordDecl *Rec = cast<RecordType>(CanonicalType)->getDecl(); 2225 if (Def) 2226 *Def = Rec; 2227 return !Rec->isCompleteDefinition(); 2228 } 2229 case ConstantArray: 2230 // An array is incomplete if its element type is incomplete 2231 // (C++ [dcl.array]p1). 2232 // We don't handle variable arrays (they're not allowed in C++) or 2233 // dependent-sized arrays (dependent types are never treated as incomplete). 2234 return cast<ArrayType>(CanonicalType)->getElementType() 2235 ->isIncompleteType(Def); 2236 case IncompleteArray: 2237 // An array of unknown size is an incomplete type (C99 6.2.5p22). 2238 return true; 2239 case MemberPointer: { 2240 // Member pointers in the MS ABI have special behavior in 2241 // RequireCompleteType: they attach a MSInheritanceAttr to the CXXRecordDecl 2242 // to indicate which inheritance model to use. 2243 auto *MPTy = cast<MemberPointerType>(CanonicalType); 2244 const Type *ClassTy = MPTy->getClass(); 2245 // Member pointers with dependent class types don't get special treatment. 2246 if (ClassTy->isDependentType()) 2247 return false; 2248 const CXXRecordDecl *RD = ClassTy->getAsCXXRecordDecl(); 2249 ASTContext &Context = RD->getASTContext(); 2250 // Member pointers not in the MS ABI don't get special treatment. 2251 if (!Context.getTargetInfo().getCXXABI().isMicrosoft()) 2252 return false; 2253 // The inheritance attribute might only be present on the most recent 2254 // CXXRecordDecl, use that one. 2255 RD = RD->getMostRecentNonInjectedDecl(); 2256 // Nothing interesting to do if the inheritance attribute is already set. 2257 if (RD->hasAttr<MSInheritanceAttr>()) 2258 return false; 2259 return true; 2260 } 2261 case ObjCObject: 2262 return cast<ObjCObjectType>(CanonicalType)->getBaseType() 2263 ->isIncompleteType(Def); 2264 case ObjCInterface: { 2265 // ObjC interfaces are incomplete if they are @class, not @interface. 2266 ObjCInterfaceDecl *Interface 2267 = cast<ObjCInterfaceType>(CanonicalType)->getDecl(); 2268 if (Def) 2269 *Def = Interface; 2270 return !Interface->hasDefinition(); 2271 } 2272 } 2273 } 2274 2275 bool Type::isSizelessBuiltinType() const { 2276 if (const BuiltinType *BT = getAs<BuiltinType>()) { 2277 switch (BT->getKind()) { 2278 // SVE Types 2279 #define SVE_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 2280 #include "clang/Basic/AArch64SVEACLETypes.def" 2281 return true; 2282 default: 2283 return false; 2284 } 2285 } 2286 return false; 2287 } 2288 2289 bool Type::isSizelessType() const { return isSizelessBuiltinType(); } 2290 2291 bool Type::isVLSTBuiltinType() const { 2292 if (const BuiltinType *BT = getAs<BuiltinType>()) { 2293 switch (BT->getKind()) { 2294 case BuiltinType::SveInt8: 2295 case BuiltinType::SveInt16: 2296 case BuiltinType::SveInt32: 2297 case BuiltinType::SveInt64: 2298 case BuiltinType::SveUint8: 2299 case BuiltinType::SveUint16: 2300 case BuiltinType::SveUint32: 2301 case BuiltinType::SveUint64: 2302 case BuiltinType::SveFloat16: 2303 case BuiltinType::SveFloat32: 2304 case BuiltinType::SveFloat64: 2305 case BuiltinType::SveBFloat16: 2306 case BuiltinType::SveBool: 2307 return true; 2308 default: 2309 return false; 2310 } 2311 } 2312 return false; 2313 } 2314 2315 QualType Type::getSveEltType(const ASTContext &Ctx) const { 2316 assert(isVLSTBuiltinType() && "unsupported type!"); 2317 2318 const BuiltinType *BTy = getAs<BuiltinType>(); 2319 if (BTy->getKind() == BuiltinType::SveBool) 2320 // Represent predicates as i8 rather than i1 to avoid any layout issues. 2321 // The type is bitcasted to a scalable predicate type when casting between 2322 // scalable and fixed-length vectors. 2323 return Ctx.UnsignedCharTy; 2324 else 2325 return Ctx.getBuiltinVectorTypeInfo(BTy).ElementType; 2326 } 2327 2328 bool QualType::isPODType(const ASTContext &Context) const { 2329 // C++11 has a more relaxed definition of POD. 2330 if (Context.getLangOpts().CPlusPlus11) 2331 return isCXX11PODType(Context); 2332 2333 return isCXX98PODType(Context); 2334 } 2335 2336 bool QualType::isCXX98PODType(const ASTContext &Context) const { 2337 // The compiler shouldn't query this for incomplete types, but the user might. 2338 // We return false for that case. Except for incomplete arrays of PODs, which 2339 // are PODs according to the standard. 2340 if (isNull()) 2341 return false; 2342 2343 if ((*this)->isIncompleteArrayType()) 2344 return Context.getBaseElementType(*this).isCXX98PODType(Context); 2345 2346 if ((*this)->isIncompleteType()) 2347 return false; 2348 2349 if (hasNonTrivialObjCLifetime()) 2350 return false; 2351 2352 QualType CanonicalType = getTypePtr()->CanonicalType; 2353 switch (CanonicalType->getTypeClass()) { 2354 // Everything not explicitly mentioned is not POD. 2355 default: return false; 2356 case Type::VariableArray: 2357 case Type::ConstantArray: 2358 // IncompleteArray is handled above. 2359 return Context.getBaseElementType(*this).isCXX98PODType(Context); 2360 2361 case Type::ObjCObjectPointer: 2362 case Type::BlockPointer: 2363 case Type::Builtin: 2364 case Type::Complex: 2365 case Type::Pointer: 2366 case Type::MemberPointer: 2367 case Type::Vector: 2368 case Type::ExtVector: 2369 case Type::ExtInt: 2370 return true; 2371 2372 case Type::Enum: 2373 return true; 2374 2375 case Type::Record: 2376 if (const auto *ClassDecl = 2377 dyn_cast<CXXRecordDecl>(cast<RecordType>(CanonicalType)->getDecl())) 2378 return ClassDecl->isPOD(); 2379 2380 // C struct/union is POD. 2381 return true; 2382 } 2383 } 2384 2385 bool QualType::isTrivialType(const ASTContext &Context) const { 2386 // The compiler shouldn't query this for incomplete types, but the user might. 2387 // We return false for that case. Except for incomplete arrays of PODs, which 2388 // are PODs according to the standard. 2389 if (isNull()) 2390 return false; 2391 2392 if ((*this)->isArrayType()) 2393 return Context.getBaseElementType(*this).isTrivialType(Context); 2394 2395 if ((*this)->isSizelessBuiltinType()) 2396 return true; 2397 2398 // Return false for incomplete types after skipping any incomplete array 2399 // types which are expressly allowed by the standard and thus our API. 2400 if ((*this)->isIncompleteType()) 2401 return false; 2402 2403 if (hasNonTrivialObjCLifetime()) 2404 return false; 2405 2406 QualType CanonicalType = getTypePtr()->CanonicalType; 2407 if (CanonicalType->isDependentType()) 2408 return false; 2409 2410 // C++0x [basic.types]p9: 2411 // Scalar types, trivial class types, arrays of such types, and 2412 // cv-qualified versions of these types are collectively called trivial 2413 // types. 2414 2415 // As an extension, Clang treats vector types as Scalar types. 2416 if (CanonicalType->isScalarType() || CanonicalType->isVectorType()) 2417 return true; 2418 if (const auto *RT = CanonicalType->getAs<RecordType>()) { 2419 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 2420 // C++11 [class]p6: 2421 // A trivial class is a class that has a default constructor, 2422 // has no non-trivial default constructors, and is trivially 2423 // copyable. 2424 return ClassDecl->hasDefaultConstructor() && 2425 !ClassDecl->hasNonTrivialDefaultConstructor() && 2426 ClassDecl->isTriviallyCopyable(); 2427 } 2428 2429 return true; 2430 } 2431 2432 // No other types can match. 2433 return false; 2434 } 2435 2436 bool QualType::isTriviallyCopyableType(const ASTContext &Context) const { 2437 if ((*this)->isArrayType()) 2438 return Context.getBaseElementType(*this).isTriviallyCopyableType(Context); 2439 2440 if (hasNonTrivialObjCLifetime()) 2441 return false; 2442 2443 // C++11 [basic.types]p9 - See Core 2094 2444 // Scalar types, trivially copyable class types, arrays of such types, and 2445 // cv-qualified versions of these types are collectively 2446 // called trivially copyable types. 2447 2448 QualType CanonicalType = getCanonicalType(); 2449 if (CanonicalType->isDependentType()) 2450 return false; 2451 2452 if (CanonicalType->isSizelessBuiltinType()) 2453 return true; 2454 2455 // Return false for incomplete types after skipping any incomplete array types 2456 // which are expressly allowed by the standard and thus our API. 2457 if (CanonicalType->isIncompleteType()) 2458 return false; 2459 2460 // As an extension, Clang treats vector types as Scalar types. 2461 if (CanonicalType->isScalarType() || CanonicalType->isVectorType()) 2462 return true; 2463 2464 if (const auto *RT = CanonicalType->getAs<RecordType>()) { 2465 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 2466 if (!ClassDecl->isTriviallyCopyable()) return false; 2467 } 2468 2469 return true; 2470 } 2471 2472 // No other types can match. 2473 return false; 2474 } 2475 2476 bool QualType::isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const { 2477 return !Context.getLangOpts().ObjCAutoRefCount && 2478 Context.getLangOpts().ObjCWeak && 2479 getObjCLifetime() != Qualifiers::OCL_Weak; 2480 } 2481 2482 bool QualType::hasNonTrivialToPrimitiveDefaultInitializeCUnion(const RecordDecl *RD) { 2483 return RD->hasNonTrivialToPrimitiveDefaultInitializeCUnion(); 2484 } 2485 2486 bool QualType::hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl *RD) { 2487 return RD->hasNonTrivialToPrimitiveDestructCUnion(); 2488 } 2489 2490 bool QualType::hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD) { 2491 return RD->hasNonTrivialToPrimitiveCopyCUnion(); 2492 } 2493 2494 QualType::PrimitiveDefaultInitializeKind 2495 QualType::isNonTrivialToPrimitiveDefaultInitialize() const { 2496 if (const auto *RT = 2497 getTypePtr()->getBaseElementTypeUnsafe()->getAs<RecordType>()) 2498 if (RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) 2499 return PDIK_Struct; 2500 2501 switch (getQualifiers().getObjCLifetime()) { 2502 case Qualifiers::OCL_Strong: 2503 return PDIK_ARCStrong; 2504 case Qualifiers::OCL_Weak: 2505 return PDIK_ARCWeak; 2506 default: 2507 return PDIK_Trivial; 2508 } 2509 } 2510 2511 QualType::PrimitiveCopyKind QualType::isNonTrivialToPrimitiveCopy() const { 2512 if (const auto *RT = 2513 getTypePtr()->getBaseElementTypeUnsafe()->getAs<RecordType>()) 2514 if (RT->getDecl()->isNonTrivialToPrimitiveCopy()) 2515 return PCK_Struct; 2516 2517 Qualifiers Qs = getQualifiers(); 2518 switch (Qs.getObjCLifetime()) { 2519 case Qualifiers::OCL_Strong: 2520 return PCK_ARCStrong; 2521 case Qualifiers::OCL_Weak: 2522 return PCK_ARCWeak; 2523 default: 2524 return Qs.hasVolatile() ? PCK_VolatileTrivial : PCK_Trivial; 2525 } 2526 } 2527 2528 QualType::PrimitiveCopyKind 2529 QualType::isNonTrivialToPrimitiveDestructiveMove() const { 2530 return isNonTrivialToPrimitiveCopy(); 2531 } 2532 2533 bool Type::isLiteralType(const ASTContext &Ctx) const { 2534 if (isDependentType()) 2535 return false; 2536 2537 // C++1y [basic.types]p10: 2538 // A type is a literal type if it is: 2539 // -- cv void; or 2540 if (Ctx.getLangOpts().CPlusPlus14 && isVoidType()) 2541 return true; 2542 2543 // C++11 [basic.types]p10: 2544 // A type is a literal type if it is: 2545 // [...] 2546 // -- an array of literal type other than an array of runtime bound; or 2547 if (isVariableArrayType()) 2548 return false; 2549 const Type *BaseTy = getBaseElementTypeUnsafe(); 2550 assert(BaseTy && "NULL element type"); 2551 2552 // Return false for incomplete types after skipping any incomplete array 2553 // types; those are expressly allowed by the standard and thus our API. 2554 if (BaseTy->isIncompleteType()) 2555 return false; 2556 2557 // C++11 [basic.types]p10: 2558 // A type is a literal type if it is: 2559 // -- a scalar type; or 2560 // As an extension, Clang treats vector types and complex types as 2561 // literal types. 2562 if (BaseTy->isScalarType() || BaseTy->isVectorType() || 2563 BaseTy->isAnyComplexType()) 2564 return true; 2565 // -- a reference type; or 2566 if (BaseTy->isReferenceType()) 2567 return true; 2568 // -- a class type that has all of the following properties: 2569 if (const auto *RT = BaseTy->getAs<RecordType>()) { 2570 // -- a trivial destructor, 2571 // -- every constructor call and full-expression in the 2572 // brace-or-equal-initializers for non-static data members (if any) 2573 // is a constant expression, 2574 // -- it is an aggregate type or has at least one constexpr 2575 // constructor or constructor template that is not a copy or move 2576 // constructor, and 2577 // -- all non-static data members and base classes of literal types 2578 // 2579 // We resolve DR1361 by ignoring the second bullet. 2580 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) 2581 return ClassDecl->isLiteral(); 2582 2583 return true; 2584 } 2585 2586 // We treat _Atomic T as a literal type if T is a literal type. 2587 if (const auto *AT = BaseTy->getAs<AtomicType>()) 2588 return AT->getValueType()->isLiteralType(Ctx); 2589 2590 // If this type hasn't been deduced yet, then conservatively assume that 2591 // it'll work out to be a literal type. 2592 if (isa<AutoType>(BaseTy->getCanonicalTypeInternal())) 2593 return true; 2594 2595 return false; 2596 } 2597 2598 bool Type::isStructuralType() const { 2599 // C++20 [temp.param]p6: 2600 // A structural type is one of the following: 2601 // -- a scalar type; or 2602 // -- a vector type [Clang extension]; or 2603 if (isScalarType() || isVectorType()) 2604 return true; 2605 // -- an lvalue reference type; or 2606 if (isLValueReferenceType()) 2607 return true; 2608 // -- a literal class type [...under some conditions] 2609 if (const CXXRecordDecl *RD = getAsCXXRecordDecl()) 2610 return RD->isStructural(); 2611 return false; 2612 } 2613 2614 bool Type::isStandardLayoutType() const { 2615 if (isDependentType()) 2616 return false; 2617 2618 // C++0x [basic.types]p9: 2619 // Scalar types, standard-layout class types, arrays of such types, and 2620 // cv-qualified versions of these types are collectively called 2621 // standard-layout types. 2622 const Type *BaseTy = getBaseElementTypeUnsafe(); 2623 assert(BaseTy && "NULL element type"); 2624 2625 // Return false for incomplete types after skipping any incomplete array 2626 // types which are expressly allowed by the standard and thus our API. 2627 if (BaseTy->isIncompleteType()) 2628 return false; 2629 2630 // As an extension, Clang treats vector types as Scalar types. 2631 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true; 2632 if (const auto *RT = BaseTy->getAs<RecordType>()) { 2633 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) 2634 if (!ClassDecl->isStandardLayout()) 2635 return false; 2636 2637 // Default to 'true' for non-C++ class types. 2638 // FIXME: This is a bit dubious, but plain C structs should trivially meet 2639 // all the requirements of standard layout classes. 2640 return true; 2641 } 2642 2643 // No other types can match. 2644 return false; 2645 } 2646 2647 // This is effectively the intersection of isTrivialType and 2648 // isStandardLayoutType. We implement it directly to avoid redundant 2649 // conversions from a type to a CXXRecordDecl. 2650 bool QualType::isCXX11PODType(const ASTContext &Context) const { 2651 const Type *ty = getTypePtr(); 2652 if (ty->isDependentType()) 2653 return false; 2654 2655 if (hasNonTrivialObjCLifetime()) 2656 return false; 2657 2658 // C++11 [basic.types]p9: 2659 // Scalar types, POD classes, arrays of such types, and cv-qualified 2660 // versions of these types are collectively called trivial types. 2661 const Type *BaseTy = ty->getBaseElementTypeUnsafe(); 2662 assert(BaseTy && "NULL element type"); 2663 2664 if (BaseTy->isSizelessBuiltinType()) 2665 return true; 2666 2667 // Return false for incomplete types after skipping any incomplete array 2668 // types which are expressly allowed by the standard and thus our API. 2669 if (BaseTy->isIncompleteType()) 2670 return false; 2671 2672 // As an extension, Clang treats vector types as Scalar types. 2673 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true; 2674 if (const auto *RT = BaseTy->getAs<RecordType>()) { 2675 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 2676 // C++11 [class]p10: 2677 // A POD struct is a non-union class that is both a trivial class [...] 2678 if (!ClassDecl->isTrivial()) return false; 2679 2680 // C++11 [class]p10: 2681 // A POD struct is a non-union class that is both a trivial class and 2682 // a standard-layout class [...] 2683 if (!ClassDecl->isStandardLayout()) return false; 2684 2685 // C++11 [class]p10: 2686 // A POD struct is a non-union class that is both a trivial class and 2687 // a standard-layout class, and has no non-static data members of type 2688 // non-POD struct, non-POD union (or array of such types). [...] 2689 // 2690 // We don't directly query the recursive aspect as the requirements for 2691 // both standard-layout classes and trivial classes apply recursively 2692 // already. 2693 } 2694 2695 return true; 2696 } 2697 2698 // No other types can match. 2699 return false; 2700 } 2701 2702 bool Type::isNothrowT() const { 2703 if (const auto *RD = getAsCXXRecordDecl()) { 2704 IdentifierInfo *II = RD->getIdentifier(); 2705 if (II && II->isStr("nothrow_t") && RD->isInStdNamespace()) 2706 return true; 2707 } 2708 return false; 2709 } 2710 2711 bool Type::isAlignValT() const { 2712 if (const auto *ET = getAs<EnumType>()) { 2713 IdentifierInfo *II = ET->getDecl()->getIdentifier(); 2714 if (II && II->isStr("align_val_t") && ET->getDecl()->isInStdNamespace()) 2715 return true; 2716 } 2717 return false; 2718 } 2719 2720 bool Type::isStdByteType() const { 2721 if (const auto *ET = getAs<EnumType>()) { 2722 IdentifierInfo *II = ET->getDecl()->getIdentifier(); 2723 if (II && II->isStr("byte") && ET->getDecl()->isInStdNamespace()) 2724 return true; 2725 } 2726 return false; 2727 } 2728 2729 bool Type::isPromotableIntegerType() const { 2730 if (const auto *BT = getAs<BuiltinType>()) 2731 switch (BT->getKind()) { 2732 case BuiltinType::Bool: 2733 case BuiltinType::Char_S: 2734 case BuiltinType::Char_U: 2735 case BuiltinType::SChar: 2736 case BuiltinType::UChar: 2737 case BuiltinType::Short: 2738 case BuiltinType::UShort: 2739 case BuiltinType::WChar_S: 2740 case BuiltinType::WChar_U: 2741 case BuiltinType::Char8: 2742 case BuiltinType::Char16: 2743 case BuiltinType::Char32: 2744 return true; 2745 default: 2746 return false; 2747 } 2748 2749 // Enumerated types are promotable to their compatible integer types 2750 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2). 2751 if (const auto *ET = getAs<EnumType>()){ 2752 if (this->isDependentType() || ET->getDecl()->getPromotionType().isNull() 2753 || ET->getDecl()->isScoped()) 2754 return false; 2755 2756 return true; 2757 } 2758 2759 return false; 2760 } 2761 2762 bool Type::isSpecifierType() const { 2763 // Note that this intentionally does not use the canonical type. 2764 switch (getTypeClass()) { 2765 case Builtin: 2766 case Record: 2767 case Enum: 2768 case Typedef: 2769 case Complex: 2770 case TypeOfExpr: 2771 case TypeOf: 2772 case TemplateTypeParm: 2773 case SubstTemplateTypeParm: 2774 case TemplateSpecialization: 2775 case Elaborated: 2776 case DependentName: 2777 case DependentTemplateSpecialization: 2778 case ObjCInterface: 2779 case ObjCObject: 2780 case ObjCObjectPointer: // FIXME: object pointers aren't really specifiers 2781 return true; 2782 default: 2783 return false; 2784 } 2785 } 2786 2787 ElaboratedTypeKeyword 2788 TypeWithKeyword::getKeywordForTypeSpec(unsigned TypeSpec) { 2789 switch (TypeSpec) { 2790 default: return ETK_None; 2791 case TST_typename: return ETK_Typename; 2792 case TST_class: return ETK_Class; 2793 case TST_struct: return ETK_Struct; 2794 case TST_interface: return ETK_Interface; 2795 case TST_union: return ETK_Union; 2796 case TST_enum: return ETK_Enum; 2797 } 2798 } 2799 2800 TagTypeKind 2801 TypeWithKeyword::getTagTypeKindForTypeSpec(unsigned TypeSpec) { 2802 switch(TypeSpec) { 2803 case TST_class: return TTK_Class; 2804 case TST_struct: return TTK_Struct; 2805 case TST_interface: return TTK_Interface; 2806 case TST_union: return TTK_Union; 2807 case TST_enum: return TTK_Enum; 2808 } 2809 2810 llvm_unreachable("Type specifier is not a tag type kind."); 2811 } 2812 2813 ElaboratedTypeKeyword 2814 TypeWithKeyword::getKeywordForTagTypeKind(TagTypeKind Kind) { 2815 switch (Kind) { 2816 case TTK_Class: return ETK_Class; 2817 case TTK_Struct: return ETK_Struct; 2818 case TTK_Interface: return ETK_Interface; 2819 case TTK_Union: return ETK_Union; 2820 case TTK_Enum: return ETK_Enum; 2821 } 2822 llvm_unreachable("Unknown tag type kind."); 2823 } 2824 2825 TagTypeKind 2826 TypeWithKeyword::getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword) { 2827 switch (Keyword) { 2828 case ETK_Class: return TTK_Class; 2829 case ETK_Struct: return TTK_Struct; 2830 case ETK_Interface: return TTK_Interface; 2831 case ETK_Union: return TTK_Union; 2832 case ETK_Enum: return TTK_Enum; 2833 case ETK_None: // Fall through. 2834 case ETK_Typename: 2835 llvm_unreachable("Elaborated type keyword is not a tag type kind."); 2836 } 2837 llvm_unreachable("Unknown elaborated type keyword."); 2838 } 2839 2840 bool 2841 TypeWithKeyword::KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword) { 2842 switch (Keyword) { 2843 case ETK_None: 2844 case ETK_Typename: 2845 return false; 2846 case ETK_Class: 2847 case ETK_Struct: 2848 case ETK_Interface: 2849 case ETK_Union: 2850 case ETK_Enum: 2851 return true; 2852 } 2853 llvm_unreachable("Unknown elaborated type keyword."); 2854 } 2855 2856 StringRef TypeWithKeyword::getKeywordName(ElaboratedTypeKeyword Keyword) { 2857 switch (Keyword) { 2858 case ETK_None: return {}; 2859 case ETK_Typename: return "typename"; 2860 case ETK_Class: return "class"; 2861 case ETK_Struct: return "struct"; 2862 case ETK_Interface: return "__interface"; 2863 case ETK_Union: return "union"; 2864 case ETK_Enum: return "enum"; 2865 } 2866 2867 llvm_unreachable("Unknown elaborated type keyword."); 2868 } 2869 2870 DependentTemplateSpecializationType::DependentTemplateSpecializationType( 2871 ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, 2872 const IdentifierInfo *Name, ArrayRef<TemplateArgument> Args, QualType Canon) 2873 : TypeWithKeyword(Keyword, DependentTemplateSpecialization, Canon, 2874 TypeDependence::DependentInstantiation | 2875 (NNS ? toTypeDependence(NNS->getDependence()) 2876 : TypeDependence::None)), 2877 NNS(NNS), Name(Name) { 2878 DependentTemplateSpecializationTypeBits.NumArgs = Args.size(); 2879 assert((!NNS || NNS->isDependent()) && 2880 "DependentTemplateSpecializatonType requires dependent qualifier"); 2881 TemplateArgument *ArgBuffer = getArgBuffer(); 2882 for (const TemplateArgument &Arg : Args) { 2883 addDependence(toTypeDependence(Arg.getDependence() & 2884 TemplateArgumentDependence::UnexpandedPack)); 2885 2886 new (ArgBuffer++) TemplateArgument(Arg); 2887 } 2888 } 2889 2890 void 2891 DependentTemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID, 2892 const ASTContext &Context, 2893 ElaboratedTypeKeyword Keyword, 2894 NestedNameSpecifier *Qualifier, 2895 const IdentifierInfo *Name, 2896 ArrayRef<TemplateArgument> Args) { 2897 ID.AddInteger(Keyword); 2898 ID.AddPointer(Qualifier); 2899 ID.AddPointer(Name); 2900 for (const TemplateArgument &Arg : Args) 2901 Arg.Profile(ID, Context); 2902 } 2903 2904 bool Type::isElaboratedTypeSpecifier() const { 2905 ElaboratedTypeKeyword Keyword; 2906 if (const auto *Elab = dyn_cast<ElaboratedType>(this)) 2907 Keyword = Elab->getKeyword(); 2908 else if (const auto *DepName = dyn_cast<DependentNameType>(this)) 2909 Keyword = DepName->getKeyword(); 2910 else if (const auto *DepTST = 2911 dyn_cast<DependentTemplateSpecializationType>(this)) 2912 Keyword = DepTST->getKeyword(); 2913 else 2914 return false; 2915 2916 return TypeWithKeyword::KeywordIsTagTypeKind(Keyword); 2917 } 2918 2919 const char *Type::getTypeClassName() const { 2920 switch (TypeBits.TC) { 2921 #define ABSTRACT_TYPE(Derived, Base) 2922 #define TYPE(Derived, Base) case Derived: return #Derived; 2923 #include "clang/AST/TypeNodes.inc" 2924 } 2925 2926 llvm_unreachable("Invalid type class."); 2927 } 2928 2929 StringRef BuiltinType::getName(const PrintingPolicy &Policy) const { 2930 switch (getKind()) { 2931 case Void: 2932 return "void"; 2933 case Bool: 2934 return Policy.Bool ? "bool" : "_Bool"; 2935 case Char_S: 2936 return "char"; 2937 case Char_U: 2938 return "char"; 2939 case SChar: 2940 return "signed char"; 2941 case Short: 2942 return "short"; 2943 case Int: 2944 return "int"; 2945 case Long: 2946 return "long"; 2947 case LongLong: 2948 return "long long"; 2949 case Int128: 2950 return "__int128"; 2951 case UChar: 2952 return "unsigned char"; 2953 case UShort: 2954 return "unsigned short"; 2955 case UInt: 2956 return "unsigned int"; 2957 case ULong: 2958 return "unsigned long"; 2959 case ULongLong: 2960 return "unsigned long long"; 2961 case UInt128: 2962 return "unsigned __int128"; 2963 case Half: 2964 return Policy.Half ? "half" : "__fp16"; 2965 case BFloat16: 2966 return "__bf16"; 2967 case Float: 2968 return "float"; 2969 case Double: 2970 return "double"; 2971 case LongDouble: 2972 return "long double"; 2973 case ShortAccum: 2974 return "short _Accum"; 2975 case Accum: 2976 return "_Accum"; 2977 case LongAccum: 2978 return "long _Accum"; 2979 case UShortAccum: 2980 return "unsigned short _Accum"; 2981 case UAccum: 2982 return "unsigned _Accum"; 2983 case ULongAccum: 2984 return "unsigned long _Accum"; 2985 case BuiltinType::ShortFract: 2986 return "short _Fract"; 2987 case BuiltinType::Fract: 2988 return "_Fract"; 2989 case BuiltinType::LongFract: 2990 return "long _Fract"; 2991 case BuiltinType::UShortFract: 2992 return "unsigned short _Fract"; 2993 case BuiltinType::UFract: 2994 return "unsigned _Fract"; 2995 case BuiltinType::ULongFract: 2996 return "unsigned long _Fract"; 2997 case BuiltinType::SatShortAccum: 2998 return "_Sat short _Accum"; 2999 case BuiltinType::SatAccum: 3000 return "_Sat _Accum"; 3001 case BuiltinType::SatLongAccum: 3002 return "_Sat long _Accum"; 3003 case BuiltinType::SatUShortAccum: 3004 return "_Sat unsigned short _Accum"; 3005 case BuiltinType::SatUAccum: 3006 return "_Sat unsigned _Accum"; 3007 case BuiltinType::SatULongAccum: 3008 return "_Sat unsigned long _Accum"; 3009 case BuiltinType::SatShortFract: 3010 return "_Sat short _Fract"; 3011 case BuiltinType::SatFract: 3012 return "_Sat _Fract"; 3013 case BuiltinType::SatLongFract: 3014 return "_Sat long _Fract"; 3015 case BuiltinType::SatUShortFract: 3016 return "_Sat unsigned short _Fract"; 3017 case BuiltinType::SatUFract: 3018 return "_Sat unsigned _Fract"; 3019 case BuiltinType::SatULongFract: 3020 return "_Sat unsigned long _Fract"; 3021 case Float16: 3022 return "_Float16"; 3023 case Float128: 3024 return "__float128"; 3025 case WChar_S: 3026 case WChar_U: 3027 return Policy.MSWChar ? "__wchar_t" : "wchar_t"; 3028 case Char8: 3029 return "char8_t"; 3030 case Char16: 3031 return "char16_t"; 3032 case Char32: 3033 return "char32_t"; 3034 case NullPtr: 3035 return "nullptr_t"; 3036 case Overload: 3037 return "<overloaded function type>"; 3038 case BoundMember: 3039 return "<bound member function type>"; 3040 case PseudoObject: 3041 return "<pseudo-object type>"; 3042 case Dependent: 3043 return "<dependent type>"; 3044 case UnknownAny: 3045 return "<unknown type>"; 3046 case ARCUnbridgedCast: 3047 return "<ARC unbridged cast type>"; 3048 case BuiltinFn: 3049 return "<builtin fn type>"; 3050 case ObjCId: 3051 return "id"; 3052 case ObjCClass: 3053 return "Class"; 3054 case ObjCSel: 3055 return "SEL"; 3056 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 3057 case Id: \ 3058 return "__" #Access " " #ImgType "_t"; 3059 #include "clang/Basic/OpenCLImageTypes.def" 3060 case OCLSampler: 3061 return "sampler_t"; 3062 case OCLEvent: 3063 return "event_t"; 3064 case OCLClkEvent: 3065 return "clk_event_t"; 3066 case OCLQueue: 3067 return "queue_t"; 3068 case OCLReserveID: 3069 return "reserve_id_t"; 3070 case IncompleteMatrixIdx: 3071 return "<incomplete matrix index type>"; 3072 case OMPArraySection: 3073 return "<OpenMP array section type>"; 3074 case OMPArrayShaping: 3075 return "<OpenMP array shaping type>"; 3076 case OMPIterator: 3077 return "<OpenMP iterator type>"; 3078 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 3079 case Id: \ 3080 return #ExtType; 3081 #include "clang/Basic/OpenCLExtensionTypes.def" 3082 #define SVE_TYPE(Name, Id, SingletonId) \ 3083 case Id: \ 3084 return Name; 3085 #include "clang/Basic/AArch64SVEACLETypes.def" 3086 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 3087 case Id: \ 3088 return #Name; 3089 #include "clang/Basic/PPCTypes.def" 3090 } 3091 3092 llvm_unreachable("Invalid builtin type."); 3093 } 3094 3095 QualType QualType::getNonPackExpansionType() const { 3096 // We never wrap type sugar around a PackExpansionType. 3097 if (auto *PET = dyn_cast<PackExpansionType>(getTypePtr())) 3098 return PET->getPattern(); 3099 return *this; 3100 } 3101 3102 QualType QualType::getNonLValueExprType(const ASTContext &Context) const { 3103 if (const auto *RefType = getTypePtr()->getAs<ReferenceType>()) 3104 return RefType->getPointeeType(); 3105 3106 // C++0x [basic.lval]: 3107 // Class prvalues can have cv-qualified types; non-class prvalues always 3108 // have cv-unqualified types. 3109 // 3110 // See also C99 6.3.2.1p2. 3111 if (!Context.getLangOpts().CPlusPlus || 3112 (!getTypePtr()->isDependentType() && !getTypePtr()->isRecordType())) 3113 return getUnqualifiedType(); 3114 3115 return *this; 3116 } 3117 3118 StringRef FunctionType::getNameForCallConv(CallingConv CC) { 3119 switch (CC) { 3120 case CC_C: return "cdecl"; 3121 case CC_X86StdCall: return "stdcall"; 3122 case CC_X86FastCall: return "fastcall"; 3123 case CC_X86ThisCall: return "thiscall"; 3124 case CC_X86Pascal: return "pascal"; 3125 case CC_X86VectorCall: return "vectorcall"; 3126 case CC_Win64: return "ms_abi"; 3127 case CC_X86_64SysV: return "sysv_abi"; 3128 case CC_X86RegCall : return "regcall"; 3129 case CC_AAPCS: return "aapcs"; 3130 case CC_AAPCS_VFP: return "aapcs-vfp"; 3131 case CC_AArch64VectorCall: return "aarch64_vector_pcs"; 3132 case CC_IntelOclBicc: return "intel_ocl_bicc"; 3133 case CC_SpirFunction: return "spir_function"; 3134 case CC_OpenCLKernel: return "opencl_kernel"; 3135 case CC_Swift: return "swiftcall"; 3136 case CC_PreserveMost: return "preserve_most"; 3137 case CC_PreserveAll: return "preserve_all"; 3138 } 3139 3140 llvm_unreachable("Invalid calling convention."); 3141 } 3142 3143 FunctionProtoType::FunctionProtoType(QualType result, ArrayRef<QualType> params, 3144 QualType canonical, 3145 const ExtProtoInfo &epi) 3146 : FunctionType(FunctionProto, result, canonical, result->getDependence(), 3147 epi.ExtInfo) { 3148 FunctionTypeBits.FastTypeQuals = epi.TypeQuals.getFastQualifiers(); 3149 FunctionTypeBits.RefQualifier = epi.RefQualifier; 3150 FunctionTypeBits.NumParams = params.size(); 3151 assert(getNumParams() == params.size() && "NumParams overflow!"); 3152 FunctionTypeBits.ExceptionSpecType = epi.ExceptionSpec.Type; 3153 FunctionTypeBits.HasExtParameterInfos = !!epi.ExtParameterInfos; 3154 FunctionTypeBits.Variadic = epi.Variadic; 3155 FunctionTypeBits.HasTrailingReturn = epi.HasTrailingReturn; 3156 3157 // Fill in the extra trailing bitfields if present. 3158 if (hasExtraBitfields(epi.ExceptionSpec.Type)) { 3159 auto &ExtraBits = *getTrailingObjects<FunctionTypeExtraBitfields>(); 3160 ExtraBits.NumExceptionType = epi.ExceptionSpec.Exceptions.size(); 3161 } 3162 3163 // Fill in the trailing argument array. 3164 auto *argSlot = getTrailingObjects<QualType>(); 3165 for (unsigned i = 0; i != getNumParams(); ++i) { 3166 addDependence(params[i]->getDependence() & 3167 ~TypeDependence::VariablyModified); 3168 argSlot[i] = params[i]; 3169 } 3170 3171 // Fill in the exception type array if present. 3172 if (getExceptionSpecType() == EST_Dynamic) { 3173 assert(hasExtraBitfields() && "missing trailing extra bitfields!"); 3174 auto *exnSlot = 3175 reinterpret_cast<QualType *>(getTrailingObjects<ExceptionType>()); 3176 unsigned I = 0; 3177 for (QualType ExceptionType : epi.ExceptionSpec.Exceptions) { 3178 // Note that, before C++17, a dependent exception specification does 3179 // *not* make a type dependent; it's not even part of the C++ type 3180 // system. 3181 addDependence( 3182 ExceptionType->getDependence() & 3183 (TypeDependence::Instantiation | TypeDependence::UnexpandedPack)); 3184 3185 exnSlot[I++] = ExceptionType; 3186 } 3187 } 3188 // Fill in the Expr * in the exception specification if present. 3189 else if (isComputedNoexcept(getExceptionSpecType())) { 3190 assert(epi.ExceptionSpec.NoexceptExpr && "computed noexcept with no expr"); 3191 assert((getExceptionSpecType() == EST_DependentNoexcept) == 3192 epi.ExceptionSpec.NoexceptExpr->isValueDependent()); 3193 3194 // Store the noexcept expression and context. 3195 *getTrailingObjects<Expr *>() = epi.ExceptionSpec.NoexceptExpr; 3196 3197 addDependence( 3198 toTypeDependence(epi.ExceptionSpec.NoexceptExpr->getDependence()) & 3199 (TypeDependence::Instantiation | TypeDependence::UnexpandedPack)); 3200 } 3201 // Fill in the FunctionDecl * in the exception specification if present. 3202 else if (getExceptionSpecType() == EST_Uninstantiated) { 3203 // Store the function decl from which we will resolve our 3204 // exception specification. 3205 auto **slot = getTrailingObjects<FunctionDecl *>(); 3206 slot[0] = epi.ExceptionSpec.SourceDecl; 3207 slot[1] = epi.ExceptionSpec.SourceTemplate; 3208 // This exception specification doesn't make the type dependent, because 3209 // it's not instantiated as part of instantiating the type. 3210 } else if (getExceptionSpecType() == EST_Unevaluated) { 3211 // Store the function decl from which we will resolve our 3212 // exception specification. 3213 auto **slot = getTrailingObjects<FunctionDecl *>(); 3214 slot[0] = epi.ExceptionSpec.SourceDecl; 3215 } 3216 3217 // If this is a canonical type, and its exception specification is dependent, 3218 // then it's a dependent type. This only happens in C++17 onwards. 3219 if (isCanonicalUnqualified()) { 3220 if (getExceptionSpecType() == EST_Dynamic || 3221 getExceptionSpecType() == EST_DependentNoexcept) { 3222 assert(hasDependentExceptionSpec() && "type should not be canonical"); 3223 addDependence(TypeDependence::DependentInstantiation); 3224 } 3225 } else if (getCanonicalTypeInternal()->isDependentType()) { 3226 // Ask our canonical type whether our exception specification was dependent. 3227 addDependence(TypeDependence::DependentInstantiation); 3228 } 3229 3230 // Fill in the extra parameter info if present. 3231 if (epi.ExtParameterInfos) { 3232 auto *extParamInfos = getTrailingObjects<ExtParameterInfo>(); 3233 for (unsigned i = 0; i != getNumParams(); ++i) 3234 extParamInfos[i] = epi.ExtParameterInfos[i]; 3235 } 3236 3237 if (epi.TypeQuals.hasNonFastQualifiers()) { 3238 FunctionTypeBits.HasExtQuals = 1; 3239 *getTrailingObjects<Qualifiers>() = epi.TypeQuals; 3240 } else { 3241 FunctionTypeBits.HasExtQuals = 0; 3242 } 3243 3244 // Fill in the Ellipsis location info if present. 3245 if (epi.Variadic) { 3246 auto &EllipsisLoc = *getTrailingObjects<SourceLocation>(); 3247 EllipsisLoc = epi.EllipsisLoc; 3248 } 3249 } 3250 3251 bool FunctionProtoType::hasDependentExceptionSpec() const { 3252 if (Expr *NE = getNoexceptExpr()) 3253 return NE->isValueDependent(); 3254 for (QualType ET : exceptions()) 3255 // A pack expansion with a non-dependent pattern is still dependent, 3256 // because we don't know whether the pattern is in the exception spec 3257 // or not (that depends on whether the pack has 0 expansions). 3258 if (ET->isDependentType() || ET->getAs<PackExpansionType>()) 3259 return true; 3260 return false; 3261 } 3262 3263 bool FunctionProtoType::hasInstantiationDependentExceptionSpec() const { 3264 if (Expr *NE = getNoexceptExpr()) 3265 return NE->isInstantiationDependent(); 3266 for (QualType ET : exceptions()) 3267 if (ET->isInstantiationDependentType()) 3268 return true; 3269 return false; 3270 } 3271 3272 CanThrowResult FunctionProtoType::canThrow() const { 3273 switch (getExceptionSpecType()) { 3274 case EST_Unparsed: 3275 case EST_Unevaluated: 3276 case EST_Uninstantiated: 3277 llvm_unreachable("should not call this with unresolved exception specs"); 3278 3279 case EST_DynamicNone: 3280 case EST_BasicNoexcept: 3281 case EST_NoexceptTrue: 3282 case EST_NoThrow: 3283 return CT_Cannot; 3284 3285 case EST_None: 3286 case EST_MSAny: 3287 case EST_NoexceptFalse: 3288 return CT_Can; 3289 3290 case EST_Dynamic: 3291 // A dynamic exception specification is throwing unless every exception 3292 // type is an (unexpanded) pack expansion type. 3293 for (unsigned I = 0; I != getNumExceptions(); ++I) 3294 if (!getExceptionType(I)->getAs<PackExpansionType>()) 3295 return CT_Can; 3296 return CT_Dependent; 3297 3298 case EST_DependentNoexcept: 3299 return CT_Dependent; 3300 } 3301 3302 llvm_unreachable("unexpected exception specification kind"); 3303 } 3304 3305 bool FunctionProtoType::isTemplateVariadic() const { 3306 for (unsigned ArgIdx = getNumParams(); ArgIdx; --ArgIdx) 3307 if (isa<PackExpansionType>(getParamType(ArgIdx - 1))) 3308 return true; 3309 3310 return false; 3311 } 3312 3313 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result, 3314 const QualType *ArgTys, unsigned NumParams, 3315 const ExtProtoInfo &epi, 3316 const ASTContext &Context, bool Canonical) { 3317 // We have to be careful not to get ambiguous profile encodings. 3318 // Note that valid type pointers are never ambiguous with anything else. 3319 // 3320 // The encoding grammar begins: 3321 // type type* bool int bool 3322 // If that final bool is true, then there is a section for the EH spec: 3323 // bool type* 3324 // This is followed by an optional "consumed argument" section of the 3325 // same length as the first type sequence: 3326 // bool* 3327 // Finally, we have the ext info and trailing return type flag: 3328 // int bool 3329 // 3330 // There is no ambiguity between the consumed arguments and an empty EH 3331 // spec because of the leading 'bool' which unambiguously indicates 3332 // whether the following bool is the EH spec or part of the arguments. 3333 3334 ID.AddPointer(Result.getAsOpaquePtr()); 3335 for (unsigned i = 0; i != NumParams; ++i) 3336 ID.AddPointer(ArgTys[i].getAsOpaquePtr()); 3337 // This method is relatively performance sensitive, so as a performance 3338 // shortcut, use one AddInteger call instead of four for the next four 3339 // fields. 3340 assert(!(unsigned(epi.Variadic) & ~1) && 3341 !(unsigned(epi.RefQualifier) & ~3) && 3342 !(unsigned(epi.ExceptionSpec.Type) & ~15) && 3343 "Values larger than expected."); 3344 ID.AddInteger(unsigned(epi.Variadic) + 3345 (epi.RefQualifier << 1) + 3346 (epi.ExceptionSpec.Type << 3)); 3347 ID.Add(epi.TypeQuals); 3348 if (epi.ExceptionSpec.Type == EST_Dynamic) { 3349 for (QualType Ex : epi.ExceptionSpec.Exceptions) 3350 ID.AddPointer(Ex.getAsOpaquePtr()); 3351 } else if (isComputedNoexcept(epi.ExceptionSpec.Type)) { 3352 epi.ExceptionSpec.NoexceptExpr->Profile(ID, Context, Canonical); 3353 } else if (epi.ExceptionSpec.Type == EST_Uninstantiated || 3354 epi.ExceptionSpec.Type == EST_Unevaluated) { 3355 ID.AddPointer(epi.ExceptionSpec.SourceDecl->getCanonicalDecl()); 3356 } 3357 if (epi.ExtParameterInfos) { 3358 for (unsigned i = 0; i != NumParams; ++i) 3359 ID.AddInteger(epi.ExtParameterInfos[i].getOpaqueValue()); 3360 } 3361 epi.ExtInfo.Profile(ID); 3362 ID.AddBoolean(epi.HasTrailingReturn); 3363 } 3364 3365 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, 3366 const ASTContext &Ctx) { 3367 Profile(ID, getReturnType(), param_type_begin(), getNumParams(), 3368 getExtProtoInfo(), Ctx, isCanonicalUnqualified()); 3369 } 3370 3371 TypedefType::TypedefType(TypeClass tc, const TypedefNameDecl *D, 3372 QualType underlying, QualType can) 3373 : Type(tc, can, underlying->getDependence()), 3374 Decl(const_cast<TypedefNameDecl *>(D)) { 3375 assert(!isa<TypedefType>(can) && "Invalid canonical type"); 3376 } 3377 3378 QualType TypedefType::desugar() const { 3379 return getDecl()->getUnderlyingType(); 3380 } 3381 3382 QualType MacroQualifiedType::desugar() const { return getUnderlyingType(); } 3383 3384 QualType MacroQualifiedType::getModifiedType() const { 3385 // Step over MacroQualifiedTypes from the same macro to find the type 3386 // ultimately qualified by the macro qualifier. 3387 QualType Inner = cast<AttributedType>(getUnderlyingType())->getModifiedType(); 3388 while (auto *InnerMQT = dyn_cast<MacroQualifiedType>(Inner)) { 3389 if (InnerMQT->getMacroIdentifier() != getMacroIdentifier()) 3390 break; 3391 Inner = InnerMQT->getModifiedType(); 3392 } 3393 return Inner; 3394 } 3395 3396 TypeOfExprType::TypeOfExprType(Expr *E, QualType can) 3397 : Type(TypeOfExpr, can, 3398 typeToTypeDependence(E->getDependence(), 3399 E->getType()->getDependence())), 3400 TOExpr(E) {} 3401 3402 bool TypeOfExprType::isSugared() const { 3403 return !TOExpr->isTypeDependent(); 3404 } 3405 3406 QualType TypeOfExprType::desugar() const { 3407 if (isSugared()) 3408 return getUnderlyingExpr()->getType(); 3409 3410 return QualType(this, 0); 3411 } 3412 3413 void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID, 3414 const ASTContext &Context, Expr *E) { 3415 E->Profile(ID, Context, true); 3416 } 3417 3418 DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can) 3419 : Type(Decltype, can, 3420 typeToTypeDependence(E->getDependence(), 3421 E->getType()->getDependence())), 3422 E(E), UnderlyingType(underlyingType) {} 3423 3424 bool DecltypeType::isSugared() const { return !E->isTypeDependent(); } 3425 3426 QualType DecltypeType::desugar() const { 3427 if (isSugared()) 3428 return getUnderlyingType(); 3429 3430 return QualType(this, 0); 3431 } 3432 3433 DependentDecltypeType::DependentDecltypeType(const ASTContext &Context, Expr *E) 3434 : DecltypeType(E, Context.DependentTy), Context(Context) {} 3435 3436 void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID, 3437 const ASTContext &Context, Expr *E) { 3438 E->Profile(ID, Context, true); 3439 } 3440 3441 UnaryTransformType::UnaryTransformType(QualType BaseType, 3442 QualType UnderlyingType, UTTKind UKind, 3443 QualType CanonicalType) 3444 : Type(UnaryTransform, CanonicalType, BaseType->getDependence()), 3445 BaseType(BaseType), UnderlyingType(UnderlyingType), UKind(UKind) {} 3446 3447 DependentUnaryTransformType::DependentUnaryTransformType(const ASTContext &C, 3448 QualType BaseType, 3449 UTTKind UKind) 3450 : UnaryTransformType(BaseType, C.DependentTy, UKind, QualType()) {} 3451 3452 TagType::TagType(TypeClass TC, const TagDecl *D, QualType can) 3453 : Type(TC, can, 3454 D->isDependentType() ? TypeDependence::DependentInstantiation 3455 : TypeDependence::None), 3456 decl(const_cast<TagDecl *>(D)) {} 3457 3458 static TagDecl *getInterestingTagDecl(TagDecl *decl) { 3459 for (auto I : decl->redecls()) { 3460 if (I->isCompleteDefinition() || I->isBeingDefined()) 3461 return I; 3462 } 3463 // If there's no definition (not even in progress), return what we have. 3464 return decl; 3465 } 3466 3467 TagDecl *TagType::getDecl() const { 3468 return getInterestingTagDecl(decl); 3469 } 3470 3471 bool TagType::isBeingDefined() const { 3472 return getDecl()->isBeingDefined(); 3473 } 3474 3475 bool RecordType::hasConstFields() const { 3476 std::vector<const RecordType*> RecordTypeList; 3477 RecordTypeList.push_back(this); 3478 unsigned NextToCheckIndex = 0; 3479 3480 while (RecordTypeList.size() > NextToCheckIndex) { 3481 for (FieldDecl *FD : 3482 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 3483 QualType FieldTy = FD->getType(); 3484 if (FieldTy.isConstQualified()) 3485 return true; 3486 FieldTy = FieldTy.getCanonicalType(); 3487 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 3488 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) 3489 RecordTypeList.push_back(FieldRecTy); 3490 } 3491 } 3492 ++NextToCheckIndex; 3493 } 3494 return false; 3495 } 3496 3497 bool AttributedType::isQualifier() const { 3498 // FIXME: Generate this with TableGen. 3499 switch (getAttrKind()) { 3500 // These are type qualifiers in the traditional C sense: they annotate 3501 // something about a specific value/variable of a type. (They aren't 3502 // always part of the canonical type, though.) 3503 case attr::ObjCGC: 3504 case attr::ObjCOwnership: 3505 case attr::ObjCInertUnsafeUnretained: 3506 case attr::TypeNonNull: 3507 case attr::TypeNullable: 3508 case attr::TypeNullableResult: 3509 case attr::TypeNullUnspecified: 3510 case attr::LifetimeBound: 3511 case attr::AddressSpace: 3512 return true; 3513 3514 // All other type attributes aren't qualifiers; they rewrite the modified 3515 // type to be a semantically different type. 3516 default: 3517 return false; 3518 } 3519 } 3520 3521 bool AttributedType::isMSTypeSpec() const { 3522 // FIXME: Generate this with TableGen? 3523 switch (getAttrKind()) { 3524 default: return false; 3525 case attr::Ptr32: 3526 case attr::Ptr64: 3527 case attr::SPtr: 3528 case attr::UPtr: 3529 return true; 3530 } 3531 llvm_unreachable("invalid attr kind"); 3532 } 3533 3534 bool AttributedType::isCallingConv() const { 3535 // FIXME: Generate this with TableGen. 3536 switch (getAttrKind()) { 3537 default: return false; 3538 case attr::Pcs: 3539 case attr::CDecl: 3540 case attr::FastCall: 3541 case attr::StdCall: 3542 case attr::ThisCall: 3543 case attr::RegCall: 3544 case attr::SwiftCall: 3545 case attr::VectorCall: 3546 case attr::AArch64VectorPcs: 3547 case attr::Pascal: 3548 case attr::MSABI: 3549 case attr::SysVABI: 3550 case attr::IntelOclBicc: 3551 case attr::PreserveMost: 3552 case attr::PreserveAll: 3553 return true; 3554 } 3555 llvm_unreachable("invalid attr kind"); 3556 } 3557 3558 CXXRecordDecl *InjectedClassNameType::getDecl() const { 3559 return cast<CXXRecordDecl>(getInterestingTagDecl(Decl)); 3560 } 3561 3562 IdentifierInfo *TemplateTypeParmType::getIdentifier() const { 3563 return isCanonicalUnqualified() ? nullptr : getDecl()->getIdentifier(); 3564 } 3565 3566 SubstTemplateTypeParmPackType::SubstTemplateTypeParmPackType( 3567 const TemplateTypeParmType *Param, QualType Canon, 3568 const TemplateArgument &ArgPack) 3569 : Type(SubstTemplateTypeParmPack, Canon, 3570 TypeDependence::DependentInstantiation | 3571 TypeDependence::UnexpandedPack), 3572 Replaced(Param), Arguments(ArgPack.pack_begin()) { 3573 SubstTemplateTypeParmPackTypeBits.NumArgs = ArgPack.pack_size(); 3574 } 3575 3576 TemplateArgument SubstTemplateTypeParmPackType::getArgumentPack() const { 3577 return TemplateArgument(llvm::makeArrayRef(Arguments, getNumArgs())); 3578 } 3579 3580 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID) { 3581 Profile(ID, getReplacedParameter(), getArgumentPack()); 3582 } 3583 3584 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID, 3585 const TemplateTypeParmType *Replaced, 3586 const TemplateArgument &ArgPack) { 3587 ID.AddPointer(Replaced); 3588 ID.AddInteger(ArgPack.pack_size()); 3589 for (const auto &P : ArgPack.pack_elements()) 3590 ID.AddPointer(P.getAsType().getAsOpaquePtr()); 3591 } 3592 3593 bool TemplateSpecializationType::anyDependentTemplateArguments( 3594 const TemplateArgumentListInfo &Args, ArrayRef<TemplateArgument> Converted) { 3595 return anyDependentTemplateArguments(Args.arguments(), Converted); 3596 } 3597 3598 bool TemplateSpecializationType::anyDependentTemplateArguments( 3599 ArrayRef<TemplateArgumentLoc> Args, ArrayRef<TemplateArgument> Converted) { 3600 for (const TemplateArgument &Arg : Converted) 3601 if (Arg.isDependent()) 3602 return true; 3603 return false; 3604 } 3605 3606 bool TemplateSpecializationType::anyInstantiationDependentTemplateArguments( 3607 ArrayRef<TemplateArgumentLoc> Args) { 3608 for (const TemplateArgumentLoc &ArgLoc : Args) { 3609 if (ArgLoc.getArgument().isInstantiationDependent()) 3610 return true; 3611 } 3612 return false; 3613 } 3614 3615 TemplateSpecializationType::TemplateSpecializationType( 3616 TemplateName T, ArrayRef<TemplateArgument> Args, QualType Canon, 3617 QualType AliasedType) 3618 : Type(TemplateSpecialization, Canon.isNull() ? QualType(this, 0) : Canon, 3619 (Canon.isNull() 3620 ? TypeDependence::DependentInstantiation 3621 : Canon->getDependence() & ~(TypeDependence::VariablyModified | 3622 TypeDependence::UnexpandedPack)) | 3623 (toTypeDependence(T.getDependence()) & 3624 TypeDependence::UnexpandedPack)), 3625 Template(T) { 3626 TemplateSpecializationTypeBits.NumArgs = Args.size(); 3627 TemplateSpecializationTypeBits.TypeAlias = !AliasedType.isNull(); 3628 3629 assert(!T.getAsDependentTemplateName() && 3630 "Use DependentTemplateSpecializationType for dependent template-name"); 3631 assert((T.getKind() == TemplateName::Template || 3632 T.getKind() == TemplateName::SubstTemplateTemplateParm || 3633 T.getKind() == TemplateName::SubstTemplateTemplateParmPack) && 3634 "Unexpected template name for TemplateSpecializationType"); 3635 3636 auto *TemplateArgs = reinterpret_cast<TemplateArgument *>(this + 1); 3637 for (const TemplateArgument &Arg : Args) { 3638 // Update instantiation-dependent, variably-modified, and error bits. 3639 // If the canonical type exists and is non-dependent, the template 3640 // specialization type can be non-dependent even if one of the type 3641 // arguments is. Given: 3642 // template<typename T> using U = int; 3643 // U<T> is always non-dependent, irrespective of the type T. 3644 // However, U<Ts> contains an unexpanded parameter pack, even though 3645 // its expansion (and thus its desugared type) doesn't. 3646 addDependence(toTypeDependence(Arg.getDependence()) & 3647 ~TypeDependence::Dependent); 3648 if (Arg.getKind() == TemplateArgument::Type) 3649 addDependence(Arg.getAsType()->getDependence() & 3650 TypeDependence::VariablyModified); 3651 new (TemplateArgs++) TemplateArgument(Arg); 3652 } 3653 3654 // Store the aliased type if this is a type alias template specialization. 3655 if (isTypeAlias()) { 3656 auto *Begin = reinterpret_cast<TemplateArgument *>(this + 1); 3657 *reinterpret_cast<QualType*>(Begin + getNumArgs()) = AliasedType; 3658 } 3659 } 3660 3661 void 3662 TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID, 3663 TemplateName T, 3664 ArrayRef<TemplateArgument> Args, 3665 const ASTContext &Context) { 3666 T.Profile(ID); 3667 for (const TemplateArgument &Arg : Args) 3668 Arg.Profile(ID, Context); 3669 } 3670 3671 QualType 3672 QualifierCollector::apply(const ASTContext &Context, QualType QT) const { 3673 if (!hasNonFastQualifiers()) 3674 return QT.withFastQualifiers(getFastQualifiers()); 3675 3676 return Context.getQualifiedType(QT, *this); 3677 } 3678 3679 QualType 3680 QualifierCollector::apply(const ASTContext &Context, const Type *T) const { 3681 if (!hasNonFastQualifiers()) 3682 return QualType(T, getFastQualifiers()); 3683 3684 return Context.getQualifiedType(T, *this); 3685 } 3686 3687 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID, 3688 QualType BaseType, 3689 ArrayRef<QualType> typeArgs, 3690 ArrayRef<ObjCProtocolDecl *> protocols, 3691 bool isKindOf) { 3692 ID.AddPointer(BaseType.getAsOpaquePtr()); 3693 ID.AddInteger(typeArgs.size()); 3694 for (auto typeArg : typeArgs) 3695 ID.AddPointer(typeArg.getAsOpaquePtr()); 3696 ID.AddInteger(protocols.size()); 3697 for (auto proto : protocols) 3698 ID.AddPointer(proto); 3699 ID.AddBoolean(isKindOf); 3700 } 3701 3702 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID) { 3703 Profile(ID, getBaseType(), getTypeArgsAsWritten(), 3704 llvm::makeArrayRef(qual_begin(), getNumProtocols()), 3705 isKindOfTypeAsWritten()); 3706 } 3707 3708 void ObjCTypeParamType::Profile(llvm::FoldingSetNodeID &ID, 3709 const ObjCTypeParamDecl *OTPDecl, 3710 QualType CanonicalType, 3711 ArrayRef<ObjCProtocolDecl *> protocols) { 3712 ID.AddPointer(OTPDecl); 3713 ID.AddPointer(CanonicalType.getAsOpaquePtr()); 3714 ID.AddInteger(protocols.size()); 3715 for (auto proto : protocols) 3716 ID.AddPointer(proto); 3717 } 3718 3719 void ObjCTypeParamType::Profile(llvm::FoldingSetNodeID &ID) { 3720 Profile(ID, getDecl(), getCanonicalTypeInternal(), 3721 llvm::makeArrayRef(qual_begin(), getNumProtocols())); 3722 } 3723 3724 namespace { 3725 3726 /// The cached properties of a type. 3727 class CachedProperties { 3728 Linkage L; 3729 bool local; 3730 3731 public: 3732 CachedProperties(Linkage L, bool local) : L(L), local(local) {} 3733 3734 Linkage getLinkage() const { return L; } 3735 bool hasLocalOrUnnamedType() const { return local; } 3736 3737 friend CachedProperties merge(CachedProperties L, CachedProperties R) { 3738 Linkage MergedLinkage = minLinkage(L.L, R.L); 3739 return CachedProperties(MergedLinkage, 3740 L.hasLocalOrUnnamedType() | R.hasLocalOrUnnamedType()); 3741 } 3742 }; 3743 3744 } // namespace 3745 3746 static CachedProperties computeCachedProperties(const Type *T); 3747 3748 namespace clang { 3749 3750 /// The type-property cache. This is templated so as to be 3751 /// instantiated at an internal type to prevent unnecessary symbol 3752 /// leakage. 3753 template <class Private> class TypePropertyCache { 3754 public: 3755 static CachedProperties get(QualType T) { 3756 return get(T.getTypePtr()); 3757 } 3758 3759 static CachedProperties get(const Type *T) { 3760 ensure(T); 3761 return CachedProperties(T->TypeBits.getLinkage(), 3762 T->TypeBits.hasLocalOrUnnamedType()); 3763 } 3764 3765 static void ensure(const Type *T) { 3766 // If the cache is valid, we're okay. 3767 if (T->TypeBits.isCacheValid()) return; 3768 3769 // If this type is non-canonical, ask its canonical type for the 3770 // relevant information. 3771 if (!T->isCanonicalUnqualified()) { 3772 const Type *CT = T->getCanonicalTypeInternal().getTypePtr(); 3773 ensure(CT); 3774 T->TypeBits.CacheValid = true; 3775 T->TypeBits.CachedLinkage = CT->TypeBits.CachedLinkage; 3776 T->TypeBits.CachedLocalOrUnnamed = CT->TypeBits.CachedLocalOrUnnamed; 3777 return; 3778 } 3779 3780 // Compute the cached properties and then set the cache. 3781 CachedProperties Result = computeCachedProperties(T); 3782 T->TypeBits.CacheValid = true; 3783 T->TypeBits.CachedLinkage = Result.getLinkage(); 3784 T->TypeBits.CachedLocalOrUnnamed = Result.hasLocalOrUnnamedType(); 3785 } 3786 }; 3787 3788 } // namespace clang 3789 3790 // Instantiate the friend template at a private class. In a 3791 // reasonable implementation, these symbols will be internal. 3792 // It is terrible that this is the best way to accomplish this. 3793 namespace { 3794 3795 class Private {}; 3796 3797 } // namespace 3798 3799 using Cache = TypePropertyCache<Private>; 3800 3801 static CachedProperties computeCachedProperties(const Type *T) { 3802 switch (T->getTypeClass()) { 3803 #define TYPE(Class,Base) 3804 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class: 3805 #include "clang/AST/TypeNodes.inc" 3806 llvm_unreachable("didn't expect a non-canonical type here"); 3807 3808 #define TYPE(Class,Base) 3809 #define DEPENDENT_TYPE(Class,Base) case Type::Class: 3810 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class: 3811 #include "clang/AST/TypeNodes.inc" 3812 // Treat instantiation-dependent types as external. 3813 if (!T->isInstantiationDependentType()) T->dump(); 3814 assert(T->isInstantiationDependentType()); 3815 return CachedProperties(ExternalLinkage, false); 3816 3817 case Type::Auto: 3818 case Type::DeducedTemplateSpecialization: 3819 // Give non-deduced 'auto' types external linkage. We should only see them 3820 // here in error recovery. 3821 return CachedProperties(ExternalLinkage, false); 3822 3823 case Type::ExtInt: 3824 case Type::Builtin: 3825 // C++ [basic.link]p8: 3826 // A type is said to have linkage if and only if: 3827 // - it is a fundamental type (3.9.1); or 3828 return CachedProperties(ExternalLinkage, false); 3829 3830 case Type::Record: 3831 case Type::Enum: { 3832 const TagDecl *Tag = cast<TagType>(T)->getDecl(); 3833 3834 // C++ [basic.link]p8: 3835 // - it is a class or enumeration type that is named (or has a name 3836 // for linkage purposes (7.1.3)) and the name has linkage; or 3837 // - it is a specialization of a class template (14); or 3838 Linkage L = Tag->getLinkageInternal(); 3839 bool IsLocalOrUnnamed = 3840 Tag->getDeclContext()->isFunctionOrMethod() || 3841 !Tag->hasNameForLinkage(); 3842 return CachedProperties(L, IsLocalOrUnnamed); 3843 } 3844 3845 // C++ [basic.link]p8: 3846 // - it is a compound type (3.9.2) other than a class or enumeration, 3847 // compounded exclusively from types that have linkage; or 3848 case Type::Complex: 3849 return Cache::get(cast<ComplexType>(T)->getElementType()); 3850 case Type::Pointer: 3851 return Cache::get(cast<PointerType>(T)->getPointeeType()); 3852 case Type::BlockPointer: 3853 return Cache::get(cast<BlockPointerType>(T)->getPointeeType()); 3854 case Type::LValueReference: 3855 case Type::RValueReference: 3856 return Cache::get(cast<ReferenceType>(T)->getPointeeType()); 3857 case Type::MemberPointer: { 3858 const auto *MPT = cast<MemberPointerType>(T); 3859 return merge(Cache::get(MPT->getClass()), 3860 Cache::get(MPT->getPointeeType())); 3861 } 3862 case Type::ConstantArray: 3863 case Type::IncompleteArray: 3864 case Type::VariableArray: 3865 return Cache::get(cast<ArrayType>(T)->getElementType()); 3866 case Type::Vector: 3867 case Type::ExtVector: 3868 return Cache::get(cast<VectorType>(T)->getElementType()); 3869 case Type::ConstantMatrix: 3870 return Cache::get(cast<ConstantMatrixType>(T)->getElementType()); 3871 case Type::FunctionNoProto: 3872 return Cache::get(cast<FunctionType>(T)->getReturnType()); 3873 case Type::FunctionProto: { 3874 const auto *FPT = cast<FunctionProtoType>(T); 3875 CachedProperties result = Cache::get(FPT->getReturnType()); 3876 for (const auto &ai : FPT->param_types()) 3877 result = merge(result, Cache::get(ai)); 3878 return result; 3879 } 3880 case Type::ObjCInterface: { 3881 Linkage L = cast<ObjCInterfaceType>(T)->getDecl()->getLinkageInternal(); 3882 return CachedProperties(L, false); 3883 } 3884 case Type::ObjCObject: 3885 return Cache::get(cast<ObjCObjectType>(T)->getBaseType()); 3886 case Type::ObjCObjectPointer: 3887 return Cache::get(cast<ObjCObjectPointerType>(T)->getPointeeType()); 3888 case Type::Atomic: 3889 return Cache::get(cast<AtomicType>(T)->getValueType()); 3890 case Type::Pipe: 3891 return Cache::get(cast<PipeType>(T)->getElementType()); 3892 } 3893 3894 llvm_unreachable("unhandled type class"); 3895 } 3896 3897 /// Determine the linkage of this type. 3898 Linkage Type::getLinkage() const { 3899 Cache::ensure(this); 3900 return TypeBits.getLinkage(); 3901 } 3902 3903 bool Type::hasUnnamedOrLocalType() const { 3904 Cache::ensure(this); 3905 return TypeBits.hasLocalOrUnnamedType(); 3906 } 3907 3908 LinkageInfo LinkageComputer::computeTypeLinkageInfo(const Type *T) { 3909 switch (T->getTypeClass()) { 3910 #define TYPE(Class,Base) 3911 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class: 3912 #include "clang/AST/TypeNodes.inc" 3913 llvm_unreachable("didn't expect a non-canonical type here"); 3914 3915 #define TYPE(Class,Base) 3916 #define DEPENDENT_TYPE(Class,Base) case Type::Class: 3917 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class: 3918 #include "clang/AST/TypeNodes.inc" 3919 // Treat instantiation-dependent types as external. 3920 assert(T->isInstantiationDependentType()); 3921 return LinkageInfo::external(); 3922 3923 case Type::ExtInt: 3924 case Type::Builtin: 3925 return LinkageInfo::external(); 3926 3927 case Type::Auto: 3928 case Type::DeducedTemplateSpecialization: 3929 return LinkageInfo::external(); 3930 3931 case Type::Record: 3932 case Type::Enum: 3933 return getDeclLinkageAndVisibility(cast<TagType>(T)->getDecl()); 3934 3935 case Type::Complex: 3936 return computeTypeLinkageInfo(cast<ComplexType>(T)->getElementType()); 3937 case Type::Pointer: 3938 return computeTypeLinkageInfo(cast<PointerType>(T)->getPointeeType()); 3939 case Type::BlockPointer: 3940 return computeTypeLinkageInfo(cast<BlockPointerType>(T)->getPointeeType()); 3941 case Type::LValueReference: 3942 case Type::RValueReference: 3943 return computeTypeLinkageInfo(cast<ReferenceType>(T)->getPointeeType()); 3944 case Type::MemberPointer: { 3945 const auto *MPT = cast<MemberPointerType>(T); 3946 LinkageInfo LV = computeTypeLinkageInfo(MPT->getClass()); 3947 LV.merge(computeTypeLinkageInfo(MPT->getPointeeType())); 3948 return LV; 3949 } 3950 case Type::ConstantArray: 3951 case Type::IncompleteArray: 3952 case Type::VariableArray: 3953 return computeTypeLinkageInfo(cast<ArrayType>(T)->getElementType()); 3954 case Type::Vector: 3955 case Type::ExtVector: 3956 return computeTypeLinkageInfo(cast<VectorType>(T)->getElementType()); 3957 case Type::ConstantMatrix: 3958 return computeTypeLinkageInfo( 3959 cast<ConstantMatrixType>(T)->getElementType()); 3960 case Type::FunctionNoProto: 3961 return computeTypeLinkageInfo(cast<FunctionType>(T)->getReturnType()); 3962 case Type::FunctionProto: { 3963 const auto *FPT = cast<FunctionProtoType>(T); 3964 LinkageInfo LV = computeTypeLinkageInfo(FPT->getReturnType()); 3965 for (const auto &ai : FPT->param_types()) 3966 LV.merge(computeTypeLinkageInfo(ai)); 3967 return LV; 3968 } 3969 case Type::ObjCInterface: 3970 return getDeclLinkageAndVisibility(cast<ObjCInterfaceType>(T)->getDecl()); 3971 case Type::ObjCObject: 3972 return computeTypeLinkageInfo(cast<ObjCObjectType>(T)->getBaseType()); 3973 case Type::ObjCObjectPointer: 3974 return computeTypeLinkageInfo( 3975 cast<ObjCObjectPointerType>(T)->getPointeeType()); 3976 case Type::Atomic: 3977 return computeTypeLinkageInfo(cast<AtomicType>(T)->getValueType()); 3978 case Type::Pipe: 3979 return computeTypeLinkageInfo(cast<PipeType>(T)->getElementType()); 3980 } 3981 3982 llvm_unreachable("unhandled type class"); 3983 } 3984 3985 bool Type::isLinkageValid() const { 3986 if (!TypeBits.isCacheValid()) 3987 return true; 3988 3989 Linkage L = LinkageComputer{} 3990 .computeTypeLinkageInfo(getCanonicalTypeInternal()) 3991 .getLinkage(); 3992 return L == TypeBits.getLinkage(); 3993 } 3994 3995 LinkageInfo LinkageComputer::getTypeLinkageAndVisibility(const Type *T) { 3996 if (!T->isCanonicalUnqualified()) 3997 return computeTypeLinkageInfo(T->getCanonicalTypeInternal()); 3998 3999 LinkageInfo LV = computeTypeLinkageInfo(T); 4000 assert(LV.getLinkage() == T->getLinkage()); 4001 return LV; 4002 } 4003 4004 LinkageInfo Type::getLinkageAndVisibility() const { 4005 return LinkageComputer{}.getTypeLinkageAndVisibility(this); 4006 } 4007 4008 Optional<NullabilityKind> 4009 Type::getNullability(const ASTContext &Context) const { 4010 QualType Type(this, 0); 4011 while (const auto *AT = Type->getAs<AttributedType>()) { 4012 // Check whether this is an attributed type with nullability 4013 // information. 4014 if (auto Nullability = AT->getImmediateNullability()) 4015 return Nullability; 4016 4017 Type = AT->getEquivalentType(); 4018 } 4019 return None; 4020 } 4021 4022 bool Type::canHaveNullability(bool ResultIfUnknown) const { 4023 QualType type = getCanonicalTypeInternal(); 4024 4025 switch (type->getTypeClass()) { 4026 // We'll only see canonical types here. 4027 #define NON_CANONICAL_TYPE(Class, Parent) \ 4028 case Type::Class: \ 4029 llvm_unreachable("non-canonical type"); 4030 #define TYPE(Class, Parent) 4031 #include "clang/AST/TypeNodes.inc" 4032 4033 // Pointer types. 4034 case Type::Pointer: 4035 case Type::BlockPointer: 4036 case Type::MemberPointer: 4037 case Type::ObjCObjectPointer: 4038 return true; 4039 4040 // Dependent types that could instantiate to pointer types. 4041 case Type::UnresolvedUsing: 4042 case Type::TypeOfExpr: 4043 case Type::TypeOf: 4044 case Type::Decltype: 4045 case Type::UnaryTransform: 4046 case Type::TemplateTypeParm: 4047 case Type::SubstTemplateTypeParmPack: 4048 case Type::DependentName: 4049 case Type::DependentTemplateSpecialization: 4050 case Type::Auto: 4051 return ResultIfUnknown; 4052 4053 // Dependent template specializations can instantiate to pointer 4054 // types unless they're known to be specializations of a class 4055 // template. 4056 case Type::TemplateSpecialization: 4057 if (TemplateDecl *templateDecl 4058 = cast<TemplateSpecializationType>(type.getTypePtr()) 4059 ->getTemplateName().getAsTemplateDecl()) { 4060 if (isa<ClassTemplateDecl>(templateDecl)) 4061 return false; 4062 } 4063 return ResultIfUnknown; 4064 4065 case Type::Builtin: 4066 switch (cast<BuiltinType>(type.getTypePtr())->getKind()) { 4067 // Signed, unsigned, and floating-point types cannot have nullability. 4068 #define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id: 4069 #define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id: 4070 #define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id: 4071 #define BUILTIN_TYPE(Id, SingletonId) 4072 #include "clang/AST/BuiltinTypes.def" 4073 return false; 4074 4075 // Dependent types that could instantiate to a pointer type. 4076 case BuiltinType::Dependent: 4077 case BuiltinType::Overload: 4078 case BuiltinType::BoundMember: 4079 case BuiltinType::PseudoObject: 4080 case BuiltinType::UnknownAny: 4081 case BuiltinType::ARCUnbridgedCast: 4082 return ResultIfUnknown; 4083 4084 case BuiltinType::Void: 4085 case BuiltinType::ObjCId: 4086 case BuiltinType::ObjCClass: 4087 case BuiltinType::ObjCSel: 4088 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 4089 case BuiltinType::Id: 4090 #include "clang/Basic/OpenCLImageTypes.def" 4091 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 4092 case BuiltinType::Id: 4093 #include "clang/Basic/OpenCLExtensionTypes.def" 4094 case BuiltinType::OCLSampler: 4095 case BuiltinType::OCLEvent: 4096 case BuiltinType::OCLClkEvent: 4097 case BuiltinType::OCLQueue: 4098 case BuiltinType::OCLReserveID: 4099 #define SVE_TYPE(Name, Id, SingletonId) \ 4100 case BuiltinType::Id: 4101 #include "clang/Basic/AArch64SVEACLETypes.def" 4102 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 4103 case BuiltinType::Id: 4104 #include "clang/Basic/PPCTypes.def" 4105 case BuiltinType::BuiltinFn: 4106 case BuiltinType::NullPtr: 4107 case BuiltinType::IncompleteMatrixIdx: 4108 case BuiltinType::OMPArraySection: 4109 case BuiltinType::OMPArrayShaping: 4110 case BuiltinType::OMPIterator: 4111 return false; 4112 } 4113 llvm_unreachable("unknown builtin type"); 4114 4115 // Non-pointer types. 4116 case Type::Complex: 4117 case Type::LValueReference: 4118 case Type::RValueReference: 4119 case Type::ConstantArray: 4120 case Type::IncompleteArray: 4121 case Type::VariableArray: 4122 case Type::DependentSizedArray: 4123 case Type::DependentVector: 4124 case Type::DependentSizedExtVector: 4125 case Type::Vector: 4126 case Type::ExtVector: 4127 case Type::ConstantMatrix: 4128 case Type::DependentSizedMatrix: 4129 case Type::DependentAddressSpace: 4130 case Type::FunctionProto: 4131 case Type::FunctionNoProto: 4132 case Type::Record: 4133 case Type::DeducedTemplateSpecialization: 4134 case Type::Enum: 4135 case Type::InjectedClassName: 4136 case Type::PackExpansion: 4137 case Type::ObjCObject: 4138 case Type::ObjCInterface: 4139 case Type::Atomic: 4140 case Type::Pipe: 4141 case Type::ExtInt: 4142 case Type::DependentExtInt: 4143 return false; 4144 } 4145 llvm_unreachable("bad type kind!"); 4146 } 4147 4148 llvm::Optional<NullabilityKind> 4149 AttributedType::getImmediateNullability() const { 4150 if (getAttrKind() == attr::TypeNonNull) 4151 return NullabilityKind::NonNull; 4152 if (getAttrKind() == attr::TypeNullable) 4153 return NullabilityKind::Nullable; 4154 if (getAttrKind() == attr::TypeNullUnspecified) 4155 return NullabilityKind::Unspecified; 4156 if (getAttrKind() == attr::TypeNullableResult) 4157 return NullabilityKind::NullableResult; 4158 return None; 4159 } 4160 4161 Optional<NullabilityKind> AttributedType::stripOuterNullability(QualType &T) { 4162 QualType AttrTy = T; 4163 if (auto MacroTy = dyn_cast<MacroQualifiedType>(T)) 4164 AttrTy = MacroTy->getUnderlyingType(); 4165 4166 if (auto attributed = dyn_cast<AttributedType>(AttrTy)) { 4167 if (auto nullability = attributed->getImmediateNullability()) { 4168 T = attributed->getModifiedType(); 4169 return nullability; 4170 } 4171 } 4172 4173 return None; 4174 } 4175 4176 bool Type::isBlockCompatibleObjCPointerType(ASTContext &ctx) const { 4177 const auto *objcPtr = getAs<ObjCObjectPointerType>(); 4178 if (!objcPtr) 4179 return false; 4180 4181 if (objcPtr->isObjCIdType()) { 4182 // id is always okay. 4183 return true; 4184 } 4185 4186 // Blocks are NSObjects. 4187 if (ObjCInterfaceDecl *iface = objcPtr->getInterfaceDecl()) { 4188 if (iface->getIdentifier() != ctx.getNSObjectName()) 4189 return false; 4190 4191 // Continue to check qualifiers, below. 4192 } else if (objcPtr->isObjCQualifiedIdType()) { 4193 // Continue to check qualifiers, below. 4194 } else { 4195 return false; 4196 } 4197 4198 // Check protocol qualifiers. 4199 for (ObjCProtocolDecl *proto : objcPtr->quals()) { 4200 // Blocks conform to NSObject and NSCopying. 4201 if (proto->getIdentifier() != ctx.getNSObjectName() && 4202 proto->getIdentifier() != ctx.getNSCopyingName()) 4203 return false; 4204 } 4205 4206 return true; 4207 } 4208 4209 Qualifiers::ObjCLifetime Type::getObjCARCImplicitLifetime() const { 4210 if (isObjCARCImplicitlyUnretainedType()) 4211 return Qualifiers::OCL_ExplicitNone; 4212 return Qualifiers::OCL_Strong; 4213 } 4214 4215 bool Type::isObjCARCImplicitlyUnretainedType() const { 4216 assert(isObjCLifetimeType() && 4217 "cannot query implicit lifetime for non-inferrable type"); 4218 4219 const Type *canon = getCanonicalTypeInternal().getTypePtr(); 4220 4221 // Walk down to the base type. We don't care about qualifiers for this. 4222 while (const auto *array = dyn_cast<ArrayType>(canon)) 4223 canon = array->getElementType().getTypePtr(); 4224 4225 if (const auto *opt = dyn_cast<ObjCObjectPointerType>(canon)) { 4226 // Class and Class<Protocol> don't require retention. 4227 if (opt->getObjectType()->isObjCClass()) 4228 return true; 4229 } 4230 4231 return false; 4232 } 4233 4234 bool Type::isObjCNSObjectType() const { 4235 const Type *cur = this; 4236 while (true) { 4237 if (const auto *typedefType = dyn_cast<TypedefType>(cur)) 4238 return typedefType->getDecl()->hasAttr<ObjCNSObjectAttr>(); 4239 4240 // Single-step desugar until we run out of sugar. 4241 QualType next = cur->getLocallyUnqualifiedSingleStepDesugaredType(); 4242 if (next.getTypePtr() == cur) return false; 4243 cur = next.getTypePtr(); 4244 } 4245 } 4246 4247 bool Type::isObjCIndependentClassType() const { 4248 if (const auto *typedefType = dyn_cast<TypedefType>(this)) 4249 return typedefType->getDecl()->hasAttr<ObjCIndependentClassAttr>(); 4250 return false; 4251 } 4252 4253 bool Type::isObjCRetainableType() const { 4254 return isObjCObjectPointerType() || 4255 isBlockPointerType() || 4256 isObjCNSObjectType(); 4257 } 4258 4259 bool Type::isObjCIndirectLifetimeType() const { 4260 if (isObjCLifetimeType()) 4261 return true; 4262 if (const auto *OPT = getAs<PointerType>()) 4263 return OPT->getPointeeType()->isObjCIndirectLifetimeType(); 4264 if (const auto *Ref = getAs<ReferenceType>()) 4265 return Ref->getPointeeType()->isObjCIndirectLifetimeType(); 4266 if (const auto *MemPtr = getAs<MemberPointerType>()) 4267 return MemPtr->getPointeeType()->isObjCIndirectLifetimeType(); 4268 return false; 4269 } 4270 4271 /// Returns true if objects of this type have lifetime semantics under 4272 /// ARC. 4273 bool Type::isObjCLifetimeType() const { 4274 const Type *type = this; 4275 while (const ArrayType *array = type->getAsArrayTypeUnsafe()) 4276 type = array->getElementType().getTypePtr(); 4277 return type->isObjCRetainableType(); 4278 } 4279 4280 /// Determine whether the given type T is a "bridgable" Objective-C type, 4281 /// which is either an Objective-C object pointer type or an 4282 bool Type::isObjCARCBridgableType() const { 4283 return isObjCObjectPointerType() || isBlockPointerType(); 4284 } 4285 4286 /// Determine whether the given type T is a "bridgeable" C type. 4287 bool Type::isCARCBridgableType() const { 4288 const auto *Pointer = getAs<PointerType>(); 4289 if (!Pointer) 4290 return false; 4291 4292 QualType Pointee = Pointer->getPointeeType(); 4293 return Pointee->isVoidType() || Pointee->isRecordType(); 4294 } 4295 4296 /// Check if the specified type is the CUDA device builtin surface type. 4297 bool Type::isCUDADeviceBuiltinSurfaceType() const { 4298 if (const auto *RT = getAs<RecordType>()) 4299 return RT->getDecl()->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>(); 4300 return false; 4301 } 4302 4303 /// Check if the specified type is the CUDA device builtin texture type. 4304 bool Type::isCUDADeviceBuiltinTextureType() const { 4305 if (const auto *RT = getAs<RecordType>()) 4306 return RT->getDecl()->hasAttr<CUDADeviceBuiltinTextureTypeAttr>(); 4307 return false; 4308 } 4309 4310 bool Type::hasSizedVLAType() const { 4311 if (!isVariablyModifiedType()) return false; 4312 4313 if (const auto *ptr = getAs<PointerType>()) 4314 return ptr->getPointeeType()->hasSizedVLAType(); 4315 if (const auto *ref = getAs<ReferenceType>()) 4316 return ref->getPointeeType()->hasSizedVLAType(); 4317 if (const ArrayType *arr = getAsArrayTypeUnsafe()) { 4318 if (isa<VariableArrayType>(arr) && 4319 cast<VariableArrayType>(arr)->getSizeExpr()) 4320 return true; 4321 4322 return arr->getElementType()->hasSizedVLAType(); 4323 } 4324 4325 return false; 4326 } 4327 4328 QualType::DestructionKind QualType::isDestructedTypeImpl(QualType type) { 4329 switch (type.getObjCLifetime()) { 4330 case Qualifiers::OCL_None: 4331 case Qualifiers::OCL_ExplicitNone: 4332 case Qualifiers::OCL_Autoreleasing: 4333 break; 4334 4335 case Qualifiers::OCL_Strong: 4336 return DK_objc_strong_lifetime; 4337 case Qualifiers::OCL_Weak: 4338 return DK_objc_weak_lifetime; 4339 } 4340 4341 if (const auto *RT = 4342 type->getBaseElementTypeUnsafe()->getAs<RecordType>()) { 4343 const RecordDecl *RD = RT->getDecl(); 4344 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 4345 /// Check if this is a C++ object with a non-trivial destructor. 4346 if (CXXRD->hasDefinition() && !CXXRD->hasTrivialDestructor()) 4347 return DK_cxx_destructor; 4348 } else { 4349 /// Check if this is a C struct that is non-trivial to destroy or an array 4350 /// that contains such a struct. 4351 if (RD->isNonTrivialToPrimitiveDestroy()) 4352 return DK_nontrivial_c_struct; 4353 } 4354 } 4355 4356 return DK_none; 4357 } 4358 4359 CXXRecordDecl *MemberPointerType::getMostRecentCXXRecordDecl() const { 4360 return getClass()->getAsCXXRecordDecl()->getMostRecentNonInjectedDecl(); 4361 } 4362 4363 void clang::FixedPointValueToString(SmallVectorImpl<char> &Str, 4364 llvm::APSInt Val, unsigned Scale) { 4365 llvm::FixedPointSemantics FXSema(Val.getBitWidth(), Scale, Val.isSigned(), 4366 /*IsSaturated=*/false, 4367 /*HasUnsignedPadding=*/false); 4368 llvm::APFixedPoint(Val, FXSema).toString(Str); 4369 } 4370 4371 AutoType::AutoType(QualType DeducedAsType, AutoTypeKeyword Keyword, 4372 TypeDependence ExtraDependence, 4373 ConceptDecl *TypeConstraintConcept, 4374 ArrayRef<TemplateArgument> TypeConstraintArgs) 4375 : DeducedType(Auto, DeducedAsType, ExtraDependence) { 4376 AutoTypeBits.Keyword = (unsigned)Keyword; 4377 AutoTypeBits.NumArgs = TypeConstraintArgs.size(); 4378 this->TypeConstraintConcept = TypeConstraintConcept; 4379 if (TypeConstraintConcept) { 4380 TemplateArgument *ArgBuffer = getArgBuffer(); 4381 for (const TemplateArgument &Arg : TypeConstraintArgs) { 4382 addDependence(toTypeDependence( 4383 Arg.getDependence() & TemplateArgumentDependence::UnexpandedPack)); 4384 4385 new (ArgBuffer++) TemplateArgument(Arg); 4386 } 4387 } 4388 } 4389 4390 void AutoType::Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, 4391 QualType Deduced, AutoTypeKeyword Keyword, 4392 bool IsDependent, ConceptDecl *CD, 4393 ArrayRef<TemplateArgument> Arguments) { 4394 ID.AddPointer(Deduced.getAsOpaquePtr()); 4395 ID.AddInteger((unsigned)Keyword); 4396 ID.AddBoolean(IsDependent); 4397 ID.AddPointer(CD); 4398 for (const TemplateArgument &Arg : Arguments) 4399 Arg.Profile(ID, Context); 4400 } 4401