1 //===--- SemaType.cpp - Semantic Analysis for Types -----------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements type-related semantic analysis. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "TypeLocBuilder.h" 14 #include "clang/AST/ASTConsumer.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTMutationListener.h" 17 #include "clang/AST/ASTStructuralEquivalence.h" 18 #include "clang/AST/CXXInheritance.h" 19 #include "clang/AST/Decl.h" 20 #include "clang/AST/DeclObjC.h" 21 #include "clang/AST/DeclTemplate.h" 22 #include "clang/AST/Expr.h" 23 #include "clang/AST/ExprObjC.h" 24 #include "clang/AST/LocInfoType.h" 25 #include "clang/AST/Type.h" 26 #include "clang/AST/TypeLoc.h" 27 #include "clang/AST/TypeLocVisitor.h" 28 #include "clang/Basic/LangOptions.h" 29 #include "clang/Basic/PartialDiagnostic.h" 30 #include "clang/Basic/SourceLocation.h" 31 #include "clang/Basic/Specifiers.h" 32 #include "clang/Basic/TargetInfo.h" 33 #include "clang/Lex/Preprocessor.h" 34 #include "clang/Sema/DeclSpec.h" 35 #include "clang/Sema/DelayedDiagnostic.h" 36 #include "clang/Sema/Lookup.h" 37 #include "clang/Sema/ParsedAttr.h" 38 #include "clang/Sema/ParsedTemplate.h" 39 #include "clang/Sema/ScopeInfo.h" 40 #include "clang/Sema/SemaCUDA.h" 41 #include "clang/Sema/SemaHLSL.h" 42 #include "clang/Sema/SemaInternal.h" 43 #include "clang/Sema/SemaObjC.h" 44 #include "clang/Sema/SemaOpenMP.h" 45 #include "clang/Sema/Template.h" 46 #include "clang/Sema/TemplateInstCallback.h" 47 #include "llvm/ADT/ArrayRef.h" 48 #include "llvm/ADT/STLForwardCompat.h" 49 #include "llvm/ADT/SmallPtrSet.h" 50 #include "llvm/ADT/SmallString.h" 51 #include "llvm/ADT/StringExtras.h" 52 #include "llvm/IR/DerivedTypes.h" 53 #include "llvm/Support/Casting.h" 54 #include "llvm/Support/ErrorHandling.h" 55 #include <bitset> 56 #include <optional> 57 58 using namespace clang; 59 60 enum TypeDiagSelector { 61 TDS_Function, 62 TDS_Pointer, 63 TDS_ObjCObjOrBlock 64 }; 65 66 /// isOmittedBlockReturnType - Return true if this declarator is missing a 67 /// return type because this is a omitted return type on a block literal. 68 static bool isOmittedBlockReturnType(const Declarator &D) { 69 if (D.getContext() != DeclaratorContext::BlockLiteral || 70 D.getDeclSpec().hasTypeSpecifier()) 71 return false; 72 73 if (D.getNumTypeObjects() == 0) 74 return true; // ^{ ... } 75 76 if (D.getNumTypeObjects() == 1 && 77 D.getTypeObject(0).Kind == DeclaratorChunk::Function) 78 return true; // ^(int X, float Y) { ... } 79 80 return false; 81 } 82 83 /// diagnoseBadTypeAttribute - Diagnoses a type attribute which 84 /// doesn't apply to the given type. 85 static void diagnoseBadTypeAttribute(Sema &S, const ParsedAttr &attr, 86 QualType type) { 87 TypeDiagSelector WhichType; 88 bool useExpansionLoc = true; 89 switch (attr.getKind()) { 90 case ParsedAttr::AT_ObjCGC: 91 WhichType = TDS_Pointer; 92 break; 93 case ParsedAttr::AT_ObjCOwnership: 94 WhichType = TDS_ObjCObjOrBlock; 95 break; 96 default: 97 // Assume everything else was a function attribute. 98 WhichType = TDS_Function; 99 useExpansionLoc = false; 100 break; 101 } 102 103 SourceLocation loc = attr.getLoc(); 104 StringRef name = attr.getAttrName()->getName(); 105 106 // The GC attributes are usually written with macros; special-case them. 107 IdentifierInfo *II = attr.isArgIdent(0) ? attr.getArgAsIdent(0)->Ident 108 : nullptr; 109 if (useExpansionLoc && loc.isMacroID() && II) { 110 if (II->isStr("strong")) { 111 if (S.findMacroSpelling(loc, "__strong")) name = "__strong"; 112 } else if (II->isStr("weak")) { 113 if (S.findMacroSpelling(loc, "__weak")) name = "__weak"; 114 } 115 } 116 117 S.Diag(loc, attr.isRegularKeywordAttribute() 118 ? diag::err_type_attribute_wrong_type 119 : diag::warn_type_attribute_wrong_type) 120 << name << WhichType << type; 121 } 122 123 // objc_gc applies to Objective-C pointers or, otherwise, to the 124 // smallest available pointer type (i.e. 'void*' in 'void**'). 125 #define OBJC_POINTER_TYPE_ATTRS_CASELIST \ 126 case ParsedAttr::AT_ObjCGC: \ 127 case ParsedAttr::AT_ObjCOwnership 128 129 // Calling convention attributes. 130 #define CALLING_CONV_ATTRS_CASELIST \ 131 case ParsedAttr::AT_CDecl: \ 132 case ParsedAttr::AT_FastCall: \ 133 case ParsedAttr::AT_StdCall: \ 134 case ParsedAttr::AT_ThisCall: \ 135 case ParsedAttr::AT_RegCall: \ 136 case ParsedAttr::AT_Pascal: \ 137 case ParsedAttr::AT_SwiftCall: \ 138 case ParsedAttr::AT_SwiftAsyncCall: \ 139 case ParsedAttr::AT_VectorCall: \ 140 case ParsedAttr::AT_AArch64VectorPcs: \ 141 case ParsedAttr::AT_AArch64SVEPcs: \ 142 case ParsedAttr::AT_AMDGPUKernelCall: \ 143 case ParsedAttr::AT_MSABI: \ 144 case ParsedAttr::AT_SysVABI: \ 145 case ParsedAttr::AT_Pcs: \ 146 case ParsedAttr::AT_IntelOclBicc: \ 147 case ParsedAttr::AT_PreserveMost: \ 148 case ParsedAttr::AT_PreserveAll: \ 149 case ParsedAttr::AT_M68kRTD: \ 150 case ParsedAttr::AT_PreserveNone: \ 151 case ParsedAttr::AT_RISCVVectorCC 152 153 // Function type attributes. 154 #define FUNCTION_TYPE_ATTRS_CASELIST \ 155 case ParsedAttr::AT_NSReturnsRetained: \ 156 case ParsedAttr::AT_NoReturn: \ 157 case ParsedAttr::AT_NonBlocking: \ 158 case ParsedAttr::AT_NonAllocating: \ 159 case ParsedAttr::AT_Blocking: \ 160 case ParsedAttr::AT_Allocating: \ 161 case ParsedAttr::AT_Regparm: \ 162 case ParsedAttr::AT_CmseNSCall: \ 163 case ParsedAttr::AT_ArmStreaming: \ 164 case ParsedAttr::AT_ArmStreamingCompatible: \ 165 case ParsedAttr::AT_ArmPreserves: \ 166 case ParsedAttr::AT_ArmIn: \ 167 case ParsedAttr::AT_ArmOut: \ 168 case ParsedAttr::AT_ArmInOut: \ 169 case ParsedAttr::AT_AnyX86NoCallerSavedRegisters: \ 170 case ParsedAttr::AT_AnyX86NoCfCheck: \ 171 CALLING_CONV_ATTRS_CASELIST 172 173 // Microsoft-specific type qualifiers. 174 #define MS_TYPE_ATTRS_CASELIST \ 175 case ParsedAttr::AT_Ptr32: \ 176 case ParsedAttr::AT_Ptr64: \ 177 case ParsedAttr::AT_SPtr: \ 178 case ParsedAttr::AT_UPtr 179 180 // Nullability qualifiers. 181 #define NULLABILITY_TYPE_ATTRS_CASELIST \ 182 case ParsedAttr::AT_TypeNonNull: \ 183 case ParsedAttr::AT_TypeNullable: \ 184 case ParsedAttr::AT_TypeNullableResult: \ 185 case ParsedAttr::AT_TypeNullUnspecified 186 187 namespace { 188 /// An object which stores processing state for the entire 189 /// GetTypeForDeclarator process. 190 class TypeProcessingState { 191 Sema &sema; 192 193 /// The declarator being processed. 194 Declarator &declarator; 195 196 /// The index of the declarator chunk we're currently processing. 197 /// May be the total number of valid chunks, indicating the 198 /// DeclSpec. 199 unsigned chunkIndex; 200 201 /// The original set of attributes on the DeclSpec. 202 SmallVector<ParsedAttr *, 2> savedAttrs; 203 204 /// A list of attributes to diagnose the uselessness of when the 205 /// processing is complete. 206 SmallVector<ParsedAttr *, 2> ignoredTypeAttrs; 207 208 /// Attributes corresponding to AttributedTypeLocs that we have not yet 209 /// populated. 210 // FIXME: The two-phase mechanism by which we construct Types and fill 211 // their TypeLocs makes it hard to correctly assign these. We keep the 212 // attributes in creation order as an attempt to make them line up 213 // properly. 214 using TypeAttrPair = std::pair<const AttributedType*, const Attr*>; 215 SmallVector<TypeAttrPair, 8> AttrsForTypes; 216 bool AttrsForTypesSorted = true; 217 218 /// MacroQualifiedTypes mapping to macro expansion locations that will be 219 /// stored in a MacroQualifiedTypeLoc. 220 llvm::DenseMap<const MacroQualifiedType *, SourceLocation> LocsForMacros; 221 222 /// Flag to indicate we parsed a noderef attribute. This is used for 223 /// validating that noderef was used on a pointer or array. 224 bool parsedNoDeref; 225 226 // Flag to indicate that we already parsed a HLSL parameter modifier 227 // attribute. This prevents double-mutating the type. 228 bool ParsedHLSLParamMod; 229 230 public: 231 TypeProcessingState(Sema &sema, Declarator &declarator) 232 : sema(sema), declarator(declarator), 233 chunkIndex(declarator.getNumTypeObjects()), parsedNoDeref(false), 234 ParsedHLSLParamMod(false) {} 235 236 Sema &getSema() const { 237 return sema; 238 } 239 240 Declarator &getDeclarator() const { 241 return declarator; 242 } 243 244 bool isProcessingDeclSpec() const { 245 return chunkIndex == declarator.getNumTypeObjects(); 246 } 247 248 unsigned getCurrentChunkIndex() const { 249 return chunkIndex; 250 } 251 252 void setCurrentChunkIndex(unsigned idx) { 253 assert(idx <= declarator.getNumTypeObjects()); 254 chunkIndex = idx; 255 } 256 257 ParsedAttributesView &getCurrentAttributes() const { 258 if (isProcessingDeclSpec()) 259 return getMutableDeclSpec().getAttributes(); 260 return declarator.getTypeObject(chunkIndex).getAttrs(); 261 } 262 263 /// Save the current set of attributes on the DeclSpec. 264 void saveDeclSpecAttrs() { 265 // Don't try to save them multiple times. 266 if (!savedAttrs.empty()) 267 return; 268 269 DeclSpec &spec = getMutableDeclSpec(); 270 llvm::append_range(savedAttrs, 271 llvm::make_pointer_range(spec.getAttributes())); 272 } 273 274 /// Record that we had nowhere to put the given type attribute. 275 /// We will diagnose such attributes later. 276 void addIgnoredTypeAttr(ParsedAttr &attr) { 277 ignoredTypeAttrs.push_back(&attr); 278 } 279 280 /// Diagnose all the ignored type attributes, given that the 281 /// declarator worked out to the given type. 282 void diagnoseIgnoredTypeAttrs(QualType type) const { 283 for (auto *Attr : ignoredTypeAttrs) 284 diagnoseBadTypeAttribute(getSema(), *Attr, type); 285 } 286 287 /// Get an attributed type for the given attribute, and remember the Attr 288 /// object so that we can attach it to the AttributedTypeLoc. 289 QualType getAttributedType(Attr *A, QualType ModifiedType, 290 QualType EquivType) { 291 QualType T = 292 sema.Context.getAttributedType(A, ModifiedType, EquivType); 293 AttrsForTypes.push_back({cast<AttributedType>(T.getTypePtr()), A}); 294 AttrsForTypesSorted = false; 295 return T; 296 } 297 298 /// Get a BTFTagAttributed type for the btf_type_tag attribute. 299 QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr, 300 QualType WrappedType) { 301 return sema.Context.getBTFTagAttributedType(BTFAttr, WrappedType); 302 } 303 304 /// Completely replace the \c auto in \p TypeWithAuto by 305 /// \p Replacement. Also replace \p TypeWithAuto in \c TypeAttrPair if 306 /// necessary. 307 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement) { 308 QualType T = sema.ReplaceAutoType(TypeWithAuto, Replacement); 309 if (auto *AttrTy = TypeWithAuto->getAs<AttributedType>()) { 310 // Attributed type still should be an attributed type after replacement. 311 auto *NewAttrTy = cast<AttributedType>(T.getTypePtr()); 312 for (TypeAttrPair &A : AttrsForTypes) { 313 if (A.first == AttrTy) 314 A.first = NewAttrTy; 315 } 316 AttrsForTypesSorted = false; 317 } 318 return T; 319 } 320 321 /// Extract and remove the Attr* for a given attributed type. 322 const Attr *takeAttrForAttributedType(const AttributedType *AT) { 323 if (!AttrsForTypesSorted) { 324 llvm::stable_sort(AttrsForTypes, llvm::less_first()); 325 AttrsForTypesSorted = true; 326 } 327 328 // FIXME: This is quadratic if we have lots of reuses of the same 329 // attributed type. 330 for (auto It = std::partition_point( 331 AttrsForTypes.begin(), AttrsForTypes.end(), 332 [=](const TypeAttrPair &A) { return A.first < AT; }); 333 It != AttrsForTypes.end() && It->first == AT; ++It) { 334 if (It->second) { 335 const Attr *Result = It->second; 336 It->second = nullptr; 337 return Result; 338 } 339 } 340 341 llvm_unreachable("no Attr* for AttributedType*"); 342 } 343 344 SourceLocation 345 getExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT) const { 346 auto FoundLoc = LocsForMacros.find(MQT); 347 assert(FoundLoc != LocsForMacros.end() && 348 "Unable to find macro expansion location for MacroQualifedType"); 349 return FoundLoc->second; 350 } 351 352 void setExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT, 353 SourceLocation Loc) { 354 LocsForMacros[MQT] = Loc; 355 } 356 357 void setParsedNoDeref(bool parsed) { parsedNoDeref = parsed; } 358 359 bool didParseNoDeref() const { return parsedNoDeref; } 360 361 void setParsedHLSLParamMod(bool Parsed) { ParsedHLSLParamMod = Parsed; } 362 363 bool didParseHLSLParamMod() const { return ParsedHLSLParamMod; } 364 365 ~TypeProcessingState() { 366 if (savedAttrs.empty()) 367 return; 368 369 getMutableDeclSpec().getAttributes().clearListOnly(); 370 for (ParsedAttr *AL : savedAttrs) 371 getMutableDeclSpec().getAttributes().addAtEnd(AL); 372 } 373 374 private: 375 DeclSpec &getMutableDeclSpec() const { 376 return const_cast<DeclSpec&>(declarator.getDeclSpec()); 377 } 378 }; 379 } // end anonymous namespace 380 381 static void moveAttrFromListToList(ParsedAttr &attr, 382 ParsedAttributesView &fromList, 383 ParsedAttributesView &toList) { 384 fromList.remove(&attr); 385 toList.addAtEnd(&attr); 386 } 387 388 /// The location of a type attribute. 389 enum TypeAttrLocation { 390 /// The attribute is in the decl-specifier-seq. 391 TAL_DeclSpec, 392 /// The attribute is part of a DeclaratorChunk. 393 TAL_DeclChunk, 394 /// The attribute is immediately after the declaration's name. 395 TAL_DeclName 396 }; 397 398 static void 399 processTypeAttrs(TypeProcessingState &state, QualType &type, 400 TypeAttrLocation TAL, const ParsedAttributesView &attrs, 401 CUDAFunctionTarget CFT = CUDAFunctionTarget::HostDevice); 402 403 static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr, 404 QualType &type, CUDAFunctionTarget CFT); 405 406 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state, 407 ParsedAttr &attr, QualType &type); 408 409 static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr, 410 QualType &type); 411 412 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state, 413 ParsedAttr &attr, QualType &type); 414 415 static bool handleObjCPointerTypeAttr(TypeProcessingState &state, 416 ParsedAttr &attr, QualType &type) { 417 if (attr.getKind() == ParsedAttr::AT_ObjCGC) 418 return handleObjCGCTypeAttr(state, attr, type); 419 assert(attr.getKind() == ParsedAttr::AT_ObjCOwnership); 420 return handleObjCOwnershipTypeAttr(state, attr, type); 421 } 422 423 /// Given the index of a declarator chunk, check whether that chunk 424 /// directly specifies the return type of a function and, if so, find 425 /// an appropriate place for it. 426 /// 427 /// \param i - a notional index which the search will start 428 /// immediately inside 429 /// 430 /// \param onlyBlockPointers Whether we should only look into block 431 /// pointer types (vs. all pointer types). 432 static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator, 433 unsigned i, 434 bool onlyBlockPointers) { 435 assert(i <= declarator.getNumTypeObjects()); 436 437 DeclaratorChunk *result = nullptr; 438 439 // First, look inwards past parens for a function declarator. 440 for (; i != 0; --i) { 441 DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1); 442 switch (fnChunk.Kind) { 443 case DeclaratorChunk::Paren: 444 continue; 445 446 // If we find anything except a function, bail out. 447 case DeclaratorChunk::Pointer: 448 case DeclaratorChunk::BlockPointer: 449 case DeclaratorChunk::Array: 450 case DeclaratorChunk::Reference: 451 case DeclaratorChunk::MemberPointer: 452 case DeclaratorChunk::Pipe: 453 return result; 454 455 // If we do find a function declarator, scan inwards from that, 456 // looking for a (block-)pointer declarator. 457 case DeclaratorChunk::Function: 458 for (--i; i != 0; --i) { 459 DeclaratorChunk &ptrChunk = declarator.getTypeObject(i-1); 460 switch (ptrChunk.Kind) { 461 case DeclaratorChunk::Paren: 462 case DeclaratorChunk::Array: 463 case DeclaratorChunk::Function: 464 case DeclaratorChunk::Reference: 465 case DeclaratorChunk::Pipe: 466 continue; 467 468 case DeclaratorChunk::MemberPointer: 469 case DeclaratorChunk::Pointer: 470 if (onlyBlockPointers) 471 continue; 472 473 [[fallthrough]]; 474 475 case DeclaratorChunk::BlockPointer: 476 result = &ptrChunk; 477 goto continue_outer; 478 } 479 llvm_unreachable("bad declarator chunk kind"); 480 } 481 482 // If we run out of declarators doing that, we're done. 483 return result; 484 } 485 llvm_unreachable("bad declarator chunk kind"); 486 487 // Okay, reconsider from our new point. 488 continue_outer: ; 489 } 490 491 // Ran out of chunks, bail out. 492 return result; 493 } 494 495 /// Given that an objc_gc attribute was written somewhere on a 496 /// declaration *other* than on the declarator itself (for which, use 497 /// distributeObjCPointerTypeAttrFromDeclarator), and given that it 498 /// didn't apply in whatever position it was written in, try to move 499 /// it to a more appropriate position. 500 static void distributeObjCPointerTypeAttr(TypeProcessingState &state, 501 ParsedAttr &attr, QualType type) { 502 Declarator &declarator = state.getDeclarator(); 503 504 // Move it to the outermost normal or block pointer declarator. 505 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { 506 DeclaratorChunk &chunk = declarator.getTypeObject(i-1); 507 switch (chunk.Kind) { 508 case DeclaratorChunk::Pointer: 509 case DeclaratorChunk::BlockPointer: { 510 // But don't move an ARC ownership attribute to the return type 511 // of a block. 512 DeclaratorChunk *destChunk = nullptr; 513 if (state.isProcessingDeclSpec() && 514 attr.getKind() == ParsedAttr::AT_ObjCOwnership) 515 destChunk = maybeMovePastReturnType(declarator, i - 1, 516 /*onlyBlockPointers=*/true); 517 if (!destChunk) destChunk = &chunk; 518 519 moveAttrFromListToList(attr, state.getCurrentAttributes(), 520 destChunk->getAttrs()); 521 return; 522 } 523 524 case DeclaratorChunk::Paren: 525 case DeclaratorChunk::Array: 526 continue; 527 528 // We may be starting at the return type of a block. 529 case DeclaratorChunk::Function: 530 if (state.isProcessingDeclSpec() && 531 attr.getKind() == ParsedAttr::AT_ObjCOwnership) { 532 if (DeclaratorChunk *dest = maybeMovePastReturnType( 533 declarator, i, 534 /*onlyBlockPointers=*/true)) { 535 moveAttrFromListToList(attr, state.getCurrentAttributes(), 536 dest->getAttrs()); 537 return; 538 } 539 } 540 goto error; 541 542 // Don't walk through these. 543 case DeclaratorChunk::Reference: 544 case DeclaratorChunk::MemberPointer: 545 case DeclaratorChunk::Pipe: 546 goto error; 547 } 548 } 549 error: 550 551 diagnoseBadTypeAttribute(state.getSema(), attr, type); 552 } 553 554 /// Distribute an objc_gc type attribute that was written on the 555 /// declarator. 556 static void distributeObjCPointerTypeAttrFromDeclarator( 557 TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType) { 558 Declarator &declarator = state.getDeclarator(); 559 560 // objc_gc goes on the innermost pointer to something that's not a 561 // pointer. 562 unsigned innermost = -1U; 563 bool considerDeclSpec = true; 564 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { 565 DeclaratorChunk &chunk = declarator.getTypeObject(i); 566 switch (chunk.Kind) { 567 case DeclaratorChunk::Pointer: 568 case DeclaratorChunk::BlockPointer: 569 innermost = i; 570 continue; 571 572 case DeclaratorChunk::Reference: 573 case DeclaratorChunk::MemberPointer: 574 case DeclaratorChunk::Paren: 575 case DeclaratorChunk::Array: 576 case DeclaratorChunk::Pipe: 577 continue; 578 579 case DeclaratorChunk::Function: 580 considerDeclSpec = false; 581 goto done; 582 } 583 } 584 done: 585 586 // That might actually be the decl spec if we weren't blocked by 587 // anything in the declarator. 588 if (considerDeclSpec) { 589 if (handleObjCPointerTypeAttr(state, attr, declSpecType)) { 590 // Splice the attribute into the decl spec. Prevents the 591 // attribute from being applied multiple times and gives 592 // the source-location-filler something to work with. 593 state.saveDeclSpecAttrs(); 594 declarator.getMutableDeclSpec().getAttributes().takeOneFrom( 595 declarator.getAttributes(), &attr); 596 return; 597 } 598 } 599 600 // Otherwise, if we found an appropriate chunk, splice the attribute 601 // into it. 602 if (innermost != -1U) { 603 moveAttrFromListToList(attr, declarator.getAttributes(), 604 declarator.getTypeObject(innermost).getAttrs()); 605 return; 606 } 607 608 // Otherwise, diagnose when we're done building the type. 609 declarator.getAttributes().remove(&attr); 610 state.addIgnoredTypeAttr(attr); 611 } 612 613 /// A function type attribute was written somewhere in a declaration 614 /// *other* than on the declarator itself or in the decl spec. Given 615 /// that it didn't apply in whatever position it was written in, try 616 /// to move it to a more appropriate position. 617 static void distributeFunctionTypeAttr(TypeProcessingState &state, 618 ParsedAttr &attr, QualType type) { 619 Declarator &declarator = state.getDeclarator(); 620 621 // Try to push the attribute from the return type of a function to 622 // the function itself. 623 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { 624 DeclaratorChunk &chunk = declarator.getTypeObject(i-1); 625 switch (chunk.Kind) { 626 case DeclaratorChunk::Function: 627 moveAttrFromListToList(attr, state.getCurrentAttributes(), 628 chunk.getAttrs()); 629 return; 630 631 case DeclaratorChunk::Paren: 632 case DeclaratorChunk::Pointer: 633 case DeclaratorChunk::BlockPointer: 634 case DeclaratorChunk::Array: 635 case DeclaratorChunk::Reference: 636 case DeclaratorChunk::MemberPointer: 637 case DeclaratorChunk::Pipe: 638 continue; 639 } 640 } 641 642 diagnoseBadTypeAttribute(state.getSema(), attr, type); 643 } 644 645 /// Try to distribute a function type attribute to the innermost 646 /// function chunk or type. Returns true if the attribute was 647 /// distributed, false if no location was found. 648 static bool distributeFunctionTypeAttrToInnermost( 649 TypeProcessingState &state, ParsedAttr &attr, 650 ParsedAttributesView &attrList, QualType &declSpecType, 651 CUDAFunctionTarget CFT) { 652 Declarator &declarator = state.getDeclarator(); 653 654 // Put it on the innermost function chunk, if there is one. 655 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { 656 DeclaratorChunk &chunk = declarator.getTypeObject(i); 657 if (chunk.Kind != DeclaratorChunk::Function) continue; 658 659 moveAttrFromListToList(attr, attrList, chunk.getAttrs()); 660 return true; 661 } 662 663 return handleFunctionTypeAttr(state, attr, declSpecType, CFT); 664 } 665 666 /// A function type attribute was written in the decl spec. Try to 667 /// apply it somewhere. 668 static void distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state, 669 ParsedAttr &attr, 670 QualType &declSpecType, 671 CUDAFunctionTarget CFT) { 672 state.saveDeclSpecAttrs(); 673 674 // Try to distribute to the innermost. 675 if (distributeFunctionTypeAttrToInnermost( 676 state, attr, state.getCurrentAttributes(), declSpecType, CFT)) 677 return; 678 679 // If that failed, diagnose the bad attribute when the declarator is 680 // fully built. 681 state.addIgnoredTypeAttr(attr); 682 } 683 684 /// A function type attribute was written on the declarator or declaration. 685 /// Try to apply it somewhere. 686 /// `Attrs` is the attribute list containing the declaration (either of the 687 /// declarator or the declaration). 688 static void distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state, 689 ParsedAttr &attr, 690 QualType &declSpecType, 691 CUDAFunctionTarget CFT) { 692 Declarator &declarator = state.getDeclarator(); 693 694 // Try to distribute to the innermost. 695 if (distributeFunctionTypeAttrToInnermost( 696 state, attr, declarator.getAttributes(), declSpecType, CFT)) 697 return; 698 699 // If that failed, diagnose the bad attribute when the declarator is 700 // fully built. 701 declarator.getAttributes().remove(&attr); 702 state.addIgnoredTypeAttr(attr); 703 } 704 705 /// Given that there are attributes written on the declarator or declaration 706 /// itself, try to distribute any type attributes to the appropriate 707 /// declarator chunk. 708 /// 709 /// These are attributes like the following: 710 /// int f ATTR; 711 /// int (f ATTR)(); 712 /// but not necessarily this: 713 /// int f() ATTR; 714 /// 715 /// `Attrs` is the attribute list containing the declaration (either of the 716 /// declarator or the declaration). 717 static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state, 718 QualType &declSpecType, 719 CUDAFunctionTarget CFT) { 720 // The called functions in this loop actually remove things from the current 721 // list, so iterating over the existing list isn't possible. Instead, make a 722 // non-owning copy and iterate over that. 723 ParsedAttributesView AttrsCopy{state.getDeclarator().getAttributes()}; 724 for (ParsedAttr &attr : AttrsCopy) { 725 // Do not distribute [[]] attributes. They have strict rules for what 726 // they appertain to. 727 if (attr.isStandardAttributeSyntax() || attr.isRegularKeywordAttribute()) 728 continue; 729 730 switch (attr.getKind()) { 731 OBJC_POINTER_TYPE_ATTRS_CASELIST: 732 distributeObjCPointerTypeAttrFromDeclarator(state, attr, declSpecType); 733 break; 734 735 FUNCTION_TYPE_ATTRS_CASELIST: 736 distributeFunctionTypeAttrFromDeclarator(state, attr, declSpecType, CFT); 737 break; 738 739 MS_TYPE_ATTRS_CASELIST: 740 // Microsoft type attributes cannot go after the declarator-id. 741 continue; 742 743 NULLABILITY_TYPE_ATTRS_CASELIST: 744 // Nullability specifiers cannot go after the declarator-id. 745 746 // Objective-C __kindof does not get distributed. 747 case ParsedAttr::AT_ObjCKindOf: 748 continue; 749 750 default: 751 break; 752 } 753 } 754 } 755 756 /// Add a synthetic '()' to a block-literal declarator if it is 757 /// required, given the return type. 758 static void maybeSynthesizeBlockSignature(TypeProcessingState &state, 759 QualType declSpecType) { 760 Declarator &declarator = state.getDeclarator(); 761 762 // First, check whether the declarator would produce a function, 763 // i.e. whether the innermost semantic chunk is a function. 764 if (declarator.isFunctionDeclarator()) { 765 // If so, make that declarator a prototyped declarator. 766 declarator.getFunctionTypeInfo().hasPrototype = true; 767 return; 768 } 769 770 // If there are any type objects, the type as written won't name a 771 // function, regardless of the decl spec type. This is because a 772 // block signature declarator is always an abstract-declarator, and 773 // abstract-declarators can't just be parentheses chunks. Therefore 774 // we need to build a function chunk unless there are no type 775 // objects and the decl spec type is a function. 776 if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType()) 777 return; 778 779 // Note that there *are* cases with invalid declarators where 780 // declarators consist solely of parentheses. In general, these 781 // occur only in failed efforts to make function declarators, so 782 // faking up the function chunk is still the right thing to do. 783 784 // Otherwise, we need to fake up a function declarator. 785 SourceLocation loc = declarator.getBeginLoc(); 786 787 // ...and *prepend* it to the declarator. 788 SourceLocation NoLoc; 789 declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction( 790 /*HasProto=*/true, 791 /*IsAmbiguous=*/false, 792 /*LParenLoc=*/NoLoc, 793 /*ArgInfo=*/nullptr, 794 /*NumParams=*/0, 795 /*EllipsisLoc=*/NoLoc, 796 /*RParenLoc=*/NoLoc, 797 /*RefQualifierIsLvalueRef=*/true, 798 /*RefQualifierLoc=*/NoLoc, 799 /*MutableLoc=*/NoLoc, EST_None, 800 /*ESpecRange=*/SourceRange(), 801 /*Exceptions=*/nullptr, 802 /*ExceptionRanges=*/nullptr, 803 /*NumExceptions=*/0, 804 /*NoexceptExpr=*/nullptr, 805 /*ExceptionSpecTokens=*/nullptr, 806 /*DeclsInPrototype=*/{}, loc, loc, declarator)); 807 808 // For consistency, make sure the state still has us as processing 809 // the decl spec. 810 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1); 811 state.setCurrentChunkIndex(declarator.getNumTypeObjects()); 812 } 813 814 static void diagnoseAndRemoveTypeQualifiers(Sema &S, const DeclSpec &DS, 815 unsigned &TypeQuals, 816 QualType TypeSoFar, 817 unsigned RemoveTQs, 818 unsigned DiagID) { 819 // If this occurs outside a template instantiation, warn the user about 820 // it; they probably didn't mean to specify a redundant qualifier. 821 typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc; 822 for (QualLoc Qual : {QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()), 823 QualLoc(DeclSpec::TQ_restrict, DS.getRestrictSpecLoc()), 824 QualLoc(DeclSpec::TQ_volatile, DS.getVolatileSpecLoc()), 825 QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) { 826 if (!(RemoveTQs & Qual.first)) 827 continue; 828 829 if (!S.inTemplateInstantiation()) { 830 if (TypeQuals & Qual.first) 831 S.Diag(Qual.second, DiagID) 832 << DeclSpec::getSpecifierName(Qual.first) << TypeSoFar 833 << FixItHint::CreateRemoval(Qual.second); 834 } 835 836 TypeQuals &= ~Qual.first; 837 } 838 } 839 840 /// Return true if this is omitted block return type. Also check type 841 /// attributes and type qualifiers when returning true. 842 static bool checkOmittedBlockReturnType(Sema &S, Declarator &declarator, 843 QualType Result) { 844 if (!isOmittedBlockReturnType(declarator)) 845 return false; 846 847 // Warn if we see type attributes for omitted return type on a block literal. 848 SmallVector<ParsedAttr *, 2> ToBeRemoved; 849 for (ParsedAttr &AL : declarator.getMutableDeclSpec().getAttributes()) { 850 if (AL.isInvalid() || !AL.isTypeAttr()) 851 continue; 852 S.Diag(AL.getLoc(), 853 diag::warn_block_literal_attributes_on_omitted_return_type) 854 << AL; 855 ToBeRemoved.push_back(&AL); 856 } 857 // Remove bad attributes from the list. 858 for (ParsedAttr *AL : ToBeRemoved) 859 declarator.getMutableDeclSpec().getAttributes().remove(AL); 860 861 // Warn if we see type qualifiers for omitted return type on a block literal. 862 const DeclSpec &DS = declarator.getDeclSpec(); 863 unsigned TypeQuals = DS.getTypeQualifiers(); 864 diagnoseAndRemoveTypeQualifiers(S, DS, TypeQuals, Result, (unsigned)-1, 865 diag::warn_block_literal_qualifiers_on_omitted_return_type); 866 declarator.getMutableDeclSpec().ClearTypeQualifiers(); 867 868 return true; 869 } 870 871 static OpenCLAccessAttr::Spelling 872 getImageAccess(const ParsedAttributesView &Attrs) { 873 for (const ParsedAttr &AL : Attrs) 874 if (AL.getKind() == ParsedAttr::AT_OpenCLAccess) 875 return static_cast<OpenCLAccessAttr::Spelling>(AL.getSemanticSpelling()); 876 return OpenCLAccessAttr::Keyword_read_only; 877 } 878 879 static UnaryTransformType::UTTKind 880 TSTToUnaryTransformType(DeclSpec::TST SwitchTST) { 881 switch (SwitchTST) { 882 #define TRANSFORM_TYPE_TRAIT_DEF(Enum, Trait) \ 883 case TST_##Trait: \ 884 return UnaryTransformType::Enum; 885 #include "clang/Basic/TransformTypeTraits.def" 886 default: 887 llvm_unreachable("attempted to parse a non-unary transform builtin"); 888 } 889 } 890 891 /// Convert the specified declspec to the appropriate type 892 /// object. 893 /// \param state Specifies the declarator containing the declaration specifier 894 /// to be converted, along with other associated processing state. 895 /// \returns The type described by the declaration specifiers. This function 896 /// never returns null. 897 static QualType ConvertDeclSpecToType(TypeProcessingState &state) { 898 // FIXME: Should move the logic from DeclSpec::Finish to here for validity 899 // checking. 900 901 Sema &S = state.getSema(); 902 Declarator &declarator = state.getDeclarator(); 903 DeclSpec &DS = declarator.getMutableDeclSpec(); 904 SourceLocation DeclLoc = declarator.getIdentifierLoc(); 905 if (DeclLoc.isInvalid()) 906 DeclLoc = DS.getBeginLoc(); 907 908 ASTContext &Context = S.Context; 909 910 QualType Result; 911 switch (DS.getTypeSpecType()) { 912 case DeclSpec::TST_void: 913 Result = Context.VoidTy; 914 break; 915 case DeclSpec::TST_char: 916 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified) 917 Result = Context.CharTy; 918 else if (DS.getTypeSpecSign() == TypeSpecifierSign::Signed) 919 Result = Context.SignedCharTy; 920 else { 921 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned && 922 "Unknown TSS value"); 923 Result = Context.UnsignedCharTy; 924 } 925 break; 926 case DeclSpec::TST_wchar: 927 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified) 928 Result = Context.WCharTy; 929 else if (DS.getTypeSpecSign() == TypeSpecifierSign::Signed) { 930 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec) 931 << DS.getSpecifierName(DS.getTypeSpecType(), 932 Context.getPrintingPolicy()); 933 Result = Context.getSignedWCharType(); 934 } else { 935 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned && 936 "Unknown TSS value"); 937 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec) 938 << DS.getSpecifierName(DS.getTypeSpecType(), 939 Context.getPrintingPolicy()); 940 Result = Context.getUnsignedWCharType(); 941 } 942 break; 943 case DeclSpec::TST_char8: 944 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && 945 "Unknown TSS value"); 946 Result = Context.Char8Ty; 947 break; 948 case DeclSpec::TST_char16: 949 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && 950 "Unknown TSS value"); 951 Result = Context.Char16Ty; 952 break; 953 case DeclSpec::TST_char32: 954 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && 955 "Unknown TSS value"); 956 Result = Context.Char32Ty; 957 break; 958 case DeclSpec::TST_unspecified: 959 // If this is a missing declspec in a block literal return context, then it 960 // is inferred from the return statements inside the block. 961 // The declspec is always missing in a lambda expr context; it is either 962 // specified with a trailing return type or inferred. 963 if (S.getLangOpts().CPlusPlus14 && 964 declarator.getContext() == DeclaratorContext::LambdaExpr) { 965 // In C++1y, a lambda's implicit return type is 'auto'. 966 Result = Context.getAutoDeductType(); 967 break; 968 } else if (declarator.getContext() == DeclaratorContext::LambdaExpr || 969 checkOmittedBlockReturnType(S, declarator, 970 Context.DependentTy)) { 971 Result = Context.DependentTy; 972 break; 973 } 974 975 // Unspecified typespec defaults to int in C90. However, the C90 grammar 976 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier, 977 // type-qualifier, or storage-class-specifier. If not, emit an extwarn. 978 // Note that the one exception to this is function definitions, which are 979 // allowed to be completely missing a declspec. This is handled in the 980 // parser already though by it pretending to have seen an 'int' in this 981 // case. 982 if (S.getLangOpts().isImplicitIntRequired()) { 983 S.Diag(DeclLoc, diag::warn_missing_type_specifier) 984 << DS.getSourceRange() 985 << FixItHint::CreateInsertion(DS.getBeginLoc(), "int"); 986 } else if (!DS.hasTypeSpecifier()) { 987 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says: 988 // "At least one type specifier shall be given in the declaration 989 // specifiers in each declaration, and in the specifier-qualifier list in 990 // each struct declaration and type name." 991 if (!S.getLangOpts().isImplicitIntAllowed() && !DS.isTypeSpecPipe()) { 992 S.Diag(DeclLoc, diag::err_missing_type_specifier) 993 << DS.getSourceRange(); 994 995 // When this occurs, often something is very broken with the value 996 // being declared, poison it as invalid so we don't get chains of 997 // errors. 998 declarator.setInvalidType(true); 999 } else if (S.getLangOpts().getOpenCLCompatibleVersion() >= 200 && 1000 DS.isTypeSpecPipe()) { 1001 S.Diag(DeclLoc, diag::err_missing_actual_pipe_type) 1002 << DS.getSourceRange(); 1003 declarator.setInvalidType(true); 1004 } else { 1005 assert(S.getLangOpts().isImplicitIntAllowed() && 1006 "implicit int is disabled?"); 1007 S.Diag(DeclLoc, diag::ext_missing_type_specifier) 1008 << DS.getSourceRange() 1009 << FixItHint::CreateInsertion(DS.getBeginLoc(), "int"); 1010 } 1011 } 1012 1013 [[fallthrough]]; 1014 case DeclSpec::TST_int: { 1015 if (DS.getTypeSpecSign() != TypeSpecifierSign::Unsigned) { 1016 switch (DS.getTypeSpecWidth()) { 1017 case TypeSpecifierWidth::Unspecified: 1018 Result = Context.IntTy; 1019 break; 1020 case TypeSpecifierWidth::Short: 1021 Result = Context.ShortTy; 1022 break; 1023 case TypeSpecifierWidth::Long: 1024 Result = Context.LongTy; 1025 break; 1026 case TypeSpecifierWidth::LongLong: 1027 Result = Context.LongLongTy; 1028 1029 // 'long long' is a C99 or C++11 feature. 1030 if (!S.getLangOpts().C99) { 1031 if (S.getLangOpts().CPlusPlus) 1032 S.Diag(DS.getTypeSpecWidthLoc(), 1033 S.getLangOpts().CPlusPlus11 ? 1034 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 1035 else 1036 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong); 1037 } 1038 break; 1039 } 1040 } else { 1041 switch (DS.getTypeSpecWidth()) { 1042 case TypeSpecifierWidth::Unspecified: 1043 Result = Context.UnsignedIntTy; 1044 break; 1045 case TypeSpecifierWidth::Short: 1046 Result = Context.UnsignedShortTy; 1047 break; 1048 case TypeSpecifierWidth::Long: 1049 Result = Context.UnsignedLongTy; 1050 break; 1051 case TypeSpecifierWidth::LongLong: 1052 Result = Context.UnsignedLongLongTy; 1053 1054 // 'long long' is a C99 or C++11 feature. 1055 if (!S.getLangOpts().C99) { 1056 if (S.getLangOpts().CPlusPlus) 1057 S.Diag(DS.getTypeSpecWidthLoc(), 1058 S.getLangOpts().CPlusPlus11 ? 1059 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 1060 else 1061 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong); 1062 } 1063 break; 1064 } 1065 } 1066 break; 1067 } 1068 case DeclSpec::TST_bitint: { 1069 if (!S.Context.getTargetInfo().hasBitIntType()) 1070 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "_BitInt"; 1071 Result = 1072 S.BuildBitIntType(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned, 1073 DS.getRepAsExpr(), DS.getBeginLoc()); 1074 if (Result.isNull()) { 1075 Result = Context.IntTy; 1076 declarator.setInvalidType(true); 1077 } 1078 break; 1079 } 1080 case DeclSpec::TST_accum: { 1081 switch (DS.getTypeSpecWidth()) { 1082 case TypeSpecifierWidth::Short: 1083 Result = Context.ShortAccumTy; 1084 break; 1085 case TypeSpecifierWidth::Unspecified: 1086 Result = Context.AccumTy; 1087 break; 1088 case TypeSpecifierWidth::Long: 1089 Result = Context.LongAccumTy; 1090 break; 1091 case TypeSpecifierWidth::LongLong: 1092 llvm_unreachable("Unable to specify long long as _Accum width"); 1093 } 1094 1095 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned) 1096 Result = Context.getCorrespondingUnsignedType(Result); 1097 1098 if (DS.isTypeSpecSat()) 1099 Result = Context.getCorrespondingSaturatedType(Result); 1100 1101 break; 1102 } 1103 case DeclSpec::TST_fract: { 1104 switch (DS.getTypeSpecWidth()) { 1105 case TypeSpecifierWidth::Short: 1106 Result = Context.ShortFractTy; 1107 break; 1108 case TypeSpecifierWidth::Unspecified: 1109 Result = Context.FractTy; 1110 break; 1111 case TypeSpecifierWidth::Long: 1112 Result = Context.LongFractTy; 1113 break; 1114 case TypeSpecifierWidth::LongLong: 1115 llvm_unreachable("Unable to specify long long as _Fract width"); 1116 } 1117 1118 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned) 1119 Result = Context.getCorrespondingUnsignedType(Result); 1120 1121 if (DS.isTypeSpecSat()) 1122 Result = Context.getCorrespondingSaturatedType(Result); 1123 1124 break; 1125 } 1126 case DeclSpec::TST_int128: 1127 if (!S.Context.getTargetInfo().hasInt128Type() && 1128 !(S.getLangOpts().SYCLIsDevice || S.getLangOpts().CUDAIsDevice || 1129 (S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice))) 1130 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) 1131 << "__int128"; 1132 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned) 1133 Result = Context.UnsignedInt128Ty; 1134 else 1135 Result = Context.Int128Ty; 1136 break; 1137 case DeclSpec::TST_float16: 1138 // CUDA host and device may have different _Float16 support, therefore 1139 // do not diagnose _Float16 usage to avoid false alarm. 1140 // ToDo: more precise diagnostics for CUDA. 1141 if (!S.Context.getTargetInfo().hasFloat16Type() && !S.getLangOpts().CUDA && 1142 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice)) 1143 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) 1144 << "_Float16"; 1145 Result = Context.Float16Ty; 1146 break; 1147 case DeclSpec::TST_half: Result = Context.HalfTy; break; 1148 case DeclSpec::TST_BFloat16: 1149 if (!S.Context.getTargetInfo().hasBFloat16Type() && 1150 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice) && 1151 !S.getLangOpts().SYCLIsDevice) 1152 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "__bf16"; 1153 Result = Context.BFloat16Ty; 1154 break; 1155 case DeclSpec::TST_float: Result = Context.FloatTy; break; 1156 case DeclSpec::TST_double: 1157 if (DS.getTypeSpecWidth() == TypeSpecifierWidth::Long) 1158 Result = Context.LongDoubleTy; 1159 else 1160 Result = Context.DoubleTy; 1161 if (S.getLangOpts().OpenCL) { 1162 if (!S.getOpenCLOptions().isSupported("cl_khr_fp64", S.getLangOpts())) 1163 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension) 1164 << 0 << Result 1165 << (S.getLangOpts().getOpenCLCompatibleVersion() == 300 1166 ? "cl_khr_fp64 and __opencl_c_fp64" 1167 : "cl_khr_fp64"); 1168 else if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp64", S.getLangOpts())) 1169 S.Diag(DS.getTypeSpecTypeLoc(), diag::ext_opencl_double_without_pragma); 1170 } 1171 break; 1172 case DeclSpec::TST_float128: 1173 if (!S.Context.getTargetInfo().hasFloat128Type() && 1174 !S.getLangOpts().SYCLIsDevice && !S.getLangOpts().CUDAIsDevice && 1175 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice)) 1176 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) 1177 << "__float128"; 1178 Result = Context.Float128Ty; 1179 break; 1180 case DeclSpec::TST_ibm128: 1181 if (!S.Context.getTargetInfo().hasIbm128Type() && 1182 !S.getLangOpts().SYCLIsDevice && 1183 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice)) 1184 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "__ibm128"; 1185 Result = Context.Ibm128Ty; 1186 break; 1187 case DeclSpec::TST_bool: 1188 Result = Context.BoolTy; // _Bool or bool 1189 break; 1190 case DeclSpec::TST_decimal32: // _Decimal32 1191 case DeclSpec::TST_decimal64: // _Decimal64 1192 case DeclSpec::TST_decimal128: // _Decimal128 1193 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported); 1194 Result = Context.IntTy; 1195 declarator.setInvalidType(true); 1196 break; 1197 case DeclSpec::TST_class: 1198 case DeclSpec::TST_enum: 1199 case DeclSpec::TST_union: 1200 case DeclSpec::TST_struct: 1201 case DeclSpec::TST_interface: { 1202 TagDecl *D = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl()); 1203 if (!D) { 1204 // This can happen in C++ with ambiguous lookups. 1205 Result = Context.IntTy; 1206 declarator.setInvalidType(true); 1207 break; 1208 } 1209 1210 // If the type is deprecated or unavailable, diagnose it. 1211 S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc()); 1212 1213 assert(DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified && 1214 DS.getTypeSpecComplex() == 0 && 1215 DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && 1216 "No qualifiers on tag names!"); 1217 1218 // TypeQuals handled by caller. 1219 Result = Context.getTypeDeclType(D); 1220 1221 // In both C and C++, make an ElaboratedType. 1222 ElaboratedTypeKeyword Keyword 1223 = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType()); 1224 Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result, 1225 DS.isTypeSpecOwned() ? D : nullptr); 1226 break; 1227 } 1228 case DeclSpec::TST_typename: { 1229 assert(DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified && 1230 DS.getTypeSpecComplex() == 0 && 1231 DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && 1232 "Can't handle qualifiers on typedef names yet!"); 1233 Result = S.GetTypeFromParser(DS.getRepAsType()); 1234 if (Result.isNull()) { 1235 declarator.setInvalidType(true); 1236 } 1237 1238 // TypeQuals handled by caller. 1239 break; 1240 } 1241 case DeclSpec::TST_typeof_unqualType: 1242 case DeclSpec::TST_typeofType: 1243 // FIXME: Preserve type source info. 1244 Result = S.GetTypeFromParser(DS.getRepAsType()); 1245 assert(!Result.isNull() && "Didn't get a type for typeof?"); 1246 if (!Result->isDependentType()) 1247 if (const TagType *TT = Result->getAs<TagType>()) 1248 S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc()); 1249 // TypeQuals handled by caller. 1250 Result = Context.getTypeOfType( 1251 Result, DS.getTypeSpecType() == DeclSpec::TST_typeof_unqualType 1252 ? TypeOfKind::Unqualified 1253 : TypeOfKind::Qualified); 1254 break; 1255 case DeclSpec::TST_typeof_unqualExpr: 1256 case DeclSpec::TST_typeofExpr: { 1257 Expr *E = DS.getRepAsExpr(); 1258 assert(E && "Didn't get an expression for typeof?"); 1259 // TypeQuals handled by caller. 1260 Result = S.BuildTypeofExprType(E, DS.getTypeSpecType() == 1261 DeclSpec::TST_typeof_unqualExpr 1262 ? TypeOfKind::Unqualified 1263 : TypeOfKind::Qualified); 1264 if (Result.isNull()) { 1265 Result = Context.IntTy; 1266 declarator.setInvalidType(true); 1267 } 1268 break; 1269 } 1270 case DeclSpec::TST_decltype: { 1271 Expr *E = DS.getRepAsExpr(); 1272 assert(E && "Didn't get an expression for decltype?"); 1273 // TypeQuals handled by caller. 1274 Result = S.BuildDecltypeType(E); 1275 if (Result.isNull()) { 1276 Result = Context.IntTy; 1277 declarator.setInvalidType(true); 1278 } 1279 break; 1280 } 1281 case DeclSpec::TST_typename_pack_indexing: { 1282 Expr *E = DS.getPackIndexingExpr(); 1283 assert(E && "Didn't get an expression for pack indexing"); 1284 QualType Pattern = S.GetTypeFromParser(DS.getRepAsType()); 1285 Result = S.BuildPackIndexingType(Pattern, E, DS.getBeginLoc(), 1286 DS.getEllipsisLoc()); 1287 if (Result.isNull()) { 1288 declarator.setInvalidType(true); 1289 Result = Context.IntTy; 1290 } 1291 break; 1292 } 1293 1294 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait: 1295 #include "clang/Basic/TransformTypeTraits.def" 1296 Result = S.GetTypeFromParser(DS.getRepAsType()); 1297 assert(!Result.isNull() && "Didn't get a type for the transformation?"); 1298 Result = S.BuildUnaryTransformType( 1299 Result, TSTToUnaryTransformType(DS.getTypeSpecType()), 1300 DS.getTypeSpecTypeLoc()); 1301 if (Result.isNull()) { 1302 Result = Context.IntTy; 1303 declarator.setInvalidType(true); 1304 } 1305 break; 1306 1307 case DeclSpec::TST_auto: 1308 case DeclSpec::TST_decltype_auto: { 1309 auto AutoKW = DS.getTypeSpecType() == DeclSpec::TST_decltype_auto 1310 ? AutoTypeKeyword::DecltypeAuto 1311 : AutoTypeKeyword::Auto; 1312 1313 ConceptDecl *TypeConstraintConcept = nullptr; 1314 llvm::SmallVector<TemplateArgument, 8> TemplateArgs; 1315 if (DS.isConstrainedAuto()) { 1316 if (TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId()) { 1317 TypeConstraintConcept = 1318 cast<ConceptDecl>(TemplateId->Template.get().getAsTemplateDecl()); 1319 TemplateArgumentListInfo TemplateArgsInfo; 1320 TemplateArgsInfo.setLAngleLoc(TemplateId->LAngleLoc); 1321 TemplateArgsInfo.setRAngleLoc(TemplateId->RAngleLoc); 1322 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 1323 TemplateId->NumArgs); 1324 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo); 1325 for (const auto &ArgLoc : TemplateArgsInfo.arguments()) 1326 TemplateArgs.push_back(ArgLoc.getArgument()); 1327 } else { 1328 declarator.setInvalidType(true); 1329 } 1330 } 1331 Result = S.Context.getAutoType(QualType(), AutoKW, 1332 /*IsDependent*/ false, /*IsPack=*/false, 1333 TypeConstraintConcept, TemplateArgs); 1334 break; 1335 } 1336 1337 case DeclSpec::TST_auto_type: 1338 Result = Context.getAutoType(QualType(), AutoTypeKeyword::GNUAutoType, false); 1339 break; 1340 1341 case DeclSpec::TST_unknown_anytype: 1342 Result = Context.UnknownAnyTy; 1343 break; 1344 1345 case DeclSpec::TST_atomic: 1346 Result = S.GetTypeFromParser(DS.getRepAsType()); 1347 assert(!Result.isNull() && "Didn't get a type for _Atomic?"); 1348 Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc()); 1349 if (Result.isNull()) { 1350 Result = Context.IntTy; 1351 declarator.setInvalidType(true); 1352 } 1353 break; 1354 1355 #define GENERIC_IMAGE_TYPE(ImgType, Id) \ 1356 case DeclSpec::TST_##ImgType##_t: \ 1357 switch (getImageAccess(DS.getAttributes())) { \ 1358 case OpenCLAccessAttr::Keyword_write_only: \ 1359 Result = Context.Id##WOTy; \ 1360 break; \ 1361 case OpenCLAccessAttr::Keyword_read_write: \ 1362 Result = Context.Id##RWTy; \ 1363 break; \ 1364 case OpenCLAccessAttr::Keyword_read_only: \ 1365 Result = Context.Id##ROTy; \ 1366 break; \ 1367 case OpenCLAccessAttr::SpellingNotCalculated: \ 1368 llvm_unreachable("Spelling not yet calculated"); \ 1369 } \ 1370 break; 1371 #include "clang/Basic/OpenCLImageTypes.def" 1372 1373 #define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \ 1374 case DeclSpec::TST_##Name: \ 1375 Result = Context.SingletonId; \ 1376 break; 1377 #include "clang/Basic/HLSLIntangibleTypes.def" 1378 1379 case DeclSpec::TST_error: 1380 Result = Context.IntTy; 1381 declarator.setInvalidType(true); 1382 break; 1383 } 1384 1385 // FIXME: we want resulting declarations to be marked invalid, but claiming 1386 // the type is invalid is too strong - e.g. it causes ActOnTypeName to return 1387 // a null type. 1388 if (Result->containsErrors()) 1389 declarator.setInvalidType(); 1390 1391 if (S.getLangOpts().OpenCL) { 1392 const auto &OpenCLOptions = S.getOpenCLOptions(); 1393 bool IsOpenCLC30Compatible = 1394 S.getLangOpts().getOpenCLCompatibleVersion() == 300; 1395 // OpenCL C v3.0 s6.3.3 - OpenCL image types require __opencl_c_images 1396 // support. 1397 // OpenCL C v3.0 s6.2.1 - OpenCL 3d image write types requires support 1398 // for OpenCL C 2.0, or OpenCL C 3.0 or newer and the 1399 // __opencl_c_3d_image_writes feature. OpenCL C v3.0 API s4.2 - For devices 1400 // that support OpenCL 3.0, cl_khr_3d_image_writes must be returned when and 1401 // only when the optional feature is supported 1402 if ((Result->isImageType() || Result->isSamplerT()) && 1403 (IsOpenCLC30Compatible && 1404 !OpenCLOptions.isSupported("__opencl_c_images", S.getLangOpts()))) { 1405 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension) 1406 << 0 << Result << "__opencl_c_images"; 1407 declarator.setInvalidType(); 1408 } else if (Result->isOCLImage3dWOType() && 1409 !OpenCLOptions.isSupported("cl_khr_3d_image_writes", 1410 S.getLangOpts())) { 1411 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension) 1412 << 0 << Result 1413 << (IsOpenCLC30Compatible 1414 ? "cl_khr_3d_image_writes and __opencl_c_3d_image_writes" 1415 : "cl_khr_3d_image_writes"); 1416 declarator.setInvalidType(); 1417 } 1418 } 1419 1420 bool IsFixedPointType = DS.getTypeSpecType() == DeclSpec::TST_accum || 1421 DS.getTypeSpecType() == DeclSpec::TST_fract; 1422 1423 // Only fixed point types can be saturated 1424 if (DS.isTypeSpecSat() && !IsFixedPointType) 1425 S.Diag(DS.getTypeSpecSatLoc(), diag::err_invalid_saturation_spec) 1426 << DS.getSpecifierName(DS.getTypeSpecType(), 1427 Context.getPrintingPolicy()); 1428 1429 // Handle complex types. 1430 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) { 1431 if (S.getLangOpts().Freestanding) 1432 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex); 1433 Result = Context.getComplexType(Result); 1434 } else if (DS.isTypeAltiVecVector()) { 1435 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result)); 1436 assert(typeSize > 0 && "type size for vector must be greater than 0 bits"); 1437 VectorKind VecKind = VectorKind::AltiVecVector; 1438 if (DS.isTypeAltiVecPixel()) 1439 VecKind = VectorKind::AltiVecPixel; 1440 else if (DS.isTypeAltiVecBool()) 1441 VecKind = VectorKind::AltiVecBool; 1442 Result = Context.getVectorType(Result, 128/typeSize, VecKind); 1443 } 1444 1445 // _Imaginary was a feature of C99 through C23 but was never supported in 1446 // Clang. The feature was removed in C2y, but we retain the unsupported 1447 // diagnostic for an improved user experience. 1448 if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary) 1449 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported); 1450 1451 // Before we process any type attributes, synthesize a block literal 1452 // function declarator if necessary. 1453 if (declarator.getContext() == DeclaratorContext::BlockLiteral) 1454 maybeSynthesizeBlockSignature(state, Result); 1455 1456 // Apply any type attributes from the decl spec. This may cause the 1457 // list of type attributes to be temporarily saved while the type 1458 // attributes are pushed around. 1459 // pipe attributes will be handled later ( at GetFullTypeForDeclarator ) 1460 if (!DS.isTypeSpecPipe()) { 1461 // We also apply declaration attributes that "slide" to the decl spec. 1462 // Ordering can be important for attributes. The decalaration attributes 1463 // come syntactically before the decl spec attributes, so we process them 1464 // in that order. 1465 ParsedAttributesView SlidingAttrs; 1466 for (ParsedAttr &AL : declarator.getDeclarationAttributes()) { 1467 if (AL.slidesFromDeclToDeclSpecLegacyBehavior()) { 1468 SlidingAttrs.addAtEnd(&AL); 1469 1470 // For standard syntax attributes, which would normally appertain to the 1471 // declaration here, suggest moving them to the type instead. But only 1472 // do this for our own vendor attributes; moving other vendors' 1473 // attributes might hurt portability. 1474 // There's one special case that we need to deal with here: The 1475 // `MatrixType` attribute may only be used in a typedef declaration. If 1476 // it's being used anywhere else, don't output the warning as 1477 // ProcessDeclAttributes() will output an error anyway. 1478 if (AL.isStandardAttributeSyntax() && AL.isClangScope() && 1479 !(AL.getKind() == ParsedAttr::AT_MatrixType && 1480 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)) { 1481 S.Diag(AL.getLoc(), diag::warn_type_attribute_deprecated_on_decl) 1482 << AL; 1483 } 1484 } 1485 } 1486 // During this call to processTypeAttrs(), 1487 // TypeProcessingState::getCurrentAttributes() will erroneously return a 1488 // reference to the DeclSpec attributes, rather than the declaration 1489 // attributes. However, this doesn't matter, as getCurrentAttributes() 1490 // is only called when distributing attributes from one attribute list 1491 // to another. Declaration attributes are always C++11 attributes, and these 1492 // are never distributed. 1493 processTypeAttrs(state, Result, TAL_DeclSpec, SlidingAttrs); 1494 processTypeAttrs(state, Result, TAL_DeclSpec, DS.getAttributes()); 1495 } 1496 1497 // Apply const/volatile/restrict qualifiers to T. 1498 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 1499 // Warn about CV qualifiers on function types. 1500 // C99 6.7.3p8: 1501 // If the specification of a function type includes any type qualifiers, 1502 // the behavior is undefined. 1503 // C++11 [dcl.fct]p7: 1504 // The effect of a cv-qualifier-seq in a function declarator is not the 1505 // same as adding cv-qualification on top of the function type. In the 1506 // latter case, the cv-qualifiers are ignored. 1507 if (Result->isFunctionType()) { 1508 diagnoseAndRemoveTypeQualifiers( 1509 S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile, 1510 S.getLangOpts().CPlusPlus 1511 ? diag::warn_typecheck_function_qualifiers_ignored 1512 : diag::warn_typecheck_function_qualifiers_unspecified); 1513 // No diagnostic for 'restrict' or '_Atomic' applied to a 1514 // function type; we'll diagnose those later, in BuildQualifiedType. 1515 } 1516 1517 // C++11 [dcl.ref]p1: 1518 // Cv-qualified references are ill-formed except when the 1519 // cv-qualifiers are introduced through the use of a typedef-name 1520 // or decltype-specifier, in which case the cv-qualifiers are ignored. 1521 // 1522 // There don't appear to be any other contexts in which a cv-qualified 1523 // reference type could be formed, so the 'ill-formed' clause here appears 1524 // to never happen. 1525 if (TypeQuals && Result->isReferenceType()) { 1526 diagnoseAndRemoveTypeQualifiers( 1527 S, DS, TypeQuals, Result, 1528 DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic, 1529 diag::warn_typecheck_reference_qualifiers); 1530 } 1531 1532 // C90 6.5.3 constraints: "The same type qualifier shall not appear more 1533 // than once in the same specifier-list or qualifier-list, either directly 1534 // or via one or more typedefs." 1535 if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus 1536 && TypeQuals & Result.getCVRQualifiers()) { 1537 if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) { 1538 S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec) 1539 << "const"; 1540 } 1541 1542 if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) { 1543 S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec) 1544 << "volatile"; 1545 } 1546 1547 // C90 doesn't have restrict nor _Atomic, so it doesn't force us to 1548 // produce a warning in this case. 1549 } 1550 1551 QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS); 1552 1553 // If adding qualifiers fails, just use the unqualified type. 1554 if (Qualified.isNull()) 1555 declarator.setInvalidType(true); 1556 else 1557 Result = Qualified; 1558 } 1559 1560 if (S.getLangOpts().HLSL) 1561 Result = S.HLSL().ProcessResourceTypeAttributes(Result); 1562 1563 assert(!Result.isNull() && "This function should not return a null type"); 1564 return Result; 1565 } 1566 1567 static std::string getPrintableNameForEntity(DeclarationName Entity) { 1568 if (Entity) 1569 return Entity.getAsString(); 1570 1571 return "type name"; 1572 } 1573 1574 static bool isDependentOrGNUAutoType(QualType T) { 1575 if (T->isDependentType()) 1576 return true; 1577 1578 const auto *AT = dyn_cast<AutoType>(T); 1579 return AT && AT->isGNUAutoType(); 1580 } 1581 1582 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc, 1583 Qualifiers Qs, const DeclSpec *DS) { 1584 if (T.isNull()) 1585 return QualType(); 1586 1587 // Ignore any attempt to form a cv-qualified reference. 1588 if (T->isReferenceType()) { 1589 Qs.removeConst(); 1590 Qs.removeVolatile(); 1591 } 1592 1593 // Enforce C99 6.7.3p2: "Types other than pointer types derived from 1594 // object or incomplete types shall not be restrict-qualified." 1595 if (Qs.hasRestrict()) { 1596 unsigned DiagID = 0; 1597 QualType ProblemTy; 1598 1599 if (T->isAnyPointerType() || T->isReferenceType() || 1600 T->isMemberPointerType()) { 1601 QualType EltTy; 1602 if (T->isObjCObjectPointerType()) 1603 EltTy = T; 1604 else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>()) 1605 EltTy = PTy->getPointeeType(); 1606 else 1607 EltTy = T->getPointeeType(); 1608 1609 // If we have a pointer or reference, the pointee must have an object 1610 // incomplete type. 1611 if (!EltTy->isIncompleteOrObjectType()) { 1612 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee; 1613 ProblemTy = EltTy; 1614 } 1615 } else if (!isDependentOrGNUAutoType(T)) { 1616 // For an __auto_type variable, we may not have seen the initializer yet 1617 // and so have no idea whether the underlying type is a pointer type or 1618 // not. 1619 DiagID = diag::err_typecheck_invalid_restrict_not_pointer; 1620 ProblemTy = T; 1621 } 1622 1623 if (DiagID) { 1624 Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy; 1625 Qs.removeRestrict(); 1626 } 1627 } 1628 1629 return Context.getQualifiedType(T, Qs); 1630 } 1631 1632 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc, 1633 unsigned CVRAU, const DeclSpec *DS) { 1634 if (T.isNull()) 1635 return QualType(); 1636 1637 // Ignore any attempt to form a cv-qualified reference. 1638 if (T->isReferenceType()) 1639 CVRAU &= 1640 ~(DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic); 1641 1642 // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic and 1643 // TQ_unaligned; 1644 unsigned CVR = CVRAU & ~(DeclSpec::TQ_atomic | DeclSpec::TQ_unaligned); 1645 1646 // C11 6.7.3/5: 1647 // If the same qualifier appears more than once in the same 1648 // specifier-qualifier-list, either directly or via one or more typedefs, 1649 // the behavior is the same as if it appeared only once. 1650 // 1651 // It's not specified what happens when the _Atomic qualifier is applied to 1652 // a type specified with the _Atomic specifier, but we assume that this 1653 // should be treated as if the _Atomic qualifier appeared multiple times. 1654 if (CVRAU & DeclSpec::TQ_atomic && !T->isAtomicType()) { 1655 // C11 6.7.3/5: 1656 // If other qualifiers appear along with the _Atomic qualifier in a 1657 // specifier-qualifier-list, the resulting type is the so-qualified 1658 // atomic type. 1659 // 1660 // Don't need to worry about array types here, since _Atomic can't be 1661 // applied to such types. 1662 SplitQualType Split = T.getSplitUnqualifiedType(); 1663 T = BuildAtomicType(QualType(Split.Ty, 0), 1664 DS ? DS->getAtomicSpecLoc() : Loc); 1665 if (T.isNull()) 1666 return T; 1667 Split.Quals.addCVRQualifiers(CVR); 1668 return BuildQualifiedType(T, Loc, Split.Quals); 1669 } 1670 1671 Qualifiers Q = Qualifiers::fromCVRMask(CVR); 1672 Q.setUnaligned(CVRAU & DeclSpec::TQ_unaligned); 1673 return BuildQualifiedType(T, Loc, Q, DS); 1674 } 1675 1676 QualType Sema::BuildParenType(QualType T) { 1677 return Context.getParenType(T); 1678 } 1679 1680 /// Given that we're building a pointer or reference to the given 1681 static QualType inferARCLifetimeForPointee(Sema &S, QualType type, 1682 SourceLocation loc, 1683 bool isReference) { 1684 // Bail out if retention is unrequired or already specified. 1685 if (!type->isObjCLifetimeType() || 1686 type.getObjCLifetime() != Qualifiers::OCL_None) 1687 return type; 1688 1689 Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None; 1690 1691 // If the object type is const-qualified, we can safely use 1692 // __unsafe_unretained. This is safe (because there are no read 1693 // barriers), and it'll be safe to coerce anything but __weak* to 1694 // the resulting type. 1695 if (type.isConstQualified()) { 1696 implicitLifetime = Qualifiers::OCL_ExplicitNone; 1697 1698 // Otherwise, check whether the static type does not require 1699 // retaining. This currently only triggers for Class (possibly 1700 // protocol-qualifed, and arrays thereof). 1701 } else if (type->isObjCARCImplicitlyUnretainedType()) { 1702 implicitLifetime = Qualifiers::OCL_ExplicitNone; 1703 1704 // If we are in an unevaluated context, like sizeof, skip adding a 1705 // qualification. 1706 } else if (S.isUnevaluatedContext()) { 1707 return type; 1708 1709 // If that failed, give an error and recover using __strong. __strong 1710 // is the option most likely to prevent spurious second-order diagnostics, 1711 // like when binding a reference to a field. 1712 } else { 1713 // These types can show up in private ivars in system headers, so 1714 // we need this to not be an error in those cases. Instead we 1715 // want to delay. 1716 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) { 1717 S.DelayedDiagnostics.add( 1718 sema::DelayedDiagnostic::makeForbiddenType(loc, 1719 diag::err_arc_indirect_no_ownership, type, isReference)); 1720 } else { 1721 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference; 1722 } 1723 implicitLifetime = Qualifiers::OCL_Strong; 1724 } 1725 assert(implicitLifetime && "didn't infer any lifetime!"); 1726 1727 Qualifiers qs; 1728 qs.addObjCLifetime(implicitLifetime); 1729 return S.Context.getQualifiedType(type, qs); 1730 } 1731 1732 static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){ 1733 std::string Quals = FnTy->getMethodQuals().getAsString(); 1734 1735 switch (FnTy->getRefQualifier()) { 1736 case RQ_None: 1737 break; 1738 1739 case RQ_LValue: 1740 if (!Quals.empty()) 1741 Quals += ' '; 1742 Quals += '&'; 1743 break; 1744 1745 case RQ_RValue: 1746 if (!Quals.empty()) 1747 Quals += ' '; 1748 Quals += "&&"; 1749 break; 1750 } 1751 1752 return Quals; 1753 } 1754 1755 namespace { 1756 /// Kinds of declarator that cannot contain a qualified function type. 1757 /// 1758 /// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6: 1759 /// a function type with a cv-qualifier or a ref-qualifier can only appear 1760 /// at the topmost level of a type. 1761 /// 1762 /// Parens and member pointers are permitted. We don't diagnose array and 1763 /// function declarators, because they don't allow function types at all. 1764 /// 1765 /// The values of this enum are used in diagnostics. 1766 enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference }; 1767 } // end anonymous namespace 1768 1769 /// Check whether the type T is a qualified function type, and if it is, 1770 /// diagnose that it cannot be contained within the given kind of declarator. 1771 static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc, 1772 QualifiedFunctionKind QFK) { 1773 // Does T refer to a function type with a cv-qualifier or a ref-qualifier? 1774 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>(); 1775 if (!FPT || 1776 (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None)) 1777 return false; 1778 1779 S.Diag(Loc, diag::err_compound_qualified_function_type) 1780 << QFK << isa<FunctionType>(T.IgnoreParens()) << T 1781 << getFunctionQualifiersAsString(FPT); 1782 return true; 1783 } 1784 1785 bool Sema::CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc) { 1786 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>(); 1787 if (!FPT || 1788 (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None)) 1789 return false; 1790 1791 Diag(Loc, diag::err_qualified_function_typeid) 1792 << T << getFunctionQualifiersAsString(FPT); 1793 return true; 1794 } 1795 1796 // Helper to deduce addr space of a pointee type in OpenCL mode. 1797 static QualType deduceOpenCLPointeeAddrSpace(Sema &S, QualType PointeeType) { 1798 if (!PointeeType->isUndeducedAutoType() && !PointeeType->isDependentType() && 1799 !PointeeType->isSamplerT() && 1800 !PointeeType.hasAddressSpace()) 1801 PointeeType = S.getASTContext().getAddrSpaceQualType( 1802 PointeeType, S.getASTContext().getDefaultOpenCLPointeeAddrSpace()); 1803 return PointeeType; 1804 } 1805 1806 QualType Sema::BuildPointerType(QualType T, 1807 SourceLocation Loc, DeclarationName Entity) { 1808 if (T->isReferenceType()) { 1809 // C++ 8.3.2p4: There shall be no ... pointers to references ... 1810 Diag(Loc, diag::err_illegal_decl_pointer_to_reference) 1811 << getPrintableNameForEntity(Entity) << T; 1812 return QualType(); 1813 } 1814 1815 if (T->isFunctionType() && getLangOpts().OpenCL && 1816 !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers", 1817 getLangOpts())) { 1818 Diag(Loc, diag::err_opencl_function_pointer) << /*pointer*/ 0; 1819 return QualType(); 1820 } 1821 1822 if (getLangOpts().HLSL && Loc.isValid()) { 1823 Diag(Loc, diag::err_hlsl_pointers_unsupported) << 0; 1824 return QualType(); 1825 } 1826 1827 if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer)) 1828 return QualType(); 1829 1830 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType"); 1831 1832 // In ARC, it is forbidden to build pointers to unqualified pointers. 1833 if (getLangOpts().ObjCAutoRefCount) 1834 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false); 1835 1836 if (getLangOpts().OpenCL) 1837 T = deduceOpenCLPointeeAddrSpace(*this, T); 1838 1839 // In WebAssembly, pointers to reference types and pointers to tables are 1840 // illegal. 1841 if (getASTContext().getTargetInfo().getTriple().isWasm()) { 1842 if (T.isWebAssemblyReferenceType()) { 1843 Diag(Loc, diag::err_wasm_reference_pr) << 0; 1844 return QualType(); 1845 } 1846 1847 // We need to desugar the type here in case T is a ParenType. 1848 if (T->getUnqualifiedDesugaredType()->isWebAssemblyTableType()) { 1849 Diag(Loc, diag::err_wasm_table_pr) << 0; 1850 return QualType(); 1851 } 1852 } 1853 1854 // Build the pointer type. 1855 return Context.getPointerType(T); 1856 } 1857 1858 QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue, 1859 SourceLocation Loc, 1860 DeclarationName Entity) { 1861 assert(Context.getCanonicalType(T) != Context.OverloadTy && 1862 "Unresolved overloaded function type"); 1863 1864 // C++0x [dcl.ref]p6: 1865 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a 1866 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a 1867 // type T, an attempt to create the type "lvalue reference to cv TR" creates 1868 // the type "lvalue reference to T", while an attempt to create the type 1869 // "rvalue reference to cv TR" creates the type TR. 1870 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>(); 1871 1872 // C++ [dcl.ref]p4: There shall be no references to references. 1873 // 1874 // According to C++ DR 106, references to references are only 1875 // diagnosed when they are written directly (e.g., "int & &"), 1876 // but not when they happen via a typedef: 1877 // 1878 // typedef int& intref; 1879 // typedef intref& intref2; 1880 // 1881 // Parser::ParseDeclaratorInternal diagnoses the case where 1882 // references are written directly; here, we handle the 1883 // collapsing of references-to-references as described in C++0x. 1884 // DR 106 and 540 introduce reference-collapsing into C++98/03. 1885 1886 // C++ [dcl.ref]p1: 1887 // A declarator that specifies the type "reference to cv void" 1888 // is ill-formed. 1889 if (T->isVoidType()) { 1890 Diag(Loc, diag::err_reference_to_void); 1891 return QualType(); 1892 } 1893 1894 if (getLangOpts().HLSL && Loc.isValid()) { 1895 Diag(Loc, diag::err_hlsl_pointers_unsupported) << 1; 1896 return QualType(); 1897 } 1898 1899 if (checkQualifiedFunction(*this, T, Loc, QFK_Reference)) 1900 return QualType(); 1901 1902 if (T->isFunctionType() && getLangOpts().OpenCL && 1903 !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers", 1904 getLangOpts())) { 1905 Diag(Loc, diag::err_opencl_function_pointer) << /*reference*/ 1; 1906 return QualType(); 1907 } 1908 1909 // In ARC, it is forbidden to build references to unqualified pointers. 1910 if (getLangOpts().ObjCAutoRefCount) 1911 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true); 1912 1913 if (getLangOpts().OpenCL) 1914 T = deduceOpenCLPointeeAddrSpace(*this, T); 1915 1916 // In WebAssembly, references to reference types and tables are illegal. 1917 if (getASTContext().getTargetInfo().getTriple().isWasm() && 1918 T.isWebAssemblyReferenceType()) { 1919 Diag(Loc, diag::err_wasm_reference_pr) << 1; 1920 return QualType(); 1921 } 1922 if (T->isWebAssemblyTableType()) { 1923 Diag(Loc, diag::err_wasm_table_pr) << 1; 1924 return QualType(); 1925 } 1926 1927 // Handle restrict on references. 1928 if (LValueRef) 1929 return Context.getLValueReferenceType(T, SpelledAsLValue); 1930 return Context.getRValueReferenceType(T); 1931 } 1932 1933 QualType Sema::BuildReadPipeType(QualType T, SourceLocation Loc) { 1934 return Context.getReadPipeType(T); 1935 } 1936 1937 QualType Sema::BuildWritePipeType(QualType T, SourceLocation Loc) { 1938 return Context.getWritePipeType(T); 1939 } 1940 1941 QualType Sema::BuildBitIntType(bool IsUnsigned, Expr *BitWidth, 1942 SourceLocation Loc) { 1943 if (BitWidth->isInstantiationDependent()) 1944 return Context.getDependentBitIntType(IsUnsigned, BitWidth); 1945 1946 llvm::APSInt Bits(32); 1947 ExprResult ICE = 1948 VerifyIntegerConstantExpression(BitWidth, &Bits, /*FIXME*/ AllowFold); 1949 1950 if (ICE.isInvalid()) 1951 return QualType(); 1952 1953 size_t NumBits = Bits.getZExtValue(); 1954 if (!IsUnsigned && NumBits < 2) { 1955 Diag(Loc, diag::err_bit_int_bad_size) << 0; 1956 return QualType(); 1957 } 1958 1959 if (IsUnsigned && NumBits < 1) { 1960 Diag(Loc, diag::err_bit_int_bad_size) << 1; 1961 return QualType(); 1962 } 1963 1964 const TargetInfo &TI = getASTContext().getTargetInfo(); 1965 if (NumBits > TI.getMaxBitIntWidth()) { 1966 Diag(Loc, diag::err_bit_int_max_size) 1967 << IsUnsigned << static_cast<uint64_t>(TI.getMaxBitIntWidth()); 1968 return QualType(); 1969 } 1970 1971 return Context.getBitIntType(IsUnsigned, NumBits); 1972 } 1973 1974 /// Check whether the specified array bound can be evaluated using the relevant 1975 /// language rules. If so, returns the possibly-converted expression and sets 1976 /// SizeVal to the size. If not, but the expression might be a VLA bound, 1977 /// returns ExprResult(). Otherwise, produces a diagnostic and returns 1978 /// ExprError(). 1979 static ExprResult checkArraySize(Sema &S, Expr *&ArraySize, 1980 llvm::APSInt &SizeVal, unsigned VLADiag, 1981 bool VLAIsError) { 1982 if (S.getLangOpts().CPlusPlus14 && 1983 (VLAIsError || 1984 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType())) { 1985 // C++14 [dcl.array]p1: 1986 // The constant-expression shall be a converted constant expression of 1987 // type std::size_t. 1988 // 1989 // Don't apply this rule if we might be forming a VLA: in that case, we 1990 // allow non-constant expressions and constant-folding. We only need to use 1991 // the converted constant expression rules (to properly convert the source) 1992 // when the source expression is of class type. 1993 return S.CheckConvertedConstantExpression( 1994 ArraySize, S.Context.getSizeType(), SizeVal, Sema::CCEK_ArrayBound); 1995 } 1996 1997 // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode 1998 // (like gnu99, but not c99) accept any evaluatable value as an extension. 1999 class VLADiagnoser : public Sema::VerifyICEDiagnoser { 2000 public: 2001 unsigned VLADiag; 2002 bool VLAIsError; 2003 bool IsVLA = false; 2004 2005 VLADiagnoser(unsigned VLADiag, bool VLAIsError) 2006 : VLADiag(VLADiag), VLAIsError(VLAIsError) {} 2007 2008 Sema::SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, 2009 QualType T) override { 2010 return S.Diag(Loc, diag::err_array_size_non_int) << T; 2011 } 2012 2013 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S, 2014 SourceLocation Loc) override { 2015 IsVLA = !VLAIsError; 2016 return S.Diag(Loc, VLADiag); 2017 } 2018 2019 Sema::SemaDiagnosticBuilder diagnoseFold(Sema &S, 2020 SourceLocation Loc) override { 2021 return S.Diag(Loc, diag::ext_vla_folded_to_constant); 2022 } 2023 } Diagnoser(VLADiag, VLAIsError); 2024 2025 ExprResult R = 2026 S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser); 2027 if (Diagnoser.IsVLA) 2028 return ExprResult(); 2029 return R; 2030 } 2031 2032 bool Sema::checkArrayElementAlignment(QualType EltTy, SourceLocation Loc) { 2033 EltTy = Context.getBaseElementType(EltTy); 2034 if (EltTy->isIncompleteType() || EltTy->isDependentType() || 2035 EltTy->isUndeducedType()) 2036 return true; 2037 2038 CharUnits Size = Context.getTypeSizeInChars(EltTy); 2039 CharUnits Alignment = Context.getTypeAlignInChars(EltTy); 2040 2041 if (Size.isMultipleOf(Alignment)) 2042 return true; 2043 2044 Diag(Loc, diag::err_array_element_alignment) 2045 << EltTy << Size.getQuantity() << Alignment.getQuantity(); 2046 return false; 2047 } 2048 2049 QualType Sema::BuildArrayType(QualType T, ArraySizeModifier ASM, 2050 Expr *ArraySize, unsigned Quals, 2051 SourceRange Brackets, DeclarationName Entity) { 2052 2053 SourceLocation Loc = Brackets.getBegin(); 2054 if (getLangOpts().CPlusPlus) { 2055 // C++ [dcl.array]p1: 2056 // T is called the array element type; this type shall not be a reference 2057 // type, the (possibly cv-qualified) type void, a function type or an 2058 // abstract class type. 2059 // 2060 // C++ [dcl.array]p3: 2061 // When several "array of" specifications are adjacent, [...] only the 2062 // first of the constant expressions that specify the bounds of the arrays 2063 // may be omitted. 2064 // 2065 // Note: function types are handled in the common path with C. 2066 if (T->isReferenceType()) { 2067 Diag(Loc, diag::err_illegal_decl_array_of_references) 2068 << getPrintableNameForEntity(Entity) << T; 2069 return QualType(); 2070 } 2071 2072 if (T->isVoidType() || T->isIncompleteArrayType()) { 2073 Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 0 << T; 2074 return QualType(); 2075 } 2076 2077 if (RequireNonAbstractType(Brackets.getBegin(), T, 2078 diag::err_array_of_abstract_type)) 2079 return QualType(); 2080 2081 // Mentioning a member pointer type for an array type causes us to lock in 2082 // an inheritance model, even if it's inside an unused typedef. 2083 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 2084 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) 2085 if (!MPTy->getClass()->isDependentType()) 2086 (void)isCompleteType(Loc, T); 2087 2088 } else { 2089 // C99 6.7.5.2p1: If the element type is an incomplete or function type, 2090 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]()) 2091 if (!T.isWebAssemblyReferenceType() && 2092 RequireCompleteSizedType(Loc, T, 2093 diag::err_array_incomplete_or_sizeless_type)) 2094 return QualType(); 2095 } 2096 2097 // Multi-dimensional arrays of WebAssembly references are not allowed. 2098 if (Context.getTargetInfo().getTriple().isWasm() && T->isArrayType()) { 2099 const auto *ATy = dyn_cast<ArrayType>(T); 2100 if (ATy && ATy->getElementType().isWebAssemblyReferenceType()) { 2101 Diag(Loc, diag::err_wasm_reftype_multidimensional_array); 2102 return QualType(); 2103 } 2104 } 2105 2106 if (T->isSizelessType() && !T.isWebAssemblyReferenceType()) { 2107 Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 1 << T; 2108 return QualType(); 2109 } 2110 2111 if (T->isFunctionType()) { 2112 Diag(Loc, diag::err_illegal_decl_array_of_functions) 2113 << getPrintableNameForEntity(Entity) << T; 2114 return QualType(); 2115 } 2116 2117 if (const RecordType *EltTy = T->getAs<RecordType>()) { 2118 // If the element type is a struct or union that contains a variadic 2119 // array, accept it as a GNU extension: C99 6.7.2.1p2. 2120 if (EltTy->getDecl()->hasFlexibleArrayMember()) 2121 Diag(Loc, diag::ext_flexible_array_in_array) << T; 2122 } else if (T->isObjCObjectType()) { 2123 Diag(Loc, diag::err_objc_array_of_interfaces) << T; 2124 return QualType(); 2125 } 2126 2127 if (!checkArrayElementAlignment(T, Loc)) 2128 return QualType(); 2129 2130 // Do placeholder conversions on the array size expression. 2131 if (ArraySize && ArraySize->hasPlaceholderType()) { 2132 ExprResult Result = CheckPlaceholderExpr(ArraySize); 2133 if (Result.isInvalid()) return QualType(); 2134 ArraySize = Result.get(); 2135 } 2136 2137 // Do lvalue-to-rvalue conversions on the array size expression. 2138 if (ArraySize && !ArraySize->isPRValue()) { 2139 ExprResult Result = DefaultLvalueConversion(ArraySize); 2140 if (Result.isInvalid()) 2141 return QualType(); 2142 2143 ArraySize = Result.get(); 2144 } 2145 2146 // C99 6.7.5.2p1: The size expression shall have integer type. 2147 // C++11 allows contextual conversions to such types. 2148 if (!getLangOpts().CPlusPlus11 && 2149 ArraySize && !ArraySize->isTypeDependent() && 2150 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) { 2151 Diag(ArraySize->getBeginLoc(), diag::err_array_size_non_int) 2152 << ArraySize->getType() << ArraySize->getSourceRange(); 2153 return QualType(); 2154 } 2155 2156 auto IsStaticAssertLike = [](const Expr *ArraySize, ASTContext &Context) { 2157 if (!ArraySize) 2158 return false; 2159 2160 // If the array size expression is a conditional expression whose branches 2161 // are both integer constant expressions, one negative and one positive, 2162 // then it's assumed to be like an old-style static assertion. e.g., 2163 // int old_style_assert[expr ? 1 : -1]; 2164 // We will accept any integer constant expressions instead of assuming the 2165 // values 1 and -1 are always used. 2166 if (const auto *CondExpr = dyn_cast_if_present<ConditionalOperator>( 2167 ArraySize->IgnoreParenImpCasts())) { 2168 std::optional<llvm::APSInt> LHS = 2169 CondExpr->getLHS()->getIntegerConstantExpr(Context); 2170 std::optional<llvm::APSInt> RHS = 2171 CondExpr->getRHS()->getIntegerConstantExpr(Context); 2172 return LHS && RHS && LHS->isNegative() != RHS->isNegative(); 2173 } 2174 return false; 2175 }; 2176 2177 // VLAs always produce at least a -Wvla diagnostic, sometimes an error. 2178 unsigned VLADiag; 2179 bool VLAIsError; 2180 if (getLangOpts().OpenCL) { 2181 // OpenCL v1.2 s6.9.d: variable length arrays are not supported. 2182 VLADiag = diag::err_opencl_vla; 2183 VLAIsError = true; 2184 } else if (getLangOpts().C99) { 2185 VLADiag = diag::warn_vla_used; 2186 VLAIsError = false; 2187 } else if (isSFINAEContext()) { 2188 VLADiag = diag::err_vla_in_sfinae; 2189 VLAIsError = true; 2190 } else if (getLangOpts().OpenMP && OpenMP().isInOpenMPTaskUntiedContext()) { 2191 VLADiag = diag::err_openmp_vla_in_task_untied; 2192 VLAIsError = true; 2193 } else if (getLangOpts().CPlusPlus) { 2194 if (getLangOpts().CPlusPlus11 && IsStaticAssertLike(ArraySize, Context)) 2195 VLADiag = getLangOpts().GNUMode 2196 ? diag::ext_vla_cxx_in_gnu_mode_static_assert 2197 : diag::ext_vla_cxx_static_assert; 2198 else 2199 VLADiag = getLangOpts().GNUMode ? diag::ext_vla_cxx_in_gnu_mode 2200 : diag::ext_vla_cxx; 2201 VLAIsError = false; 2202 } else { 2203 VLADiag = diag::ext_vla; 2204 VLAIsError = false; 2205 } 2206 2207 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType())); 2208 if (!ArraySize) { 2209 if (ASM == ArraySizeModifier::Star) { 2210 Diag(Loc, VLADiag); 2211 if (VLAIsError) 2212 return QualType(); 2213 2214 T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets); 2215 } else { 2216 T = Context.getIncompleteArrayType(T, ASM, Quals); 2217 } 2218 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) { 2219 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets); 2220 } else { 2221 ExprResult R = 2222 checkArraySize(*this, ArraySize, ConstVal, VLADiag, VLAIsError); 2223 if (R.isInvalid()) 2224 return QualType(); 2225 2226 if (!R.isUsable()) { 2227 // C99: an array with a non-ICE size is a VLA. We accept any expression 2228 // that we can fold to a non-zero positive value as a non-VLA as an 2229 // extension. 2230 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets); 2231 } else if (!T->isDependentType() && !T->isIncompleteType() && 2232 !T->isConstantSizeType()) { 2233 // C99: an array with an element type that has a non-constant-size is a 2234 // VLA. 2235 // FIXME: Add a note to explain why this isn't a VLA. 2236 Diag(Loc, VLADiag); 2237 if (VLAIsError) 2238 return QualType(); 2239 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets); 2240 } else { 2241 // C99 6.7.5.2p1: If the expression is a constant expression, it shall 2242 // have a value greater than zero. 2243 // In C++, this follows from narrowing conversions being disallowed. 2244 if (ConstVal.isSigned() && ConstVal.isNegative()) { 2245 if (Entity) 2246 Diag(ArraySize->getBeginLoc(), diag::err_decl_negative_array_size) 2247 << getPrintableNameForEntity(Entity) 2248 << ArraySize->getSourceRange(); 2249 else 2250 Diag(ArraySize->getBeginLoc(), 2251 diag::err_typecheck_negative_array_size) 2252 << ArraySize->getSourceRange(); 2253 return QualType(); 2254 } 2255 if (ConstVal == 0 && !T.isWebAssemblyReferenceType()) { 2256 // GCC accepts zero sized static arrays. We allow them when 2257 // we're not in a SFINAE context. 2258 Diag(ArraySize->getBeginLoc(), 2259 isSFINAEContext() ? diag::err_typecheck_zero_array_size 2260 : diag::ext_typecheck_zero_array_size) 2261 << 0 << ArraySize->getSourceRange(); 2262 } 2263 2264 // Is the array too large? 2265 unsigned ActiveSizeBits = 2266 (!T->isDependentType() && !T->isVariablyModifiedType() && 2267 !T->isIncompleteType() && !T->isUndeducedType()) 2268 ? ConstantArrayType::getNumAddressingBits(Context, T, ConstVal) 2269 : ConstVal.getActiveBits(); 2270 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 2271 Diag(ArraySize->getBeginLoc(), diag::err_array_too_large) 2272 << toString(ConstVal, 10) << ArraySize->getSourceRange(); 2273 return QualType(); 2274 } 2275 2276 T = Context.getConstantArrayType(T, ConstVal, ArraySize, ASM, Quals); 2277 } 2278 } 2279 2280 if (T->isVariableArrayType()) { 2281 if (!Context.getTargetInfo().isVLASupported()) { 2282 // CUDA device code and some other targets don't support VLAs. 2283 bool IsCUDADevice = (getLangOpts().CUDA && getLangOpts().CUDAIsDevice); 2284 targetDiag(Loc, 2285 IsCUDADevice ? diag::err_cuda_vla : diag::err_vla_unsupported) 2286 << (IsCUDADevice ? llvm::to_underlying(CUDA().CurrentTarget()) : 0); 2287 } else if (sema::FunctionScopeInfo *FSI = getCurFunction()) { 2288 // VLAs are supported on this target, but we may need to do delayed 2289 // checking that the VLA is not being used within a coroutine. 2290 FSI->setHasVLA(Loc); 2291 } 2292 } 2293 2294 // If this is not C99, diagnose array size modifiers on non-VLAs. 2295 if (!getLangOpts().C99 && !T->isVariableArrayType() && 2296 (ASM != ArraySizeModifier::Normal || Quals != 0)) { 2297 Diag(Loc, getLangOpts().CPlusPlus ? diag::err_c99_array_usage_cxx 2298 : diag::ext_c99_array_usage) 2299 << llvm::to_underlying(ASM); 2300 } 2301 2302 // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported. 2303 // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported. 2304 // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported. 2305 if (getLangOpts().OpenCL) { 2306 const QualType ArrType = Context.getBaseElementType(T); 2307 if (ArrType->isBlockPointerType() || ArrType->isPipeType() || 2308 ArrType->isSamplerT() || ArrType->isImageType()) { 2309 Diag(Loc, diag::err_opencl_invalid_type_array) << ArrType; 2310 return QualType(); 2311 } 2312 } 2313 2314 return T; 2315 } 2316 2317 QualType Sema::BuildVectorType(QualType CurType, Expr *SizeExpr, 2318 SourceLocation AttrLoc) { 2319 // The base type must be integer (not Boolean or enumeration) or float, and 2320 // can't already be a vector. 2321 if ((!CurType->isDependentType() && 2322 (!CurType->isBuiltinType() || CurType->isBooleanType() || 2323 (!CurType->isIntegerType() && !CurType->isRealFloatingType())) && 2324 !CurType->isBitIntType()) || 2325 CurType->isArrayType()) { 2326 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << CurType; 2327 return QualType(); 2328 } 2329 // Only support _BitInt elements with byte-sized power of 2 NumBits. 2330 if (const auto *BIT = CurType->getAs<BitIntType>()) { 2331 unsigned NumBits = BIT->getNumBits(); 2332 if (!llvm::isPowerOf2_32(NumBits) || NumBits < 8) { 2333 Diag(AttrLoc, diag::err_attribute_invalid_bitint_vector_type) 2334 << (NumBits < 8); 2335 return QualType(); 2336 } 2337 } 2338 2339 if (SizeExpr->isTypeDependent() || SizeExpr->isValueDependent()) 2340 return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc, 2341 VectorKind::Generic); 2342 2343 std::optional<llvm::APSInt> VecSize = 2344 SizeExpr->getIntegerConstantExpr(Context); 2345 if (!VecSize) { 2346 Diag(AttrLoc, diag::err_attribute_argument_type) 2347 << "vector_size" << AANT_ArgumentIntegerConstant 2348 << SizeExpr->getSourceRange(); 2349 return QualType(); 2350 } 2351 2352 if (CurType->isDependentType()) 2353 return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc, 2354 VectorKind::Generic); 2355 2356 // vecSize is specified in bytes - convert to bits. 2357 if (!VecSize->isIntN(61)) { 2358 // Bit size will overflow uint64. 2359 Diag(AttrLoc, diag::err_attribute_size_too_large) 2360 << SizeExpr->getSourceRange() << "vector"; 2361 return QualType(); 2362 } 2363 uint64_t VectorSizeBits = VecSize->getZExtValue() * 8; 2364 unsigned TypeSize = static_cast<unsigned>(Context.getTypeSize(CurType)); 2365 2366 if (VectorSizeBits == 0) { 2367 Diag(AttrLoc, diag::err_attribute_zero_size) 2368 << SizeExpr->getSourceRange() << "vector"; 2369 return QualType(); 2370 } 2371 2372 if (!TypeSize || VectorSizeBits % TypeSize) { 2373 Diag(AttrLoc, diag::err_attribute_invalid_size) 2374 << SizeExpr->getSourceRange(); 2375 return QualType(); 2376 } 2377 2378 if (VectorSizeBits / TypeSize > std::numeric_limits<uint32_t>::max()) { 2379 Diag(AttrLoc, diag::err_attribute_size_too_large) 2380 << SizeExpr->getSourceRange() << "vector"; 2381 return QualType(); 2382 } 2383 2384 return Context.getVectorType(CurType, VectorSizeBits / TypeSize, 2385 VectorKind::Generic); 2386 } 2387 2388 QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize, 2389 SourceLocation AttrLoc) { 2390 // Unlike gcc's vector_size attribute, we do not allow vectors to be defined 2391 // in conjunction with complex types (pointers, arrays, functions, etc.). 2392 // 2393 // Additionally, OpenCL prohibits vectors of booleans (they're considered a 2394 // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects 2395 // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors 2396 // of bool aren't allowed. 2397 // 2398 // We explicitly allow bool elements in ext_vector_type for C/C++. 2399 bool IsNoBoolVecLang = getLangOpts().OpenCL || getLangOpts().OpenCLCPlusPlus; 2400 if ((!T->isDependentType() && !T->isIntegerType() && 2401 !T->isRealFloatingType()) || 2402 (IsNoBoolVecLang && T->isBooleanType())) { 2403 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T; 2404 return QualType(); 2405 } 2406 2407 // Only support _BitInt elements with byte-sized power of 2 NumBits. 2408 if (T->isBitIntType()) { 2409 unsigned NumBits = T->castAs<BitIntType>()->getNumBits(); 2410 if (!llvm::isPowerOf2_32(NumBits) || NumBits < 8) { 2411 Diag(AttrLoc, diag::err_attribute_invalid_bitint_vector_type) 2412 << (NumBits < 8); 2413 return QualType(); 2414 } 2415 } 2416 2417 if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) { 2418 std::optional<llvm::APSInt> vecSize = 2419 ArraySize->getIntegerConstantExpr(Context); 2420 if (!vecSize) { 2421 Diag(AttrLoc, diag::err_attribute_argument_type) 2422 << "ext_vector_type" << AANT_ArgumentIntegerConstant 2423 << ArraySize->getSourceRange(); 2424 return QualType(); 2425 } 2426 2427 if (!vecSize->isIntN(32)) { 2428 Diag(AttrLoc, diag::err_attribute_size_too_large) 2429 << ArraySize->getSourceRange() << "vector"; 2430 return QualType(); 2431 } 2432 // Unlike gcc's vector_size attribute, the size is specified as the 2433 // number of elements, not the number of bytes. 2434 unsigned vectorSize = static_cast<unsigned>(vecSize->getZExtValue()); 2435 2436 if (vectorSize == 0) { 2437 Diag(AttrLoc, diag::err_attribute_zero_size) 2438 << ArraySize->getSourceRange() << "vector"; 2439 return QualType(); 2440 } 2441 2442 return Context.getExtVectorType(T, vectorSize); 2443 } 2444 2445 return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc); 2446 } 2447 2448 QualType Sema::BuildMatrixType(QualType ElementTy, Expr *NumRows, Expr *NumCols, 2449 SourceLocation AttrLoc) { 2450 assert(Context.getLangOpts().MatrixTypes && 2451 "Should never build a matrix type when it is disabled"); 2452 2453 // Check element type, if it is not dependent. 2454 if (!ElementTy->isDependentType() && 2455 !MatrixType::isValidElementType(ElementTy)) { 2456 Diag(AttrLoc, diag::err_attribute_invalid_matrix_type) << ElementTy; 2457 return QualType(); 2458 } 2459 2460 if (NumRows->isTypeDependent() || NumCols->isTypeDependent() || 2461 NumRows->isValueDependent() || NumCols->isValueDependent()) 2462 return Context.getDependentSizedMatrixType(ElementTy, NumRows, NumCols, 2463 AttrLoc); 2464 2465 std::optional<llvm::APSInt> ValueRows = 2466 NumRows->getIntegerConstantExpr(Context); 2467 std::optional<llvm::APSInt> ValueColumns = 2468 NumCols->getIntegerConstantExpr(Context); 2469 2470 auto const RowRange = NumRows->getSourceRange(); 2471 auto const ColRange = NumCols->getSourceRange(); 2472 2473 // Both are row and column expressions are invalid. 2474 if (!ValueRows && !ValueColumns) { 2475 Diag(AttrLoc, diag::err_attribute_argument_type) 2476 << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange 2477 << ColRange; 2478 return QualType(); 2479 } 2480 2481 // Only the row expression is invalid. 2482 if (!ValueRows) { 2483 Diag(AttrLoc, diag::err_attribute_argument_type) 2484 << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange; 2485 return QualType(); 2486 } 2487 2488 // Only the column expression is invalid. 2489 if (!ValueColumns) { 2490 Diag(AttrLoc, diag::err_attribute_argument_type) 2491 << "matrix_type" << AANT_ArgumentIntegerConstant << ColRange; 2492 return QualType(); 2493 } 2494 2495 // Check the matrix dimensions. 2496 unsigned MatrixRows = static_cast<unsigned>(ValueRows->getZExtValue()); 2497 unsigned MatrixColumns = static_cast<unsigned>(ValueColumns->getZExtValue()); 2498 if (MatrixRows == 0 && MatrixColumns == 0) { 2499 Diag(AttrLoc, diag::err_attribute_zero_size) 2500 << "matrix" << RowRange << ColRange; 2501 return QualType(); 2502 } 2503 if (MatrixRows == 0) { 2504 Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << RowRange; 2505 return QualType(); 2506 } 2507 if (MatrixColumns == 0) { 2508 Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << ColRange; 2509 return QualType(); 2510 } 2511 if (!ConstantMatrixType::isDimensionValid(MatrixRows)) { 2512 Diag(AttrLoc, diag::err_attribute_size_too_large) 2513 << RowRange << "matrix row"; 2514 return QualType(); 2515 } 2516 if (!ConstantMatrixType::isDimensionValid(MatrixColumns)) { 2517 Diag(AttrLoc, diag::err_attribute_size_too_large) 2518 << ColRange << "matrix column"; 2519 return QualType(); 2520 } 2521 return Context.getConstantMatrixType(ElementTy, MatrixRows, MatrixColumns); 2522 } 2523 2524 bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) { 2525 if (T->isArrayType() || T->isFunctionType()) { 2526 Diag(Loc, diag::err_func_returning_array_function) 2527 << T->isFunctionType() << T; 2528 return true; 2529 } 2530 2531 // Functions cannot return half FP. 2532 if (T->isHalfType() && !getLangOpts().NativeHalfArgsAndReturns && 2533 !Context.getTargetInfo().allowHalfArgsAndReturns()) { 2534 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 << 2535 FixItHint::CreateInsertion(Loc, "*"); 2536 return true; 2537 } 2538 2539 // Methods cannot return interface types. All ObjC objects are 2540 // passed by reference. 2541 if (T->isObjCObjectType()) { 2542 Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value) 2543 << 0 << T << FixItHint::CreateInsertion(Loc, "*"); 2544 return true; 2545 } 2546 2547 if (T.hasNonTrivialToPrimitiveDestructCUnion() || 2548 T.hasNonTrivialToPrimitiveCopyCUnion()) 2549 checkNonTrivialCUnion(T, Loc, NTCUC_FunctionReturn, 2550 NTCUK_Destruct|NTCUK_Copy); 2551 2552 // C++2a [dcl.fct]p12: 2553 // A volatile-qualified return type is deprecated 2554 if (T.isVolatileQualified() && getLangOpts().CPlusPlus20) 2555 Diag(Loc, diag::warn_deprecated_volatile_return) << T; 2556 2557 if (T.getAddressSpace() != LangAS::Default && getLangOpts().HLSL) 2558 return true; 2559 return false; 2560 } 2561 2562 /// Check the extended parameter information. Most of the necessary 2563 /// checking should occur when applying the parameter attribute; the 2564 /// only other checks required are positional restrictions. 2565 static void checkExtParameterInfos(Sema &S, ArrayRef<QualType> paramTypes, 2566 const FunctionProtoType::ExtProtoInfo &EPI, 2567 llvm::function_ref<SourceLocation(unsigned)> getParamLoc) { 2568 assert(EPI.ExtParameterInfos && "shouldn't get here without param infos"); 2569 2570 bool emittedError = false; 2571 auto actualCC = EPI.ExtInfo.getCC(); 2572 enum class RequiredCC { OnlySwift, SwiftOrSwiftAsync }; 2573 auto checkCompatible = [&](unsigned paramIndex, RequiredCC required) { 2574 bool isCompatible = 2575 (required == RequiredCC::OnlySwift) 2576 ? (actualCC == CC_Swift) 2577 : (actualCC == CC_Swift || actualCC == CC_SwiftAsync); 2578 if (isCompatible || emittedError) 2579 return; 2580 S.Diag(getParamLoc(paramIndex), diag::err_swift_param_attr_not_swiftcall) 2581 << getParameterABISpelling(EPI.ExtParameterInfos[paramIndex].getABI()) 2582 << (required == RequiredCC::OnlySwift); 2583 emittedError = true; 2584 }; 2585 for (size_t paramIndex = 0, numParams = paramTypes.size(); 2586 paramIndex != numParams; ++paramIndex) { 2587 switch (EPI.ExtParameterInfos[paramIndex].getABI()) { 2588 // Nothing interesting to check for orindary-ABI parameters. 2589 case ParameterABI::Ordinary: 2590 case ParameterABI::HLSLOut: 2591 case ParameterABI::HLSLInOut: 2592 continue; 2593 2594 // swift_indirect_result parameters must be a prefix of the function 2595 // arguments. 2596 case ParameterABI::SwiftIndirectResult: 2597 checkCompatible(paramIndex, RequiredCC::SwiftOrSwiftAsync); 2598 if (paramIndex != 0 && 2599 EPI.ExtParameterInfos[paramIndex - 1].getABI() 2600 != ParameterABI::SwiftIndirectResult) { 2601 S.Diag(getParamLoc(paramIndex), 2602 diag::err_swift_indirect_result_not_first); 2603 } 2604 continue; 2605 2606 case ParameterABI::SwiftContext: 2607 checkCompatible(paramIndex, RequiredCC::SwiftOrSwiftAsync); 2608 continue; 2609 2610 // SwiftAsyncContext is not limited to swiftasynccall functions. 2611 case ParameterABI::SwiftAsyncContext: 2612 continue; 2613 2614 // swift_error parameters must be preceded by a swift_context parameter. 2615 case ParameterABI::SwiftErrorResult: 2616 checkCompatible(paramIndex, RequiredCC::OnlySwift); 2617 if (paramIndex == 0 || 2618 EPI.ExtParameterInfos[paramIndex - 1].getABI() != 2619 ParameterABI::SwiftContext) { 2620 S.Diag(getParamLoc(paramIndex), 2621 diag::err_swift_error_result_not_after_swift_context); 2622 } 2623 continue; 2624 } 2625 llvm_unreachable("bad ABI kind"); 2626 } 2627 } 2628 2629 QualType Sema::BuildFunctionType(QualType T, 2630 MutableArrayRef<QualType> ParamTypes, 2631 SourceLocation Loc, DeclarationName Entity, 2632 const FunctionProtoType::ExtProtoInfo &EPI) { 2633 bool Invalid = false; 2634 2635 Invalid |= CheckFunctionReturnType(T, Loc); 2636 2637 for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) { 2638 // FIXME: Loc is too inprecise here, should use proper locations for args. 2639 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]); 2640 if (ParamType->isVoidType()) { 2641 Diag(Loc, diag::err_param_with_void_type); 2642 Invalid = true; 2643 } else if (ParamType->isHalfType() && !getLangOpts().NativeHalfArgsAndReturns && 2644 !Context.getTargetInfo().allowHalfArgsAndReturns()) { 2645 // Disallow half FP arguments. 2646 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 << 2647 FixItHint::CreateInsertion(Loc, "*"); 2648 Invalid = true; 2649 } else if (ParamType->isWebAssemblyTableType()) { 2650 Diag(Loc, diag::err_wasm_table_as_function_parameter); 2651 Invalid = true; 2652 } 2653 2654 // C++2a [dcl.fct]p4: 2655 // A parameter with volatile-qualified type is deprecated 2656 if (ParamType.isVolatileQualified() && getLangOpts().CPlusPlus20) 2657 Diag(Loc, diag::warn_deprecated_volatile_param) << ParamType; 2658 2659 ParamTypes[Idx] = ParamType; 2660 } 2661 2662 if (EPI.ExtParameterInfos) { 2663 checkExtParameterInfos(*this, ParamTypes, EPI, 2664 [=](unsigned i) { return Loc; }); 2665 } 2666 2667 if (EPI.ExtInfo.getProducesResult()) { 2668 // This is just a warning, so we can't fail to build if we see it. 2669 ObjC().checkNSReturnsRetainedReturnType(Loc, T); 2670 } 2671 2672 if (Invalid) 2673 return QualType(); 2674 2675 return Context.getFunctionType(T, ParamTypes, EPI); 2676 } 2677 2678 QualType Sema::BuildMemberPointerType(QualType T, QualType Class, 2679 SourceLocation Loc, 2680 DeclarationName Entity) { 2681 // Verify that we're not building a pointer to pointer to function with 2682 // exception specification. 2683 if (CheckDistantExceptionSpec(T)) { 2684 Diag(Loc, diag::err_distant_exception_spec); 2685 return QualType(); 2686 } 2687 2688 // C++ 8.3.3p3: A pointer to member shall not point to ... a member 2689 // with reference type, or "cv void." 2690 if (T->isReferenceType()) { 2691 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference) 2692 << getPrintableNameForEntity(Entity) << T; 2693 return QualType(); 2694 } 2695 2696 if (T->isVoidType()) { 2697 Diag(Loc, diag::err_illegal_decl_mempointer_to_void) 2698 << getPrintableNameForEntity(Entity); 2699 return QualType(); 2700 } 2701 2702 if (!Class->isDependentType() && !Class->isRecordType()) { 2703 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class; 2704 return QualType(); 2705 } 2706 2707 if (T->isFunctionType() && getLangOpts().OpenCL && 2708 !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers", 2709 getLangOpts())) { 2710 Diag(Loc, diag::err_opencl_function_pointer) << /*pointer*/ 0; 2711 return QualType(); 2712 } 2713 2714 if (getLangOpts().HLSL && Loc.isValid()) { 2715 Diag(Loc, diag::err_hlsl_pointers_unsupported) << 0; 2716 return QualType(); 2717 } 2718 2719 // Adjust the default free function calling convention to the default method 2720 // calling convention. 2721 bool IsCtorOrDtor = 2722 (Entity.getNameKind() == DeclarationName::CXXConstructorName) || 2723 (Entity.getNameKind() == DeclarationName::CXXDestructorName); 2724 if (T->isFunctionType()) 2725 adjustMemberFunctionCC(T, /*HasThisPointer=*/true, IsCtorOrDtor, Loc); 2726 2727 return Context.getMemberPointerType(T, Class.getTypePtr()); 2728 } 2729 2730 QualType Sema::BuildBlockPointerType(QualType T, 2731 SourceLocation Loc, 2732 DeclarationName Entity) { 2733 if (!T->isFunctionType()) { 2734 Diag(Loc, diag::err_nonfunction_block_type); 2735 return QualType(); 2736 } 2737 2738 if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer)) 2739 return QualType(); 2740 2741 if (getLangOpts().OpenCL) 2742 T = deduceOpenCLPointeeAddrSpace(*this, T); 2743 2744 return Context.getBlockPointerType(T); 2745 } 2746 2747 QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) { 2748 QualType QT = Ty.get(); 2749 if (QT.isNull()) { 2750 if (TInfo) *TInfo = nullptr; 2751 return QualType(); 2752 } 2753 2754 TypeSourceInfo *DI = nullptr; 2755 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) { 2756 QT = LIT->getType(); 2757 DI = LIT->getTypeSourceInfo(); 2758 } 2759 2760 if (TInfo) *TInfo = DI; 2761 return QT; 2762 } 2763 2764 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, 2765 Qualifiers::ObjCLifetime ownership, 2766 unsigned chunkIndex); 2767 2768 /// Given that this is the declaration of a parameter under ARC, 2769 /// attempt to infer attributes and such for pointer-to-whatever 2770 /// types. 2771 static void inferARCWriteback(TypeProcessingState &state, 2772 QualType &declSpecType) { 2773 Sema &S = state.getSema(); 2774 Declarator &declarator = state.getDeclarator(); 2775 2776 // TODO: should we care about decl qualifiers? 2777 2778 // Check whether the declarator has the expected form. We walk 2779 // from the inside out in order to make the block logic work. 2780 unsigned outermostPointerIndex = 0; 2781 bool isBlockPointer = false; 2782 unsigned numPointers = 0; 2783 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { 2784 unsigned chunkIndex = i; 2785 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex); 2786 switch (chunk.Kind) { 2787 case DeclaratorChunk::Paren: 2788 // Ignore parens. 2789 break; 2790 2791 case DeclaratorChunk::Reference: 2792 case DeclaratorChunk::Pointer: 2793 // Count the number of pointers. Treat references 2794 // interchangeably as pointers; if they're mis-ordered, normal 2795 // type building will discover that. 2796 outermostPointerIndex = chunkIndex; 2797 numPointers++; 2798 break; 2799 2800 case DeclaratorChunk::BlockPointer: 2801 // If we have a pointer to block pointer, that's an acceptable 2802 // indirect reference; anything else is not an application of 2803 // the rules. 2804 if (numPointers != 1) return; 2805 numPointers++; 2806 outermostPointerIndex = chunkIndex; 2807 isBlockPointer = true; 2808 2809 // We don't care about pointer structure in return values here. 2810 goto done; 2811 2812 case DeclaratorChunk::Array: // suppress if written (id[])? 2813 case DeclaratorChunk::Function: 2814 case DeclaratorChunk::MemberPointer: 2815 case DeclaratorChunk::Pipe: 2816 return; 2817 } 2818 } 2819 done: 2820 2821 // If we have *one* pointer, then we want to throw the qualifier on 2822 // the declaration-specifiers, which means that it needs to be a 2823 // retainable object type. 2824 if (numPointers == 1) { 2825 // If it's not a retainable object type, the rule doesn't apply. 2826 if (!declSpecType->isObjCRetainableType()) return; 2827 2828 // If it already has lifetime, don't do anything. 2829 if (declSpecType.getObjCLifetime()) return; 2830 2831 // Otherwise, modify the type in-place. 2832 Qualifiers qs; 2833 2834 if (declSpecType->isObjCARCImplicitlyUnretainedType()) 2835 qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone); 2836 else 2837 qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing); 2838 declSpecType = S.Context.getQualifiedType(declSpecType, qs); 2839 2840 // If we have *two* pointers, then we want to throw the qualifier on 2841 // the outermost pointer. 2842 } else if (numPointers == 2) { 2843 // If we don't have a block pointer, we need to check whether the 2844 // declaration-specifiers gave us something that will turn into a 2845 // retainable object pointer after we slap the first pointer on it. 2846 if (!isBlockPointer && !declSpecType->isObjCObjectType()) 2847 return; 2848 2849 // Look for an explicit lifetime attribute there. 2850 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex); 2851 if (chunk.Kind != DeclaratorChunk::Pointer && 2852 chunk.Kind != DeclaratorChunk::BlockPointer) 2853 return; 2854 for (const ParsedAttr &AL : chunk.getAttrs()) 2855 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) 2856 return; 2857 2858 transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing, 2859 outermostPointerIndex); 2860 2861 // Any other number of pointers/references does not trigger the rule. 2862 } else return; 2863 2864 // TODO: mark whether we did this inference? 2865 } 2866 2867 void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, 2868 SourceLocation FallbackLoc, 2869 SourceLocation ConstQualLoc, 2870 SourceLocation VolatileQualLoc, 2871 SourceLocation RestrictQualLoc, 2872 SourceLocation AtomicQualLoc, 2873 SourceLocation UnalignedQualLoc) { 2874 if (!Quals) 2875 return; 2876 2877 struct Qual { 2878 const char *Name; 2879 unsigned Mask; 2880 SourceLocation Loc; 2881 } const QualKinds[5] = { 2882 { "const", DeclSpec::TQ_const, ConstQualLoc }, 2883 { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc }, 2884 { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc }, 2885 { "__unaligned", DeclSpec::TQ_unaligned, UnalignedQualLoc }, 2886 { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc } 2887 }; 2888 2889 SmallString<32> QualStr; 2890 unsigned NumQuals = 0; 2891 SourceLocation Loc; 2892 FixItHint FixIts[5]; 2893 2894 // Build a string naming the redundant qualifiers. 2895 for (auto &E : QualKinds) { 2896 if (Quals & E.Mask) { 2897 if (!QualStr.empty()) QualStr += ' '; 2898 QualStr += E.Name; 2899 2900 // If we have a location for the qualifier, offer a fixit. 2901 SourceLocation QualLoc = E.Loc; 2902 if (QualLoc.isValid()) { 2903 FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc); 2904 if (Loc.isInvalid() || 2905 getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc)) 2906 Loc = QualLoc; 2907 } 2908 2909 ++NumQuals; 2910 } 2911 } 2912 2913 Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID) 2914 << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3]; 2915 } 2916 2917 // Diagnose pointless type qualifiers on the return type of a function. 2918 static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy, 2919 Declarator &D, 2920 unsigned FunctionChunkIndex) { 2921 const DeclaratorChunk::FunctionTypeInfo &FTI = 2922 D.getTypeObject(FunctionChunkIndex).Fun; 2923 if (FTI.hasTrailingReturnType()) { 2924 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type, 2925 RetTy.getLocalCVRQualifiers(), 2926 FTI.getTrailingReturnTypeLoc()); 2927 return; 2928 } 2929 2930 for (unsigned OuterChunkIndex = FunctionChunkIndex + 1, 2931 End = D.getNumTypeObjects(); 2932 OuterChunkIndex != End; ++OuterChunkIndex) { 2933 DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex); 2934 switch (OuterChunk.Kind) { 2935 case DeclaratorChunk::Paren: 2936 continue; 2937 2938 case DeclaratorChunk::Pointer: { 2939 DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr; 2940 S.diagnoseIgnoredQualifiers( 2941 diag::warn_qual_return_type, 2942 PTI.TypeQuals, 2943 SourceLocation(), 2944 PTI.ConstQualLoc, 2945 PTI.VolatileQualLoc, 2946 PTI.RestrictQualLoc, 2947 PTI.AtomicQualLoc, 2948 PTI.UnalignedQualLoc); 2949 return; 2950 } 2951 2952 case DeclaratorChunk::Function: 2953 case DeclaratorChunk::BlockPointer: 2954 case DeclaratorChunk::Reference: 2955 case DeclaratorChunk::Array: 2956 case DeclaratorChunk::MemberPointer: 2957 case DeclaratorChunk::Pipe: 2958 // FIXME: We can't currently provide an accurate source location and a 2959 // fix-it hint for these. 2960 unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0; 2961 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type, 2962 RetTy.getCVRQualifiers() | AtomicQual, 2963 D.getIdentifierLoc()); 2964 return; 2965 } 2966 2967 llvm_unreachable("unknown declarator chunk kind"); 2968 } 2969 2970 // If the qualifiers come from a conversion function type, don't diagnose 2971 // them -- they're not necessarily redundant, since such a conversion 2972 // operator can be explicitly called as "x.operator const int()". 2973 if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId) 2974 return; 2975 2976 // Just parens all the way out to the decl specifiers. Diagnose any qualifiers 2977 // which are present there. 2978 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type, 2979 D.getDeclSpec().getTypeQualifiers(), 2980 D.getIdentifierLoc(), 2981 D.getDeclSpec().getConstSpecLoc(), 2982 D.getDeclSpec().getVolatileSpecLoc(), 2983 D.getDeclSpec().getRestrictSpecLoc(), 2984 D.getDeclSpec().getAtomicSpecLoc(), 2985 D.getDeclSpec().getUnalignedSpecLoc()); 2986 } 2987 2988 static std::pair<QualType, TypeSourceInfo *> 2989 InventTemplateParameter(TypeProcessingState &state, QualType T, 2990 TypeSourceInfo *TrailingTSI, AutoType *Auto, 2991 InventedTemplateParameterInfo &Info) { 2992 Sema &S = state.getSema(); 2993 Declarator &D = state.getDeclarator(); 2994 2995 const unsigned TemplateParameterDepth = Info.AutoTemplateParameterDepth; 2996 const unsigned AutoParameterPosition = Info.TemplateParams.size(); 2997 const bool IsParameterPack = D.hasEllipsis(); 2998 2999 // If auto is mentioned in a lambda parameter or abbreviated function 3000 // template context, convert it to a template parameter type. 3001 3002 // Create the TemplateTypeParmDecl here to retrieve the corresponding 3003 // template parameter type. Template parameters are temporarily added 3004 // to the TU until the associated TemplateDecl is created. 3005 TemplateTypeParmDecl *InventedTemplateParam = 3006 TemplateTypeParmDecl::Create( 3007 S.Context, S.Context.getTranslationUnitDecl(), 3008 /*KeyLoc=*/D.getDeclSpec().getTypeSpecTypeLoc(), 3009 /*NameLoc=*/D.getIdentifierLoc(), 3010 TemplateParameterDepth, AutoParameterPosition, 3011 S.InventAbbreviatedTemplateParameterTypeName( 3012 D.getIdentifier(), AutoParameterPosition), false, 3013 IsParameterPack, /*HasTypeConstraint=*/Auto->isConstrained()); 3014 InventedTemplateParam->setImplicit(); 3015 Info.TemplateParams.push_back(InventedTemplateParam); 3016 3017 // Attach type constraints to the new parameter. 3018 if (Auto->isConstrained()) { 3019 if (TrailingTSI) { 3020 // The 'auto' appears in a trailing return type we've already built; 3021 // extract its type constraints to attach to the template parameter. 3022 AutoTypeLoc AutoLoc = TrailingTSI->getTypeLoc().getContainedAutoTypeLoc(); 3023 TemplateArgumentListInfo TAL(AutoLoc.getLAngleLoc(), AutoLoc.getRAngleLoc()); 3024 bool Invalid = false; 3025 for (unsigned Idx = 0; Idx < AutoLoc.getNumArgs(); ++Idx) { 3026 if (D.getEllipsisLoc().isInvalid() && !Invalid && 3027 S.DiagnoseUnexpandedParameterPack(AutoLoc.getArgLoc(Idx), 3028 Sema::UPPC_TypeConstraint)) 3029 Invalid = true; 3030 TAL.addArgument(AutoLoc.getArgLoc(Idx)); 3031 } 3032 3033 if (!Invalid) { 3034 S.AttachTypeConstraint( 3035 AutoLoc.getNestedNameSpecifierLoc(), AutoLoc.getConceptNameInfo(), 3036 AutoLoc.getNamedConcept(), /*FoundDecl=*/AutoLoc.getFoundDecl(), 3037 AutoLoc.hasExplicitTemplateArgs() ? &TAL : nullptr, 3038 InventedTemplateParam, 3039 S.Context.getTypeDeclType(InventedTemplateParam), 3040 D.getEllipsisLoc()); 3041 } 3042 } else { 3043 // The 'auto' appears in the decl-specifiers; we've not finished forming 3044 // TypeSourceInfo for it yet. 3045 TemplateIdAnnotation *TemplateId = D.getDeclSpec().getRepAsTemplateId(); 3046 TemplateArgumentListInfo TemplateArgsInfo(TemplateId->LAngleLoc, 3047 TemplateId->RAngleLoc); 3048 bool Invalid = false; 3049 if (TemplateId->LAngleLoc.isValid()) { 3050 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 3051 TemplateId->NumArgs); 3052 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo); 3053 3054 if (D.getEllipsisLoc().isInvalid()) { 3055 for (TemplateArgumentLoc Arg : TemplateArgsInfo.arguments()) { 3056 if (S.DiagnoseUnexpandedParameterPack(Arg, 3057 Sema::UPPC_TypeConstraint)) { 3058 Invalid = true; 3059 break; 3060 } 3061 } 3062 } 3063 } 3064 if (!Invalid) { 3065 UsingShadowDecl *USD = 3066 TemplateId->Template.get().getAsUsingShadowDecl(); 3067 auto *CD = 3068 cast<ConceptDecl>(TemplateId->Template.get().getAsTemplateDecl()); 3069 S.AttachTypeConstraint( 3070 D.getDeclSpec().getTypeSpecScope().getWithLocInContext(S.Context), 3071 DeclarationNameInfo(DeclarationName(TemplateId->Name), 3072 TemplateId->TemplateNameLoc), 3073 CD, 3074 /*FoundDecl=*/ 3075 USD ? cast<NamedDecl>(USD) : CD, 3076 TemplateId->LAngleLoc.isValid() ? &TemplateArgsInfo : nullptr, 3077 InventedTemplateParam, 3078 S.Context.getTypeDeclType(InventedTemplateParam), 3079 D.getEllipsisLoc()); 3080 } 3081 } 3082 } 3083 3084 // Replace the 'auto' in the function parameter with this invented 3085 // template type parameter. 3086 // FIXME: Retain some type sugar to indicate that this was written 3087 // as 'auto'? 3088 QualType Replacement(InventedTemplateParam->getTypeForDecl(), 0); 3089 QualType NewT = state.ReplaceAutoType(T, Replacement); 3090 TypeSourceInfo *NewTSI = 3091 TrailingTSI ? S.ReplaceAutoTypeSourceInfo(TrailingTSI, Replacement) 3092 : nullptr; 3093 return {NewT, NewTSI}; 3094 } 3095 3096 static TypeSourceInfo * 3097 GetTypeSourceInfoForDeclarator(TypeProcessingState &State, 3098 QualType T, TypeSourceInfo *ReturnTypeInfo); 3099 3100 static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state, 3101 TypeSourceInfo *&ReturnTypeInfo) { 3102 Sema &SemaRef = state.getSema(); 3103 Declarator &D = state.getDeclarator(); 3104 QualType T; 3105 ReturnTypeInfo = nullptr; 3106 3107 // The TagDecl owned by the DeclSpec. 3108 TagDecl *OwnedTagDecl = nullptr; 3109 3110 switch (D.getName().getKind()) { 3111 case UnqualifiedIdKind::IK_ImplicitSelfParam: 3112 case UnqualifiedIdKind::IK_OperatorFunctionId: 3113 case UnqualifiedIdKind::IK_Identifier: 3114 case UnqualifiedIdKind::IK_LiteralOperatorId: 3115 case UnqualifiedIdKind::IK_TemplateId: 3116 T = ConvertDeclSpecToType(state); 3117 3118 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) { 3119 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 3120 // Owned declaration is embedded in declarator. 3121 OwnedTagDecl->setEmbeddedInDeclarator(true); 3122 } 3123 break; 3124 3125 case UnqualifiedIdKind::IK_ConstructorName: 3126 case UnqualifiedIdKind::IK_ConstructorTemplateId: 3127 case UnqualifiedIdKind::IK_DestructorName: 3128 // Constructors and destructors don't have return types. Use 3129 // "void" instead. 3130 T = SemaRef.Context.VoidTy; 3131 processTypeAttrs(state, T, TAL_DeclSpec, 3132 D.getMutableDeclSpec().getAttributes()); 3133 break; 3134 3135 case UnqualifiedIdKind::IK_DeductionGuideName: 3136 // Deduction guides have a trailing return type and no type in their 3137 // decl-specifier sequence. Use a placeholder return type for now. 3138 T = SemaRef.Context.DependentTy; 3139 break; 3140 3141 case UnqualifiedIdKind::IK_ConversionFunctionId: 3142 // The result type of a conversion function is the type that it 3143 // converts to. 3144 T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId, 3145 &ReturnTypeInfo); 3146 break; 3147 } 3148 3149 // Note: We don't need to distribute declaration attributes (i.e. 3150 // D.getDeclarationAttributes()) because those are always C++11 attributes, 3151 // and those don't get distributed. 3152 distributeTypeAttrsFromDeclarator( 3153 state, T, SemaRef.CUDA().IdentifyTarget(D.getAttributes())); 3154 3155 // Find the deduced type in this type. Look in the trailing return type if we 3156 // have one, otherwise in the DeclSpec type. 3157 // FIXME: The standard wording doesn't currently describe this. 3158 DeducedType *Deduced = T->getContainedDeducedType(); 3159 bool DeducedIsTrailingReturnType = false; 3160 if (Deduced && isa<AutoType>(Deduced) && D.hasTrailingReturnType()) { 3161 QualType T = SemaRef.GetTypeFromParser(D.getTrailingReturnType()); 3162 Deduced = T.isNull() ? nullptr : T->getContainedDeducedType(); 3163 DeducedIsTrailingReturnType = true; 3164 } 3165 3166 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context. 3167 if (Deduced) { 3168 AutoType *Auto = dyn_cast<AutoType>(Deduced); 3169 int Error = -1; 3170 3171 // Is this a 'auto' or 'decltype(auto)' type (as opposed to __auto_type or 3172 // class template argument deduction)? 3173 bool IsCXXAutoType = 3174 (Auto && Auto->getKeyword() != AutoTypeKeyword::GNUAutoType); 3175 bool IsDeducedReturnType = false; 3176 3177 switch (D.getContext()) { 3178 case DeclaratorContext::LambdaExpr: 3179 // Declared return type of a lambda-declarator is implicit and is always 3180 // 'auto'. 3181 break; 3182 case DeclaratorContext::ObjCParameter: 3183 case DeclaratorContext::ObjCResult: 3184 Error = 0; 3185 break; 3186 case DeclaratorContext::RequiresExpr: 3187 Error = 22; 3188 break; 3189 case DeclaratorContext::Prototype: 3190 case DeclaratorContext::LambdaExprParameter: { 3191 InventedTemplateParameterInfo *Info = nullptr; 3192 if (D.getContext() == DeclaratorContext::Prototype) { 3193 // With concepts we allow 'auto' in function parameters. 3194 if (!SemaRef.getLangOpts().CPlusPlus20 || !Auto || 3195 Auto->getKeyword() != AutoTypeKeyword::Auto) { 3196 Error = 0; 3197 break; 3198 } else if (!SemaRef.getCurScope()->isFunctionDeclarationScope()) { 3199 Error = 21; 3200 break; 3201 } 3202 3203 Info = &SemaRef.InventedParameterInfos.back(); 3204 } else { 3205 // In C++14, generic lambdas allow 'auto' in their parameters. 3206 if (!SemaRef.getLangOpts().CPlusPlus14 && Auto && 3207 Auto->getKeyword() == AutoTypeKeyword::Auto) { 3208 Error = 25; // auto not allowed in lambda parameter (before C++14) 3209 break; 3210 } else if (!Auto || Auto->getKeyword() != AutoTypeKeyword::Auto) { 3211 Error = 16; // __auto_type or decltype(auto) not allowed in lambda 3212 // parameter 3213 break; 3214 } 3215 Info = SemaRef.getCurLambda(); 3216 assert(Info && "No LambdaScopeInfo on the stack!"); 3217 } 3218 3219 // We'll deal with inventing template parameters for 'auto' in trailing 3220 // return types when we pick up the trailing return type when processing 3221 // the function chunk. 3222 if (!DeducedIsTrailingReturnType) 3223 T = InventTemplateParameter(state, T, nullptr, Auto, *Info).first; 3224 break; 3225 } 3226 case DeclaratorContext::Member: { 3227 if (D.isStaticMember() || D.isFunctionDeclarator()) 3228 break; 3229 bool Cxx = SemaRef.getLangOpts().CPlusPlus; 3230 if (isa<ObjCContainerDecl>(SemaRef.CurContext)) { 3231 Error = 6; // Interface member. 3232 } else { 3233 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) { 3234 case TagTypeKind::Enum: 3235 llvm_unreachable("unhandled tag kind"); 3236 case TagTypeKind::Struct: 3237 Error = Cxx ? 1 : 2; /* Struct member */ 3238 break; 3239 case TagTypeKind::Union: 3240 Error = Cxx ? 3 : 4; /* Union member */ 3241 break; 3242 case TagTypeKind::Class: 3243 Error = 5; /* Class member */ 3244 break; 3245 case TagTypeKind::Interface: 3246 Error = 6; /* Interface member */ 3247 break; 3248 } 3249 } 3250 if (D.getDeclSpec().isFriendSpecified()) 3251 Error = 20; // Friend type 3252 break; 3253 } 3254 case DeclaratorContext::CXXCatch: 3255 case DeclaratorContext::ObjCCatch: 3256 Error = 7; // Exception declaration 3257 break; 3258 case DeclaratorContext::TemplateParam: 3259 if (isa<DeducedTemplateSpecializationType>(Deduced) && 3260 !SemaRef.getLangOpts().CPlusPlus20) 3261 Error = 19; // Template parameter (until C++20) 3262 else if (!SemaRef.getLangOpts().CPlusPlus17) 3263 Error = 8; // Template parameter (until C++17) 3264 break; 3265 case DeclaratorContext::BlockLiteral: 3266 Error = 9; // Block literal 3267 break; 3268 case DeclaratorContext::TemplateArg: 3269 // Within a template argument list, a deduced template specialization 3270 // type will be reinterpreted as a template template argument. 3271 if (isa<DeducedTemplateSpecializationType>(Deduced) && 3272 !D.getNumTypeObjects() && 3273 D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier) 3274 break; 3275 [[fallthrough]]; 3276 case DeclaratorContext::TemplateTypeArg: 3277 Error = 10; // Template type argument 3278 break; 3279 case DeclaratorContext::AliasDecl: 3280 case DeclaratorContext::AliasTemplate: 3281 Error = 12; // Type alias 3282 break; 3283 case DeclaratorContext::TrailingReturn: 3284 case DeclaratorContext::TrailingReturnVar: 3285 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType) 3286 Error = 13; // Function return type 3287 IsDeducedReturnType = true; 3288 break; 3289 case DeclaratorContext::ConversionId: 3290 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType) 3291 Error = 14; // conversion-type-id 3292 IsDeducedReturnType = true; 3293 break; 3294 case DeclaratorContext::FunctionalCast: 3295 if (isa<DeducedTemplateSpecializationType>(Deduced)) 3296 break; 3297 if (SemaRef.getLangOpts().CPlusPlus23 && IsCXXAutoType && 3298 !Auto->isDecltypeAuto()) 3299 break; // auto(x) 3300 [[fallthrough]]; 3301 case DeclaratorContext::TypeName: 3302 case DeclaratorContext::Association: 3303 Error = 15; // Generic 3304 break; 3305 case DeclaratorContext::File: 3306 case DeclaratorContext::Block: 3307 case DeclaratorContext::ForInit: 3308 case DeclaratorContext::SelectionInit: 3309 case DeclaratorContext::Condition: 3310 // FIXME: P0091R3 (erroneously) does not permit class template argument 3311 // deduction in conditions, for-init-statements, and other declarations 3312 // that are not simple-declarations. 3313 break; 3314 case DeclaratorContext::CXXNew: 3315 // FIXME: P0091R3 does not permit class template argument deduction here, 3316 // but we follow GCC and allow it anyway. 3317 if (!IsCXXAutoType && !isa<DeducedTemplateSpecializationType>(Deduced)) 3318 Error = 17; // 'new' type 3319 break; 3320 case DeclaratorContext::KNRTypeList: 3321 Error = 18; // K&R function parameter 3322 break; 3323 } 3324 3325 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 3326 Error = 11; 3327 3328 // In Objective-C it is an error to use 'auto' on a function declarator 3329 // (and everywhere for '__auto_type'). 3330 if (D.isFunctionDeclarator() && 3331 (!SemaRef.getLangOpts().CPlusPlus11 || !IsCXXAutoType)) 3332 Error = 13; 3333 3334 SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc(); 3335 if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId) 3336 AutoRange = D.getName().getSourceRange(); 3337 3338 if (Error != -1) { 3339 unsigned Kind; 3340 if (Auto) { 3341 switch (Auto->getKeyword()) { 3342 case AutoTypeKeyword::Auto: Kind = 0; break; 3343 case AutoTypeKeyword::DecltypeAuto: Kind = 1; break; 3344 case AutoTypeKeyword::GNUAutoType: Kind = 2; break; 3345 } 3346 } else { 3347 assert(isa<DeducedTemplateSpecializationType>(Deduced) && 3348 "unknown auto type"); 3349 Kind = 3; 3350 } 3351 3352 auto *DTST = dyn_cast<DeducedTemplateSpecializationType>(Deduced); 3353 TemplateName TN = DTST ? DTST->getTemplateName() : TemplateName(); 3354 3355 SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed) 3356 << Kind << Error << (int)SemaRef.getTemplateNameKindForDiagnostics(TN) 3357 << QualType(Deduced, 0) << AutoRange; 3358 if (auto *TD = TN.getAsTemplateDecl()) 3359 SemaRef.NoteTemplateLocation(*TD); 3360 3361 T = SemaRef.Context.IntTy; 3362 D.setInvalidType(true); 3363 } else if (Auto && D.getContext() != DeclaratorContext::LambdaExpr) { 3364 // If there was a trailing return type, we already got 3365 // warn_cxx98_compat_trailing_return_type in the parser. 3366 SemaRef.Diag(AutoRange.getBegin(), 3367 D.getContext() == DeclaratorContext::LambdaExprParameter 3368 ? diag::warn_cxx11_compat_generic_lambda 3369 : IsDeducedReturnType 3370 ? diag::warn_cxx11_compat_deduced_return_type 3371 : diag::warn_cxx98_compat_auto_type_specifier) 3372 << AutoRange; 3373 } 3374 } 3375 3376 if (SemaRef.getLangOpts().CPlusPlus && 3377 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) { 3378 // Check the contexts where C++ forbids the declaration of a new class 3379 // or enumeration in a type-specifier-seq. 3380 unsigned DiagID = 0; 3381 switch (D.getContext()) { 3382 case DeclaratorContext::TrailingReturn: 3383 case DeclaratorContext::TrailingReturnVar: 3384 // Class and enumeration definitions are syntactically not allowed in 3385 // trailing return types. 3386 llvm_unreachable("parser should not have allowed this"); 3387 break; 3388 case DeclaratorContext::File: 3389 case DeclaratorContext::Member: 3390 case DeclaratorContext::Block: 3391 case DeclaratorContext::ForInit: 3392 case DeclaratorContext::SelectionInit: 3393 case DeclaratorContext::BlockLiteral: 3394 case DeclaratorContext::LambdaExpr: 3395 // C++11 [dcl.type]p3: 3396 // A type-specifier-seq shall not define a class or enumeration unless 3397 // it appears in the type-id of an alias-declaration (7.1.3) that is not 3398 // the declaration of a template-declaration. 3399 case DeclaratorContext::AliasDecl: 3400 break; 3401 case DeclaratorContext::AliasTemplate: 3402 DiagID = diag::err_type_defined_in_alias_template; 3403 break; 3404 case DeclaratorContext::TypeName: 3405 case DeclaratorContext::FunctionalCast: 3406 case DeclaratorContext::ConversionId: 3407 case DeclaratorContext::TemplateParam: 3408 case DeclaratorContext::CXXNew: 3409 case DeclaratorContext::CXXCatch: 3410 case DeclaratorContext::ObjCCatch: 3411 case DeclaratorContext::TemplateArg: 3412 case DeclaratorContext::TemplateTypeArg: 3413 case DeclaratorContext::Association: 3414 DiagID = diag::err_type_defined_in_type_specifier; 3415 break; 3416 case DeclaratorContext::Prototype: 3417 case DeclaratorContext::LambdaExprParameter: 3418 case DeclaratorContext::ObjCParameter: 3419 case DeclaratorContext::ObjCResult: 3420 case DeclaratorContext::KNRTypeList: 3421 case DeclaratorContext::RequiresExpr: 3422 // C++ [dcl.fct]p6: 3423 // Types shall not be defined in return or parameter types. 3424 DiagID = diag::err_type_defined_in_param_type; 3425 break; 3426 case DeclaratorContext::Condition: 3427 // C++ 6.4p2: 3428 // The type-specifier-seq shall not contain typedef and shall not declare 3429 // a new class or enumeration. 3430 DiagID = diag::err_type_defined_in_condition; 3431 break; 3432 } 3433 3434 if (DiagID != 0) { 3435 SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID) 3436 << SemaRef.Context.getTypeDeclType(OwnedTagDecl); 3437 D.setInvalidType(true); 3438 } 3439 } 3440 3441 assert(!T.isNull() && "This function should not return a null type"); 3442 return T; 3443 } 3444 3445 /// Produce an appropriate diagnostic for an ambiguity between a function 3446 /// declarator and a C++ direct-initializer. 3447 static void warnAboutAmbiguousFunction(Sema &S, Declarator &D, 3448 DeclaratorChunk &DeclType, QualType RT) { 3449 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 3450 assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity"); 3451 3452 // If the return type is void there is no ambiguity. 3453 if (RT->isVoidType()) 3454 return; 3455 3456 // An initializer for a non-class type can have at most one argument. 3457 if (!RT->isRecordType() && FTI.NumParams > 1) 3458 return; 3459 3460 // An initializer for a reference must have exactly one argument. 3461 if (RT->isReferenceType() && FTI.NumParams != 1) 3462 return; 3463 3464 // Only warn if this declarator is declaring a function at block scope, and 3465 // doesn't have a storage class (such as 'extern') specified. 3466 if (!D.isFunctionDeclarator() || 3467 D.getFunctionDefinitionKind() != FunctionDefinitionKind::Declaration || 3468 !S.CurContext->isFunctionOrMethod() || 3469 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_unspecified) 3470 return; 3471 3472 // Inside a condition, a direct initializer is not permitted. We allow one to 3473 // be parsed in order to give better diagnostics in condition parsing. 3474 if (D.getContext() == DeclaratorContext::Condition) 3475 return; 3476 3477 SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc); 3478 3479 S.Diag(DeclType.Loc, 3480 FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration 3481 : diag::warn_empty_parens_are_function_decl) 3482 << ParenRange; 3483 3484 // If the declaration looks like: 3485 // T var1, 3486 // f(); 3487 // and name lookup finds a function named 'f', then the ',' was 3488 // probably intended to be a ';'. 3489 if (!D.isFirstDeclarator() && D.getIdentifier()) { 3490 FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr); 3491 FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr); 3492 if (Comma.getFileID() != Name.getFileID() || 3493 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) { 3494 LookupResult Result(S, D.getIdentifier(), SourceLocation(), 3495 Sema::LookupOrdinaryName); 3496 if (S.LookupName(Result, S.getCurScope())) 3497 S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call) 3498 << FixItHint::CreateReplacement(D.getCommaLoc(), ";") 3499 << D.getIdentifier(); 3500 Result.suppressDiagnostics(); 3501 } 3502 } 3503 3504 if (FTI.NumParams > 0) { 3505 // For a declaration with parameters, eg. "T var(T());", suggest adding 3506 // parens around the first parameter to turn the declaration into a 3507 // variable declaration. 3508 SourceRange Range = FTI.Params[0].Param->getSourceRange(); 3509 SourceLocation B = Range.getBegin(); 3510 SourceLocation E = S.getLocForEndOfToken(Range.getEnd()); 3511 // FIXME: Maybe we should suggest adding braces instead of parens 3512 // in C++11 for classes that don't have an initializer_list constructor. 3513 S.Diag(B, diag::note_additional_parens_for_variable_declaration) 3514 << FixItHint::CreateInsertion(B, "(") 3515 << FixItHint::CreateInsertion(E, ")"); 3516 } else { 3517 // For a declaration without parameters, eg. "T var();", suggest replacing 3518 // the parens with an initializer to turn the declaration into a variable 3519 // declaration. 3520 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl(); 3521 3522 // Empty parens mean value-initialization, and no parens mean 3523 // default initialization. These are equivalent if the default 3524 // constructor is user-provided or if zero-initialization is a 3525 // no-op. 3526 if (RD && RD->hasDefinition() && 3527 (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor())) 3528 S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor) 3529 << FixItHint::CreateRemoval(ParenRange); 3530 else { 3531 std::string Init = 3532 S.getFixItZeroInitializerForType(RT, ParenRange.getBegin()); 3533 if (Init.empty() && S.LangOpts.CPlusPlus11) 3534 Init = "{}"; 3535 if (!Init.empty()) 3536 S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize) 3537 << FixItHint::CreateReplacement(ParenRange, Init); 3538 } 3539 } 3540 } 3541 3542 /// Produce an appropriate diagnostic for a declarator with top-level 3543 /// parentheses. 3544 static void warnAboutRedundantParens(Sema &S, Declarator &D, QualType T) { 3545 DeclaratorChunk &Paren = D.getTypeObject(D.getNumTypeObjects() - 1); 3546 assert(Paren.Kind == DeclaratorChunk::Paren && 3547 "do not have redundant top-level parentheses"); 3548 3549 // This is a syntactic check; we're not interested in cases that arise 3550 // during template instantiation. 3551 if (S.inTemplateInstantiation()) 3552 return; 3553 3554 // Check whether this could be intended to be a construction of a temporary 3555 // object in C++ via a function-style cast. 3556 bool CouldBeTemporaryObject = 3557 S.getLangOpts().CPlusPlus && D.isExpressionContext() && 3558 !D.isInvalidType() && D.getIdentifier() && 3559 D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier && 3560 (T->isRecordType() || T->isDependentType()) && 3561 D.getDeclSpec().getTypeQualifiers() == 0 && D.isFirstDeclarator(); 3562 3563 bool StartsWithDeclaratorId = true; 3564 for (auto &C : D.type_objects()) { 3565 switch (C.Kind) { 3566 case DeclaratorChunk::Paren: 3567 if (&C == &Paren) 3568 continue; 3569 [[fallthrough]]; 3570 case DeclaratorChunk::Pointer: 3571 StartsWithDeclaratorId = false; 3572 continue; 3573 3574 case DeclaratorChunk::Array: 3575 if (!C.Arr.NumElts) 3576 CouldBeTemporaryObject = false; 3577 continue; 3578 3579 case DeclaratorChunk::Reference: 3580 // FIXME: Suppress the warning here if there is no initializer; we're 3581 // going to give an error anyway. 3582 // We assume that something like 'T (&x) = y;' is highly likely to not 3583 // be intended to be a temporary object. 3584 CouldBeTemporaryObject = false; 3585 StartsWithDeclaratorId = false; 3586 continue; 3587 3588 case DeclaratorChunk::Function: 3589 // In a new-type-id, function chunks require parentheses. 3590 if (D.getContext() == DeclaratorContext::CXXNew) 3591 return; 3592 // FIXME: "A(f())" deserves a vexing-parse warning, not just a 3593 // redundant-parens warning, but we don't know whether the function 3594 // chunk was syntactically valid as an expression here. 3595 CouldBeTemporaryObject = false; 3596 continue; 3597 3598 case DeclaratorChunk::BlockPointer: 3599 case DeclaratorChunk::MemberPointer: 3600 case DeclaratorChunk::Pipe: 3601 // These cannot appear in expressions. 3602 CouldBeTemporaryObject = false; 3603 StartsWithDeclaratorId = false; 3604 continue; 3605 } 3606 } 3607 3608 // FIXME: If there is an initializer, assume that this is not intended to be 3609 // a construction of a temporary object. 3610 3611 // Check whether the name has already been declared; if not, this is not a 3612 // function-style cast. 3613 if (CouldBeTemporaryObject) { 3614 LookupResult Result(S, D.getIdentifier(), SourceLocation(), 3615 Sema::LookupOrdinaryName); 3616 if (!S.LookupName(Result, S.getCurScope())) 3617 CouldBeTemporaryObject = false; 3618 Result.suppressDiagnostics(); 3619 } 3620 3621 SourceRange ParenRange(Paren.Loc, Paren.EndLoc); 3622 3623 if (!CouldBeTemporaryObject) { 3624 // If we have A (::B), the parentheses affect the meaning of the program. 3625 // Suppress the warning in that case. Don't bother looking at the DeclSpec 3626 // here: even (e.g.) "int ::x" is visually ambiguous even though it's 3627 // formally unambiguous. 3628 if (StartsWithDeclaratorId && D.getCXXScopeSpec().isValid()) { 3629 for (NestedNameSpecifier *NNS = D.getCXXScopeSpec().getScopeRep(); NNS; 3630 NNS = NNS->getPrefix()) { 3631 if (NNS->getKind() == NestedNameSpecifier::Global) 3632 return; 3633 } 3634 } 3635 3636 S.Diag(Paren.Loc, diag::warn_redundant_parens_around_declarator) 3637 << ParenRange << FixItHint::CreateRemoval(Paren.Loc) 3638 << FixItHint::CreateRemoval(Paren.EndLoc); 3639 return; 3640 } 3641 3642 S.Diag(Paren.Loc, diag::warn_parens_disambiguated_as_variable_declaration) 3643 << ParenRange << D.getIdentifier(); 3644 auto *RD = T->getAsCXXRecordDecl(); 3645 if (!RD || !RD->hasDefinition() || RD->hasNonTrivialDestructor()) 3646 S.Diag(Paren.Loc, diag::note_raii_guard_add_name) 3647 << FixItHint::CreateInsertion(Paren.Loc, " varname") << T 3648 << D.getIdentifier(); 3649 // FIXME: A cast to void is probably a better suggestion in cases where it's 3650 // valid (when there is no initializer and we're not in a condition). 3651 S.Diag(D.getBeginLoc(), diag::note_function_style_cast_add_parentheses) 3652 << FixItHint::CreateInsertion(D.getBeginLoc(), "(") 3653 << FixItHint::CreateInsertion(S.getLocForEndOfToken(D.getEndLoc()), ")"); 3654 S.Diag(Paren.Loc, diag::note_remove_parens_for_variable_declaration) 3655 << FixItHint::CreateRemoval(Paren.Loc) 3656 << FixItHint::CreateRemoval(Paren.EndLoc); 3657 } 3658 3659 /// Helper for figuring out the default CC for a function declarator type. If 3660 /// this is the outermost chunk, then we can determine the CC from the 3661 /// declarator context. If not, then this could be either a member function 3662 /// type or normal function type. 3663 static CallingConv getCCForDeclaratorChunk( 3664 Sema &S, Declarator &D, const ParsedAttributesView &AttrList, 3665 const DeclaratorChunk::FunctionTypeInfo &FTI, unsigned ChunkIndex) { 3666 assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function); 3667 3668 // Check for an explicit CC attribute. 3669 for (const ParsedAttr &AL : AttrList) { 3670 switch (AL.getKind()) { 3671 CALLING_CONV_ATTRS_CASELIST : { 3672 // Ignore attributes that don't validate or can't apply to the 3673 // function type. We'll diagnose the failure to apply them in 3674 // handleFunctionTypeAttr. 3675 CallingConv CC; 3676 if (!S.CheckCallingConvAttr(AL, CC, /*FunctionDecl=*/nullptr, 3677 S.CUDA().IdentifyTarget(D.getAttributes())) && 3678 (!FTI.isVariadic || supportsVariadicCall(CC))) { 3679 return CC; 3680 } 3681 break; 3682 } 3683 3684 default: 3685 break; 3686 } 3687 } 3688 3689 bool IsCXXInstanceMethod = false; 3690 3691 if (S.getLangOpts().CPlusPlus) { 3692 // Look inwards through parentheses to see if this chunk will form a 3693 // member pointer type or if we're the declarator. Any type attributes 3694 // between here and there will override the CC we choose here. 3695 unsigned I = ChunkIndex; 3696 bool FoundNonParen = false; 3697 while (I && !FoundNonParen) { 3698 --I; 3699 if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren) 3700 FoundNonParen = true; 3701 } 3702 3703 if (FoundNonParen) { 3704 // If we're not the declarator, we're a regular function type unless we're 3705 // in a member pointer. 3706 IsCXXInstanceMethod = 3707 D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer; 3708 } else if (D.getContext() == DeclaratorContext::LambdaExpr) { 3709 // This can only be a call operator for a lambda, which is an instance 3710 // method, unless explicitly specified as 'static'. 3711 IsCXXInstanceMethod = 3712 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static; 3713 } else { 3714 // We're the innermost decl chunk, so must be a function declarator. 3715 assert(D.isFunctionDeclarator()); 3716 3717 // If we're inside a record, we're declaring a method, but it could be 3718 // explicitly or implicitly static. 3719 IsCXXInstanceMethod = 3720 D.isFirstDeclarationOfMember() && 3721 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 3722 !D.isStaticMember(); 3723 } 3724 } 3725 3726 CallingConv CC = S.Context.getDefaultCallingConvention(FTI.isVariadic, 3727 IsCXXInstanceMethod); 3728 3729 // Attribute AT_OpenCLKernel affects the calling convention for SPIR 3730 // and AMDGPU targets, hence it cannot be treated as a calling 3731 // convention attribute. This is the simplest place to infer 3732 // calling convention for OpenCL kernels. 3733 if (S.getLangOpts().OpenCL) { 3734 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) { 3735 if (AL.getKind() == ParsedAttr::AT_OpenCLKernel) { 3736 CC = CC_OpenCLKernel; 3737 break; 3738 } 3739 } 3740 } else if (S.getLangOpts().CUDA) { 3741 // If we're compiling CUDA/HIP code and targeting HIPSPV we need to make 3742 // sure the kernels will be marked with the right calling convention so that 3743 // they will be visible by the APIs that ingest SPIR-V. We do not do this 3744 // when targeting AMDGCNSPIRV, as it does not rely on OpenCL. 3745 llvm::Triple Triple = S.Context.getTargetInfo().getTriple(); 3746 if (Triple.isSPIRV() && Triple.getVendor() != llvm::Triple::AMD) { 3747 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) { 3748 if (AL.getKind() == ParsedAttr::AT_CUDAGlobal) { 3749 CC = CC_OpenCLKernel; 3750 break; 3751 } 3752 } 3753 } 3754 } 3755 3756 return CC; 3757 } 3758 3759 namespace { 3760 /// A simple notion of pointer kinds, which matches up with the various 3761 /// pointer declarators. 3762 enum class SimplePointerKind { 3763 Pointer, 3764 BlockPointer, 3765 MemberPointer, 3766 Array, 3767 }; 3768 } // end anonymous namespace 3769 3770 IdentifierInfo *Sema::getNullabilityKeyword(NullabilityKind nullability) { 3771 switch (nullability) { 3772 case NullabilityKind::NonNull: 3773 if (!Ident__Nonnull) 3774 Ident__Nonnull = PP.getIdentifierInfo("_Nonnull"); 3775 return Ident__Nonnull; 3776 3777 case NullabilityKind::Nullable: 3778 if (!Ident__Nullable) 3779 Ident__Nullable = PP.getIdentifierInfo("_Nullable"); 3780 return Ident__Nullable; 3781 3782 case NullabilityKind::NullableResult: 3783 if (!Ident__Nullable_result) 3784 Ident__Nullable_result = PP.getIdentifierInfo("_Nullable_result"); 3785 return Ident__Nullable_result; 3786 3787 case NullabilityKind::Unspecified: 3788 if (!Ident__Null_unspecified) 3789 Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified"); 3790 return Ident__Null_unspecified; 3791 } 3792 llvm_unreachable("Unknown nullability kind."); 3793 } 3794 3795 /// Check whether there is a nullability attribute of any kind in the given 3796 /// attribute list. 3797 static bool hasNullabilityAttr(const ParsedAttributesView &attrs) { 3798 for (const ParsedAttr &AL : attrs) { 3799 if (AL.getKind() == ParsedAttr::AT_TypeNonNull || 3800 AL.getKind() == ParsedAttr::AT_TypeNullable || 3801 AL.getKind() == ParsedAttr::AT_TypeNullableResult || 3802 AL.getKind() == ParsedAttr::AT_TypeNullUnspecified) 3803 return true; 3804 } 3805 3806 return false; 3807 } 3808 3809 namespace { 3810 /// Describes the kind of a pointer a declarator describes. 3811 enum class PointerDeclaratorKind { 3812 // Not a pointer. 3813 NonPointer, 3814 // Single-level pointer. 3815 SingleLevelPointer, 3816 // Multi-level pointer (of any pointer kind). 3817 MultiLevelPointer, 3818 // CFFooRef* 3819 MaybePointerToCFRef, 3820 // CFErrorRef* 3821 CFErrorRefPointer, 3822 // NSError** 3823 NSErrorPointerPointer, 3824 }; 3825 3826 /// Describes a declarator chunk wrapping a pointer that marks inference as 3827 /// unexpected. 3828 // These values must be kept in sync with diagnostics. 3829 enum class PointerWrappingDeclaratorKind { 3830 /// Pointer is top-level. 3831 None = -1, 3832 /// Pointer is an array element. 3833 Array = 0, 3834 /// Pointer is the referent type of a C++ reference. 3835 Reference = 1 3836 }; 3837 } // end anonymous namespace 3838 3839 /// Classify the given declarator, whose type-specified is \c type, based on 3840 /// what kind of pointer it refers to. 3841 /// 3842 /// This is used to determine the default nullability. 3843 static PointerDeclaratorKind 3844 classifyPointerDeclarator(Sema &S, QualType type, Declarator &declarator, 3845 PointerWrappingDeclaratorKind &wrappingKind) { 3846 unsigned numNormalPointers = 0; 3847 3848 // For any dependent type, we consider it a non-pointer. 3849 if (type->isDependentType()) 3850 return PointerDeclaratorKind::NonPointer; 3851 3852 // Look through the declarator chunks to identify pointers. 3853 for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) { 3854 DeclaratorChunk &chunk = declarator.getTypeObject(i); 3855 switch (chunk.Kind) { 3856 case DeclaratorChunk::Array: 3857 if (numNormalPointers == 0) 3858 wrappingKind = PointerWrappingDeclaratorKind::Array; 3859 break; 3860 3861 case DeclaratorChunk::Function: 3862 case DeclaratorChunk::Pipe: 3863 break; 3864 3865 case DeclaratorChunk::BlockPointer: 3866 case DeclaratorChunk::MemberPointer: 3867 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer 3868 : PointerDeclaratorKind::SingleLevelPointer; 3869 3870 case DeclaratorChunk::Paren: 3871 break; 3872 3873 case DeclaratorChunk::Reference: 3874 if (numNormalPointers == 0) 3875 wrappingKind = PointerWrappingDeclaratorKind::Reference; 3876 break; 3877 3878 case DeclaratorChunk::Pointer: 3879 ++numNormalPointers; 3880 if (numNormalPointers > 2) 3881 return PointerDeclaratorKind::MultiLevelPointer; 3882 break; 3883 } 3884 } 3885 3886 // Then, dig into the type specifier itself. 3887 unsigned numTypeSpecifierPointers = 0; 3888 do { 3889 // Decompose normal pointers. 3890 if (auto ptrType = type->getAs<PointerType>()) { 3891 ++numNormalPointers; 3892 3893 if (numNormalPointers > 2) 3894 return PointerDeclaratorKind::MultiLevelPointer; 3895 3896 type = ptrType->getPointeeType(); 3897 ++numTypeSpecifierPointers; 3898 continue; 3899 } 3900 3901 // Decompose block pointers. 3902 if (type->getAs<BlockPointerType>()) { 3903 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer 3904 : PointerDeclaratorKind::SingleLevelPointer; 3905 } 3906 3907 // Decompose member pointers. 3908 if (type->getAs<MemberPointerType>()) { 3909 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer 3910 : PointerDeclaratorKind::SingleLevelPointer; 3911 } 3912 3913 // Look at Objective-C object pointers. 3914 if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) { 3915 ++numNormalPointers; 3916 ++numTypeSpecifierPointers; 3917 3918 // If this is NSError**, report that. 3919 if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) { 3920 if (objcClassDecl->getIdentifier() == S.ObjC().getNSErrorIdent() && 3921 numNormalPointers == 2 && numTypeSpecifierPointers < 2) { 3922 return PointerDeclaratorKind::NSErrorPointerPointer; 3923 } 3924 } 3925 3926 break; 3927 } 3928 3929 // Look at Objective-C class types. 3930 if (auto objcClass = type->getAs<ObjCInterfaceType>()) { 3931 if (objcClass->getInterface()->getIdentifier() == 3932 S.ObjC().getNSErrorIdent()) { 3933 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2) 3934 return PointerDeclaratorKind::NSErrorPointerPointer; 3935 } 3936 3937 break; 3938 } 3939 3940 // If at this point we haven't seen a pointer, we won't see one. 3941 if (numNormalPointers == 0) 3942 return PointerDeclaratorKind::NonPointer; 3943 3944 if (auto recordType = type->getAs<RecordType>()) { 3945 RecordDecl *recordDecl = recordType->getDecl(); 3946 3947 // If this is CFErrorRef*, report it as such. 3948 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2 && 3949 S.ObjC().isCFError(recordDecl)) { 3950 return PointerDeclaratorKind::CFErrorRefPointer; 3951 } 3952 break; 3953 } 3954 3955 break; 3956 } while (true); 3957 3958 switch (numNormalPointers) { 3959 case 0: 3960 return PointerDeclaratorKind::NonPointer; 3961 3962 case 1: 3963 return PointerDeclaratorKind::SingleLevelPointer; 3964 3965 case 2: 3966 return PointerDeclaratorKind::MaybePointerToCFRef; 3967 3968 default: 3969 return PointerDeclaratorKind::MultiLevelPointer; 3970 } 3971 } 3972 3973 static FileID getNullabilityCompletenessCheckFileID(Sema &S, 3974 SourceLocation loc) { 3975 // If we're anywhere in a function, method, or closure context, don't perform 3976 // completeness checks. 3977 for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) { 3978 if (ctx->isFunctionOrMethod()) 3979 return FileID(); 3980 3981 if (ctx->isFileContext()) 3982 break; 3983 } 3984 3985 // We only care about the expansion location. 3986 loc = S.SourceMgr.getExpansionLoc(loc); 3987 FileID file = S.SourceMgr.getFileID(loc); 3988 if (file.isInvalid()) 3989 return FileID(); 3990 3991 // Retrieve file information. 3992 bool invalid = false; 3993 const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid); 3994 if (invalid || !sloc.isFile()) 3995 return FileID(); 3996 3997 // We don't want to perform completeness checks on the main file or in 3998 // system headers. 3999 const SrcMgr::FileInfo &fileInfo = sloc.getFile(); 4000 if (fileInfo.getIncludeLoc().isInvalid()) 4001 return FileID(); 4002 if (fileInfo.getFileCharacteristic() != SrcMgr::C_User && 4003 S.Diags.getSuppressSystemWarnings()) { 4004 return FileID(); 4005 } 4006 4007 return file; 4008 } 4009 4010 /// Creates a fix-it to insert a C-style nullability keyword at \p pointerLoc, 4011 /// taking into account whitespace before and after. 4012 template <typename DiagBuilderT> 4013 static void fixItNullability(Sema &S, DiagBuilderT &Diag, 4014 SourceLocation PointerLoc, 4015 NullabilityKind Nullability) { 4016 assert(PointerLoc.isValid()); 4017 if (PointerLoc.isMacroID()) 4018 return; 4019 4020 SourceLocation FixItLoc = S.getLocForEndOfToken(PointerLoc); 4021 if (!FixItLoc.isValid() || FixItLoc == PointerLoc) 4022 return; 4023 4024 const char *NextChar = S.SourceMgr.getCharacterData(FixItLoc); 4025 if (!NextChar) 4026 return; 4027 4028 SmallString<32> InsertionTextBuf{" "}; 4029 InsertionTextBuf += getNullabilitySpelling(Nullability); 4030 InsertionTextBuf += " "; 4031 StringRef InsertionText = InsertionTextBuf.str(); 4032 4033 if (isWhitespace(*NextChar)) { 4034 InsertionText = InsertionText.drop_back(); 4035 } else if (NextChar[-1] == '[') { 4036 if (NextChar[0] == ']') 4037 InsertionText = InsertionText.drop_back().drop_front(); 4038 else 4039 InsertionText = InsertionText.drop_front(); 4040 } else if (!isAsciiIdentifierContinue(NextChar[0], /*allow dollar*/ true) && 4041 !isAsciiIdentifierContinue(NextChar[-1], /*allow dollar*/ true)) { 4042 InsertionText = InsertionText.drop_back().drop_front(); 4043 } 4044 4045 Diag << FixItHint::CreateInsertion(FixItLoc, InsertionText); 4046 } 4047 4048 static void emitNullabilityConsistencyWarning(Sema &S, 4049 SimplePointerKind PointerKind, 4050 SourceLocation PointerLoc, 4051 SourceLocation PointerEndLoc) { 4052 assert(PointerLoc.isValid()); 4053 4054 if (PointerKind == SimplePointerKind::Array) { 4055 S.Diag(PointerLoc, diag::warn_nullability_missing_array); 4056 } else { 4057 S.Diag(PointerLoc, diag::warn_nullability_missing) 4058 << static_cast<unsigned>(PointerKind); 4059 } 4060 4061 auto FixItLoc = PointerEndLoc.isValid() ? PointerEndLoc : PointerLoc; 4062 if (FixItLoc.isMacroID()) 4063 return; 4064 4065 auto addFixIt = [&](NullabilityKind Nullability) { 4066 auto Diag = S.Diag(FixItLoc, diag::note_nullability_fix_it); 4067 Diag << static_cast<unsigned>(Nullability); 4068 Diag << static_cast<unsigned>(PointerKind); 4069 fixItNullability(S, Diag, FixItLoc, Nullability); 4070 }; 4071 addFixIt(NullabilityKind::Nullable); 4072 addFixIt(NullabilityKind::NonNull); 4073 } 4074 4075 /// Complains about missing nullability if the file containing \p pointerLoc 4076 /// has other uses of nullability (either the keywords or the \c assume_nonnull 4077 /// pragma). 4078 /// 4079 /// If the file has \e not seen other uses of nullability, this particular 4080 /// pointer is saved for possible later diagnosis. See recordNullabilitySeen(). 4081 static void 4082 checkNullabilityConsistency(Sema &S, SimplePointerKind pointerKind, 4083 SourceLocation pointerLoc, 4084 SourceLocation pointerEndLoc = SourceLocation()) { 4085 // Determine which file we're performing consistency checking for. 4086 FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc); 4087 if (file.isInvalid()) 4088 return; 4089 4090 // If we haven't seen any type nullability in this file, we won't warn now 4091 // about anything. 4092 FileNullability &fileNullability = S.NullabilityMap[file]; 4093 if (!fileNullability.SawTypeNullability) { 4094 // If this is the first pointer declarator in the file, and the appropriate 4095 // warning is on, record it in case we need to diagnose it retroactively. 4096 diag::kind diagKind; 4097 if (pointerKind == SimplePointerKind::Array) 4098 diagKind = diag::warn_nullability_missing_array; 4099 else 4100 diagKind = diag::warn_nullability_missing; 4101 4102 if (fileNullability.PointerLoc.isInvalid() && 4103 !S.Context.getDiagnostics().isIgnored(diagKind, pointerLoc)) { 4104 fileNullability.PointerLoc = pointerLoc; 4105 fileNullability.PointerEndLoc = pointerEndLoc; 4106 fileNullability.PointerKind = static_cast<unsigned>(pointerKind); 4107 } 4108 4109 return; 4110 } 4111 4112 // Complain about missing nullability. 4113 emitNullabilityConsistencyWarning(S, pointerKind, pointerLoc, pointerEndLoc); 4114 } 4115 4116 /// Marks that a nullability feature has been used in the file containing 4117 /// \p loc. 4118 /// 4119 /// If this file already had pointer types in it that were missing nullability, 4120 /// the first such instance is retroactively diagnosed. 4121 /// 4122 /// \sa checkNullabilityConsistency 4123 static void recordNullabilitySeen(Sema &S, SourceLocation loc) { 4124 FileID file = getNullabilityCompletenessCheckFileID(S, loc); 4125 if (file.isInvalid()) 4126 return; 4127 4128 FileNullability &fileNullability = S.NullabilityMap[file]; 4129 if (fileNullability.SawTypeNullability) 4130 return; 4131 fileNullability.SawTypeNullability = true; 4132 4133 // If we haven't seen any type nullability before, now we have. Retroactively 4134 // diagnose the first unannotated pointer, if there was one. 4135 if (fileNullability.PointerLoc.isInvalid()) 4136 return; 4137 4138 auto kind = static_cast<SimplePointerKind>(fileNullability.PointerKind); 4139 emitNullabilityConsistencyWarning(S, kind, fileNullability.PointerLoc, 4140 fileNullability.PointerEndLoc); 4141 } 4142 4143 /// Returns true if any of the declarator chunks before \p endIndex include a 4144 /// level of indirection: array, pointer, reference, or pointer-to-member. 4145 /// 4146 /// Because declarator chunks are stored in outer-to-inner order, testing 4147 /// every chunk before \p endIndex is testing all chunks that embed the current 4148 /// chunk as part of their type. 4149 /// 4150 /// It is legal to pass the result of Declarator::getNumTypeObjects() as the 4151 /// end index, in which case all chunks are tested. 4152 static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex) { 4153 unsigned i = endIndex; 4154 while (i != 0) { 4155 // Walk outwards along the declarator chunks. 4156 --i; 4157 const DeclaratorChunk &DC = D.getTypeObject(i); 4158 switch (DC.Kind) { 4159 case DeclaratorChunk::Paren: 4160 break; 4161 case DeclaratorChunk::Array: 4162 case DeclaratorChunk::Pointer: 4163 case DeclaratorChunk::Reference: 4164 case DeclaratorChunk::MemberPointer: 4165 return true; 4166 case DeclaratorChunk::Function: 4167 case DeclaratorChunk::BlockPointer: 4168 case DeclaratorChunk::Pipe: 4169 // These are invalid anyway, so just ignore. 4170 break; 4171 } 4172 } 4173 return false; 4174 } 4175 4176 static bool IsNoDerefableChunk(const DeclaratorChunk &Chunk) { 4177 return (Chunk.Kind == DeclaratorChunk::Pointer || 4178 Chunk.Kind == DeclaratorChunk::Array); 4179 } 4180 4181 template<typename AttrT> 4182 static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) { 4183 AL.setUsedAsTypeAttr(); 4184 return ::new (Ctx) AttrT(Ctx, AL); 4185 } 4186 4187 static Attr *createNullabilityAttr(ASTContext &Ctx, ParsedAttr &Attr, 4188 NullabilityKind NK) { 4189 switch (NK) { 4190 case NullabilityKind::NonNull: 4191 return createSimpleAttr<TypeNonNullAttr>(Ctx, Attr); 4192 4193 case NullabilityKind::Nullable: 4194 return createSimpleAttr<TypeNullableAttr>(Ctx, Attr); 4195 4196 case NullabilityKind::NullableResult: 4197 return createSimpleAttr<TypeNullableResultAttr>(Ctx, Attr); 4198 4199 case NullabilityKind::Unspecified: 4200 return createSimpleAttr<TypeNullUnspecifiedAttr>(Ctx, Attr); 4201 } 4202 llvm_unreachable("unknown NullabilityKind"); 4203 } 4204 4205 // Diagnose whether this is a case with the multiple addr spaces. 4206 // Returns true if this is an invalid case. 4207 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified 4208 // by qualifiers for two or more different address spaces." 4209 static bool DiagnoseMultipleAddrSpaceAttributes(Sema &S, LangAS ASOld, 4210 LangAS ASNew, 4211 SourceLocation AttrLoc) { 4212 if (ASOld != LangAS::Default) { 4213 if (ASOld != ASNew) { 4214 S.Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers); 4215 return true; 4216 } 4217 // Emit a warning if they are identical; it's likely unintended. 4218 S.Diag(AttrLoc, 4219 diag::warn_attribute_address_multiple_identical_qualifiers); 4220 } 4221 return false; 4222 } 4223 4224 // Whether this is a type broadly expected to have nullability attached. 4225 // These types are affected by `#pragma assume_nonnull`, and missing nullability 4226 // will be diagnosed with -Wnullability-completeness. 4227 static bool shouldHaveNullability(QualType T) { 4228 return T->canHaveNullability(/*ResultIfUnknown=*/false) && 4229 // For now, do not infer/require nullability on C++ smart pointers. 4230 // It's unclear whether the pragma's behavior is useful for C++. 4231 // e.g. treating type-aliases and template-type-parameters differently 4232 // from types of declarations can be surprising. 4233 !isa<RecordType, TemplateSpecializationType>( 4234 T->getCanonicalTypeInternal()); 4235 } 4236 4237 static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state, 4238 QualType declSpecType, 4239 TypeSourceInfo *TInfo) { 4240 // The TypeSourceInfo that this function returns will not be a null type. 4241 // If there is an error, this function will fill in a dummy type as fallback. 4242 QualType T = declSpecType; 4243 Declarator &D = state.getDeclarator(); 4244 Sema &S = state.getSema(); 4245 ASTContext &Context = S.Context; 4246 const LangOptions &LangOpts = S.getLangOpts(); 4247 4248 // The name we're declaring, if any. 4249 DeclarationName Name; 4250 if (D.getIdentifier()) 4251 Name = D.getIdentifier(); 4252 4253 // Does this declaration declare a typedef-name? 4254 bool IsTypedefName = 4255 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef || 4256 D.getContext() == DeclaratorContext::AliasDecl || 4257 D.getContext() == DeclaratorContext::AliasTemplate; 4258 4259 // Does T refer to a function type with a cv-qualifier or a ref-qualifier? 4260 bool IsQualifiedFunction = T->isFunctionProtoType() && 4261 (!T->castAs<FunctionProtoType>()->getMethodQuals().empty() || 4262 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None); 4263 4264 // If T is 'decltype(auto)', the only declarators we can have are parens 4265 // and at most one function declarator if this is a function declaration. 4266 // If T is a deduced class template specialization type, we can have no 4267 // declarator chunks at all. 4268 if (auto *DT = T->getAs<DeducedType>()) { 4269 const AutoType *AT = T->getAs<AutoType>(); 4270 bool IsClassTemplateDeduction = isa<DeducedTemplateSpecializationType>(DT); 4271 if ((AT && AT->isDecltypeAuto()) || IsClassTemplateDeduction) { 4272 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 4273 unsigned Index = E - I - 1; 4274 DeclaratorChunk &DeclChunk = D.getTypeObject(Index); 4275 unsigned DiagId = IsClassTemplateDeduction 4276 ? diag::err_deduced_class_template_compound_type 4277 : diag::err_decltype_auto_compound_type; 4278 unsigned DiagKind = 0; 4279 switch (DeclChunk.Kind) { 4280 case DeclaratorChunk::Paren: 4281 // FIXME: Rejecting this is a little silly. 4282 if (IsClassTemplateDeduction) { 4283 DiagKind = 4; 4284 break; 4285 } 4286 continue; 4287 case DeclaratorChunk::Function: { 4288 if (IsClassTemplateDeduction) { 4289 DiagKind = 3; 4290 break; 4291 } 4292 unsigned FnIndex; 4293 if (D.isFunctionDeclarationContext() && 4294 D.isFunctionDeclarator(FnIndex) && FnIndex == Index) 4295 continue; 4296 DiagId = diag::err_decltype_auto_function_declarator_not_declaration; 4297 break; 4298 } 4299 case DeclaratorChunk::Pointer: 4300 case DeclaratorChunk::BlockPointer: 4301 case DeclaratorChunk::MemberPointer: 4302 DiagKind = 0; 4303 break; 4304 case DeclaratorChunk::Reference: 4305 DiagKind = 1; 4306 break; 4307 case DeclaratorChunk::Array: 4308 DiagKind = 2; 4309 break; 4310 case DeclaratorChunk::Pipe: 4311 break; 4312 } 4313 4314 S.Diag(DeclChunk.Loc, DiagId) << DiagKind; 4315 D.setInvalidType(true); 4316 break; 4317 } 4318 } 4319 } 4320 4321 // Determine whether we should infer _Nonnull on pointer types. 4322 std::optional<NullabilityKind> inferNullability; 4323 bool inferNullabilityCS = false; 4324 bool inferNullabilityInnerOnly = false; 4325 bool inferNullabilityInnerOnlyComplete = false; 4326 4327 // Are we in an assume-nonnull region? 4328 bool inAssumeNonNullRegion = false; 4329 SourceLocation assumeNonNullLoc = S.PP.getPragmaAssumeNonNullLoc(); 4330 if (assumeNonNullLoc.isValid()) { 4331 inAssumeNonNullRegion = true; 4332 recordNullabilitySeen(S, assumeNonNullLoc); 4333 } 4334 4335 // Whether to complain about missing nullability specifiers or not. 4336 enum { 4337 /// Never complain. 4338 CAMN_No, 4339 /// Complain on the inner pointers (but not the outermost 4340 /// pointer). 4341 CAMN_InnerPointers, 4342 /// Complain about any pointers that don't have nullability 4343 /// specified or inferred. 4344 CAMN_Yes 4345 } complainAboutMissingNullability = CAMN_No; 4346 unsigned NumPointersRemaining = 0; 4347 auto complainAboutInferringWithinChunk = PointerWrappingDeclaratorKind::None; 4348 4349 if (IsTypedefName) { 4350 // For typedefs, we do not infer any nullability (the default), 4351 // and we only complain about missing nullability specifiers on 4352 // inner pointers. 4353 complainAboutMissingNullability = CAMN_InnerPointers; 4354 4355 if (shouldHaveNullability(T) && !T->getNullability()) { 4356 // Note that we allow but don't require nullability on dependent types. 4357 ++NumPointersRemaining; 4358 } 4359 4360 for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) { 4361 DeclaratorChunk &chunk = D.getTypeObject(i); 4362 switch (chunk.Kind) { 4363 case DeclaratorChunk::Array: 4364 case DeclaratorChunk::Function: 4365 case DeclaratorChunk::Pipe: 4366 break; 4367 4368 case DeclaratorChunk::BlockPointer: 4369 case DeclaratorChunk::MemberPointer: 4370 ++NumPointersRemaining; 4371 break; 4372 4373 case DeclaratorChunk::Paren: 4374 case DeclaratorChunk::Reference: 4375 continue; 4376 4377 case DeclaratorChunk::Pointer: 4378 ++NumPointersRemaining; 4379 continue; 4380 } 4381 } 4382 } else { 4383 bool isFunctionOrMethod = false; 4384 switch (auto context = state.getDeclarator().getContext()) { 4385 case DeclaratorContext::ObjCParameter: 4386 case DeclaratorContext::ObjCResult: 4387 case DeclaratorContext::Prototype: 4388 case DeclaratorContext::TrailingReturn: 4389 case DeclaratorContext::TrailingReturnVar: 4390 isFunctionOrMethod = true; 4391 [[fallthrough]]; 4392 4393 case DeclaratorContext::Member: 4394 if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) { 4395 complainAboutMissingNullability = CAMN_No; 4396 break; 4397 } 4398 4399 // Weak properties are inferred to be nullable. 4400 if (state.getDeclarator().isObjCWeakProperty()) { 4401 // Weak properties cannot be nonnull, and should not complain about 4402 // missing nullable attributes during completeness checks. 4403 complainAboutMissingNullability = CAMN_No; 4404 if (inAssumeNonNullRegion) { 4405 inferNullability = NullabilityKind::Nullable; 4406 } 4407 break; 4408 } 4409 4410 [[fallthrough]]; 4411 4412 case DeclaratorContext::File: 4413 case DeclaratorContext::KNRTypeList: { 4414 complainAboutMissingNullability = CAMN_Yes; 4415 4416 // Nullability inference depends on the type and declarator. 4417 auto wrappingKind = PointerWrappingDeclaratorKind::None; 4418 switch (classifyPointerDeclarator(S, T, D, wrappingKind)) { 4419 case PointerDeclaratorKind::NonPointer: 4420 case PointerDeclaratorKind::MultiLevelPointer: 4421 // Cannot infer nullability. 4422 break; 4423 4424 case PointerDeclaratorKind::SingleLevelPointer: 4425 // Infer _Nonnull if we are in an assumes-nonnull region. 4426 if (inAssumeNonNullRegion) { 4427 complainAboutInferringWithinChunk = wrappingKind; 4428 inferNullability = NullabilityKind::NonNull; 4429 inferNullabilityCS = (context == DeclaratorContext::ObjCParameter || 4430 context == DeclaratorContext::ObjCResult); 4431 } 4432 break; 4433 4434 case PointerDeclaratorKind::CFErrorRefPointer: 4435 case PointerDeclaratorKind::NSErrorPointerPointer: 4436 // Within a function or method signature, infer _Nullable at both 4437 // levels. 4438 if (isFunctionOrMethod && inAssumeNonNullRegion) 4439 inferNullability = NullabilityKind::Nullable; 4440 break; 4441 4442 case PointerDeclaratorKind::MaybePointerToCFRef: 4443 if (isFunctionOrMethod) { 4444 // On pointer-to-pointer parameters marked cf_returns_retained or 4445 // cf_returns_not_retained, if the outer pointer is explicit then 4446 // infer the inner pointer as _Nullable. 4447 auto hasCFReturnsAttr = 4448 [](const ParsedAttributesView &AttrList) -> bool { 4449 return AttrList.hasAttribute(ParsedAttr::AT_CFReturnsRetained) || 4450 AttrList.hasAttribute(ParsedAttr::AT_CFReturnsNotRetained); 4451 }; 4452 if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) { 4453 if (hasCFReturnsAttr(D.getDeclarationAttributes()) || 4454 hasCFReturnsAttr(D.getAttributes()) || 4455 hasCFReturnsAttr(InnermostChunk->getAttrs()) || 4456 hasCFReturnsAttr(D.getDeclSpec().getAttributes())) { 4457 inferNullability = NullabilityKind::Nullable; 4458 inferNullabilityInnerOnly = true; 4459 } 4460 } 4461 } 4462 break; 4463 } 4464 break; 4465 } 4466 4467 case DeclaratorContext::ConversionId: 4468 complainAboutMissingNullability = CAMN_Yes; 4469 break; 4470 4471 case DeclaratorContext::AliasDecl: 4472 case DeclaratorContext::AliasTemplate: 4473 case DeclaratorContext::Block: 4474 case DeclaratorContext::BlockLiteral: 4475 case DeclaratorContext::Condition: 4476 case DeclaratorContext::CXXCatch: 4477 case DeclaratorContext::CXXNew: 4478 case DeclaratorContext::ForInit: 4479 case DeclaratorContext::SelectionInit: 4480 case DeclaratorContext::LambdaExpr: 4481 case DeclaratorContext::LambdaExprParameter: 4482 case DeclaratorContext::ObjCCatch: 4483 case DeclaratorContext::TemplateParam: 4484 case DeclaratorContext::TemplateArg: 4485 case DeclaratorContext::TemplateTypeArg: 4486 case DeclaratorContext::TypeName: 4487 case DeclaratorContext::FunctionalCast: 4488 case DeclaratorContext::RequiresExpr: 4489 case DeclaratorContext::Association: 4490 // Don't infer in these contexts. 4491 break; 4492 } 4493 } 4494 4495 // Local function that returns true if its argument looks like a va_list. 4496 auto isVaList = [&S](QualType T) -> bool { 4497 auto *typedefTy = T->getAs<TypedefType>(); 4498 if (!typedefTy) 4499 return false; 4500 TypedefDecl *vaListTypedef = S.Context.getBuiltinVaListDecl(); 4501 do { 4502 if (typedefTy->getDecl() == vaListTypedef) 4503 return true; 4504 if (auto *name = typedefTy->getDecl()->getIdentifier()) 4505 if (name->isStr("va_list")) 4506 return true; 4507 typedefTy = typedefTy->desugar()->getAs<TypedefType>(); 4508 } while (typedefTy); 4509 return false; 4510 }; 4511 4512 // Local function that checks the nullability for a given pointer declarator. 4513 // Returns true if _Nonnull was inferred. 4514 auto inferPointerNullability = 4515 [&](SimplePointerKind pointerKind, SourceLocation pointerLoc, 4516 SourceLocation pointerEndLoc, 4517 ParsedAttributesView &attrs, AttributePool &Pool) -> ParsedAttr * { 4518 // We've seen a pointer. 4519 if (NumPointersRemaining > 0) 4520 --NumPointersRemaining; 4521 4522 // If a nullability attribute is present, there's nothing to do. 4523 if (hasNullabilityAttr(attrs)) 4524 return nullptr; 4525 4526 // If we're supposed to infer nullability, do so now. 4527 if (inferNullability && !inferNullabilityInnerOnlyComplete) { 4528 ParsedAttr::Form form = 4529 inferNullabilityCS 4530 ? ParsedAttr::Form::ContextSensitiveKeyword() 4531 : ParsedAttr::Form::Keyword(false /*IsAlignAs*/, 4532 false /*IsRegularKeywordAttribute*/); 4533 ParsedAttr *nullabilityAttr = Pool.create( 4534 S.getNullabilityKeyword(*inferNullability), SourceRange(pointerLoc), 4535 nullptr, SourceLocation(), nullptr, 0, form); 4536 4537 attrs.addAtEnd(nullabilityAttr); 4538 4539 if (inferNullabilityCS) { 4540 state.getDeclarator().getMutableDeclSpec().getObjCQualifiers() 4541 ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability); 4542 } 4543 4544 if (pointerLoc.isValid() && 4545 complainAboutInferringWithinChunk != 4546 PointerWrappingDeclaratorKind::None) { 4547 auto Diag = 4548 S.Diag(pointerLoc, diag::warn_nullability_inferred_on_nested_type); 4549 Diag << static_cast<int>(complainAboutInferringWithinChunk); 4550 fixItNullability(S, Diag, pointerLoc, NullabilityKind::NonNull); 4551 } 4552 4553 if (inferNullabilityInnerOnly) 4554 inferNullabilityInnerOnlyComplete = true; 4555 return nullabilityAttr; 4556 } 4557 4558 // If we're supposed to complain about missing nullability, do so 4559 // now if it's truly missing. 4560 switch (complainAboutMissingNullability) { 4561 case CAMN_No: 4562 break; 4563 4564 case CAMN_InnerPointers: 4565 if (NumPointersRemaining == 0) 4566 break; 4567 [[fallthrough]]; 4568 4569 case CAMN_Yes: 4570 checkNullabilityConsistency(S, pointerKind, pointerLoc, pointerEndLoc); 4571 } 4572 return nullptr; 4573 }; 4574 4575 // If the type itself could have nullability but does not, infer pointer 4576 // nullability and perform consistency checking. 4577 if (S.CodeSynthesisContexts.empty()) { 4578 if (shouldHaveNullability(T) && !T->getNullability()) { 4579 if (isVaList(T)) { 4580 // Record that we've seen a pointer, but do nothing else. 4581 if (NumPointersRemaining > 0) 4582 --NumPointersRemaining; 4583 } else { 4584 SimplePointerKind pointerKind = SimplePointerKind::Pointer; 4585 if (T->isBlockPointerType()) 4586 pointerKind = SimplePointerKind::BlockPointer; 4587 else if (T->isMemberPointerType()) 4588 pointerKind = SimplePointerKind::MemberPointer; 4589 4590 if (auto *attr = inferPointerNullability( 4591 pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(), 4592 D.getDeclSpec().getEndLoc(), 4593 D.getMutableDeclSpec().getAttributes(), 4594 D.getMutableDeclSpec().getAttributePool())) { 4595 T = state.getAttributedType( 4596 createNullabilityAttr(Context, *attr, *inferNullability), T, T); 4597 } 4598 } 4599 } 4600 4601 if (complainAboutMissingNullability == CAMN_Yes && T->isArrayType() && 4602 !T->getNullability() && !isVaList(T) && D.isPrototypeContext() && 4603 !hasOuterPointerLikeChunk(D, D.getNumTypeObjects())) { 4604 checkNullabilityConsistency(S, SimplePointerKind::Array, 4605 D.getDeclSpec().getTypeSpecTypeLoc()); 4606 } 4607 } 4608 4609 bool ExpectNoDerefChunk = 4610 state.getCurrentAttributes().hasAttribute(ParsedAttr::AT_NoDeref); 4611 4612 // Walk the DeclTypeInfo, building the recursive type as we go. 4613 // DeclTypeInfos are ordered from the identifier out, which is 4614 // opposite of what we want :). 4615 4616 // Track if the produced type matches the structure of the declarator. 4617 // This is used later to decide if we can fill `TypeLoc` from 4618 // `DeclaratorChunk`s. E.g. it must be false if Clang recovers from 4619 // an error by replacing the type with `int`. 4620 bool AreDeclaratorChunksValid = true; 4621 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 4622 unsigned chunkIndex = e - i - 1; 4623 state.setCurrentChunkIndex(chunkIndex); 4624 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex); 4625 IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren; 4626 switch (DeclType.Kind) { 4627 case DeclaratorChunk::Paren: 4628 if (i == 0) 4629 warnAboutRedundantParens(S, D, T); 4630 T = S.BuildParenType(T); 4631 break; 4632 case DeclaratorChunk::BlockPointer: 4633 // If blocks are disabled, emit an error. 4634 if (!LangOpts.Blocks) 4635 S.Diag(DeclType.Loc, diag::err_blocks_disable) << LangOpts.OpenCL; 4636 4637 // Handle pointer nullability. 4638 inferPointerNullability(SimplePointerKind::BlockPointer, DeclType.Loc, 4639 DeclType.EndLoc, DeclType.getAttrs(), 4640 state.getDeclarator().getAttributePool()); 4641 4642 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name); 4643 if (DeclType.Cls.TypeQuals || LangOpts.OpenCL) { 4644 // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly 4645 // qualified with const. 4646 if (LangOpts.OpenCL) 4647 DeclType.Cls.TypeQuals |= DeclSpec::TQ_const; 4648 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals); 4649 } 4650 break; 4651 case DeclaratorChunk::Pointer: 4652 // Verify that we're not building a pointer to pointer to function with 4653 // exception specification. 4654 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { 4655 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 4656 D.setInvalidType(true); 4657 // Build the type anyway. 4658 } 4659 4660 // Handle pointer nullability 4661 inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc, 4662 DeclType.EndLoc, DeclType.getAttrs(), 4663 state.getDeclarator().getAttributePool()); 4664 4665 if (LangOpts.ObjC && T->getAs<ObjCObjectType>()) { 4666 T = Context.getObjCObjectPointerType(T); 4667 if (DeclType.Ptr.TypeQuals) 4668 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals); 4669 break; 4670 } 4671 4672 // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used. 4673 // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used. 4674 // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed. 4675 if (LangOpts.OpenCL) { 4676 if (T->isImageType() || T->isSamplerT() || T->isPipeType() || 4677 T->isBlockPointerType()) { 4678 S.Diag(D.getIdentifierLoc(), diag::err_opencl_pointer_to_type) << T; 4679 D.setInvalidType(true); 4680 } 4681 } 4682 4683 T = S.BuildPointerType(T, DeclType.Loc, Name); 4684 if (DeclType.Ptr.TypeQuals) 4685 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals); 4686 break; 4687 case DeclaratorChunk::Reference: { 4688 // Verify that we're not building a reference to pointer to function with 4689 // exception specification. 4690 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { 4691 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 4692 D.setInvalidType(true); 4693 // Build the type anyway. 4694 } 4695 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name); 4696 4697 if (DeclType.Ref.HasRestrict) 4698 T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict); 4699 break; 4700 } 4701 case DeclaratorChunk::Array: { 4702 // Verify that we're not building an array of pointers to function with 4703 // exception specification. 4704 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { 4705 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 4706 D.setInvalidType(true); 4707 // Build the type anyway. 4708 } 4709 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr; 4710 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts); 4711 ArraySizeModifier ASM; 4712 4713 // Microsoft property fields can have multiple sizeless array chunks 4714 // (i.e. int x[][][]). Skip all of these except one to avoid creating 4715 // bad incomplete array types. 4716 if (chunkIndex != 0 && !ArraySize && 4717 D.getDeclSpec().getAttributes().hasMSPropertyAttr()) { 4718 // This is a sizeless chunk. If the next is also, skip this one. 4719 DeclaratorChunk &NextDeclType = D.getTypeObject(chunkIndex - 1); 4720 if (NextDeclType.Kind == DeclaratorChunk::Array && 4721 !NextDeclType.Arr.NumElts) 4722 break; 4723 } 4724 4725 if (ATI.isStar) 4726 ASM = ArraySizeModifier::Star; 4727 else if (ATI.hasStatic) 4728 ASM = ArraySizeModifier::Static; 4729 else 4730 ASM = ArraySizeModifier::Normal; 4731 if (ASM == ArraySizeModifier::Star && !D.isPrototypeContext()) { 4732 // FIXME: This check isn't quite right: it allows star in prototypes 4733 // for function definitions, and disallows some edge cases detailed 4734 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html 4735 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype); 4736 ASM = ArraySizeModifier::Normal; 4737 D.setInvalidType(true); 4738 } 4739 4740 // C99 6.7.5.2p1: The optional type qualifiers and the keyword static 4741 // shall appear only in a declaration of a function parameter with an 4742 // array type, ... 4743 if (ASM == ArraySizeModifier::Static || ATI.TypeQuals) { 4744 if (!(D.isPrototypeContext() || 4745 D.getContext() == DeclaratorContext::KNRTypeList)) { 4746 S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) 4747 << (ASM == ArraySizeModifier::Static ? "'static'" 4748 : "type qualifier"); 4749 // Remove the 'static' and the type qualifiers. 4750 if (ASM == ArraySizeModifier::Static) 4751 ASM = ArraySizeModifier::Normal; 4752 ATI.TypeQuals = 0; 4753 D.setInvalidType(true); 4754 } 4755 4756 // C99 6.7.5.2p1: ... and then only in the outermost array type 4757 // derivation. 4758 if (hasOuterPointerLikeChunk(D, chunkIndex)) { 4759 S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) 4760 << (ASM == ArraySizeModifier::Static ? "'static'" 4761 : "type qualifier"); 4762 if (ASM == ArraySizeModifier::Static) 4763 ASM = ArraySizeModifier::Normal; 4764 ATI.TypeQuals = 0; 4765 D.setInvalidType(true); 4766 } 4767 } 4768 4769 // Array parameters can be marked nullable as well, although it's not 4770 // necessary if they're marked 'static'. 4771 if (complainAboutMissingNullability == CAMN_Yes && 4772 !hasNullabilityAttr(DeclType.getAttrs()) && 4773 ASM != ArraySizeModifier::Static && D.isPrototypeContext() && 4774 !hasOuterPointerLikeChunk(D, chunkIndex)) { 4775 checkNullabilityConsistency(S, SimplePointerKind::Array, DeclType.Loc); 4776 } 4777 4778 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals, 4779 SourceRange(DeclType.Loc, DeclType.EndLoc), Name); 4780 break; 4781 } 4782 case DeclaratorChunk::Function: { 4783 // If the function declarator has a prototype (i.e. it is not () and 4784 // does not have a K&R-style identifier list), then the arguments are part 4785 // of the type, otherwise the argument list is (). 4786 DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 4787 IsQualifiedFunction = 4788 FTI.hasMethodTypeQualifiers() || FTI.hasRefQualifier(); 4789 4790 // Check for auto functions and trailing return type and adjust the 4791 // return type accordingly. 4792 if (!D.isInvalidType()) { 4793 auto IsClassType = [&](CXXScopeSpec &SS) { 4794 // If there already was an problem with the scope, don’t issue another 4795 // error about the explicit object parameter. 4796 return SS.isInvalid() || 4797 isa_and_present<CXXRecordDecl>(S.computeDeclContext(SS)); 4798 }; 4799 4800 // C++23 [dcl.fct]p6: 4801 // 4802 // An explicit-object-parameter-declaration is a parameter-declaration 4803 // with a this specifier. An explicit-object-parameter-declaration shall 4804 // appear only as the first parameter-declaration of a 4805 // parameter-declaration-list of one of: 4806 // 4807 // - a declaration of a member function or member function template 4808 // ([class.mem]), or 4809 // 4810 // - an explicit instantiation ([temp.explicit]) or explicit 4811 // specialization ([temp.expl.spec]) of a templated member function, 4812 // or 4813 // 4814 // - a lambda-declarator [expr.prim.lambda]. 4815 DeclaratorContext C = D.getContext(); 4816 ParmVarDecl *First = 4817 FTI.NumParams 4818 ? dyn_cast_if_present<ParmVarDecl>(FTI.Params[0].Param) 4819 : nullptr; 4820 4821 bool IsFunctionDecl = D.getInnermostNonParenChunk() == &DeclType; 4822 if (First && First->isExplicitObjectParameter() && 4823 C != DeclaratorContext::LambdaExpr && 4824 4825 // Either not a member or nested declarator in a member. 4826 // 4827 // Note that e.g. 'static' or 'friend' declarations are accepted 4828 // here; we diagnose them later when we build the member function 4829 // because it's easier that way. 4830 (C != DeclaratorContext::Member || !IsFunctionDecl) && 4831 4832 // Allow out-of-line definitions of member functions. 4833 !IsClassType(D.getCXXScopeSpec())) { 4834 if (IsFunctionDecl) 4835 S.Diag(First->getBeginLoc(), 4836 diag::err_explicit_object_parameter_nonmember) 4837 << /*non-member*/ 2 << /*function*/ 0 4838 << First->getSourceRange(); 4839 else 4840 S.Diag(First->getBeginLoc(), 4841 diag::err_explicit_object_parameter_invalid) 4842 << First->getSourceRange(); 4843 4844 D.setInvalidType(); 4845 AreDeclaratorChunksValid = false; 4846 } 4847 4848 // trailing-return-type is only required if we're declaring a function, 4849 // and not, for instance, a pointer to a function. 4850 if (D.getDeclSpec().hasAutoTypeSpec() && 4851 !FTI.hasTrailingReturnType() && chunkIndex == 0) { 4852 if (!S.getLangOpts().CPlusPlus14) { 4853 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 4854 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto 4855 ? diag::err_auto_missing_trailing_return 4856 : diag::err_deduced_return_type); 4857 T = Context.IntTy; 4858 D.setInvalidType(true); 4859 AreDeclaratorChunksValid = false; 4860 } else { 4861 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 4862 diag::warn_cxx11_compat_deduced_return_type); 4863 } 4864 } else if (FTI.hasTrailingReturnType()) { 4865 // T must be exactly 'auto' at this point. See CWG issue 681. 4866 if (isa<ParenType>(T)) { 4867 S.Diag(D.getBeginLoc(), diag::err_trailing_return_in_parens) 4868 << T << D.getSourceRange(); 4869 D.setInvalidType(true); 4870 // FIXME: recover and fill decls in `TypeLoc`s. 4871 AreDeclaratorChunksValid = false; 4872 } else if (D.getName().getKind() == 4873 UnqualifiedIdKind::IK_DeductionGuideName) { 4874 if (T != Context.DependentTy) { 4875 S.Diag(D.getDeclSpec().getBeginLoc(), 4876 diag::err_deduction_guide_with_complex_decl) 4877 << D.getSourceRange(); 4878 D.setInvalidType(true); 4879 // FIXME: recover and fill decls in `TypeLoc`s. 4880 AreDeclaratorChunksValid = false; 4881 } 4882 } else if (D.getContext() != DeclaratorContext::LambdaExpr && 4883 (T.hasQualifiers() || !isa<AutoType>(T) || 4884 cast<AutoType>(T)->getKeyword() != 4885 AutoTypeKeyword::Auto || 4886 cast<AutoType>(T)->isConstrained())) { 4887 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 4888 diag::err_trailing_return_without_auto) 4889 << T << D.getDeclSpec().getSourceRange(); 4890 D.setInvalidType(true); 4891 // FIXME: recover and fill decls in `TypeLoc`s. 4892 AreDeclaratorChunksValid = false; 4893 } 4894 T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo); 4895 if (T.isNull()) { 4896 // An error occurred parsing the trailing return type. 4897 T = Context.IntTy; 4898 D.setInvalidType(true); 4899 } else if (AutoType *Auto = T->getContainedAutoType()) { 4900 // If the trailing return type contains an `auto`, we may need to 4901 // invent a template parameter for it, for cases like 4902 // `auto f() -> C auto` or `[](auto (*p) -> auto) {}`. 4903 InventedTemplateParameterInfo *InventedParamInfo = nullptr; 4904 if (D.getContext() == DeclaratorContext::Prototype) 4905 InventedParamInfo = &S.InventedParameterInfos.back(); 4906 else if (D.getContext() == DeclaratorContext::LambdaExprParameter) 4907 InventedParamInfo = S.getCurLambda(); 4908 if (InventedParamInfo) { 4909 std::tie(T, TInfo) = InventTemplateParameter( 4910 state, T, TInfo, Auto, *InventedParamInfo); 4911 } 4912 } 4913 } else { 4914 // This function type is not the type of the entity being declared, 4915 // so checking the 'auto' is not the responsibility of this chunk. 4916 } 4917 } 4918 4919 // C99 6.7.5.3p1: The return type may not be a function or array type. 4920 // For conversion functions, we'll diagnose this particular error later. 4921 if (!D.isInvalidType() && (T->isArrayType() || T->isFunctionType()) && 4922 (D.getName().getKind() != 4923 UnqualifiedIdKind::IK_ConversionFunctionId)) { 4924 unsigned diagID = diag::err_func_returning_array_function; 4925 // Last processing chunk in block context means this function chunk 4926 // represents the block. 4927 if (chunkIndex == 0 && 4928 D.getContext() == DeclaratorContext::BlockLiteral) 4929 diagID = diag::err_block_returning_array_function; 4930 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T; 4931 T = Context.IntTy; 4932 D.setInvalidType(true); 4933 AreDeclaratorChunksValid = false; 4934 } 4935 4936 // Do not allow returning half FP value. 4937 // FIXME: This really should be in BuildFunctionType. 4938 if (T->isHalfType()) { 4939 if (S.getLangOpts().OpenCL) { 4940 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", 4941 S.getLangOpts())) { 4942 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return) 4943 << T << 0 /*pointer hint*/; 4944 D.setInvalidType(true); 4945 } 4946 } else if (!S.getLangOpts().NativeHalfArgsAndReturns && 4947 !S.Context.getTargetInfo().allowHalfArgsAndReturns()) { 4948 S.Diag(D.getIdentifierLoc(), 4949 diag::err_parameters_retval_cannot_have_fp16_type) << 1; 4950 D.setInvalidType(true); 4951 } 4952 } 4953 4954 if (LangOpts.OpenCL) { 4955 // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a 4956 // function. 4957 if (T->isBlockPointerType() || T->isImageType() || T->isSamplerT() || 4958 T->isPipeType()) { 4959 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return) 4960 << T << 1 /*hint off*/; 4961 D.setInvalidType(true); 4962 } 4963 // OpenCL doesn't support variadic functions and blocks 4964 // (s6.9.e and s6.12.5 OpenCL v2.0) except for printf. 4965 // We also allow here any toolchain reserved identifiers. 4966 if (FTI.isVariadic && 4967 !S.getOpenCLOptions().isAvailableOption( 4968 "__cl_clang_variadic_functions", S.getLangOpts()) && 4969 !(D.getIdentifier() && 4970 ((D.getIdentifier()->getName() == "printf" && 4971 LangOpts.getOpenCLCompatibleVersion() >= 120) || 4972 D.getIdentifier()->getName().starts_with("__")))) { 4973 S.Diag(D.getIdentifierLoc(), diag::err_opencl_variadic_function); 4974 D.setInvalidType(true); 4975 } 4976 } 4977 4978 // Methods cannot return interface types. All ObjC objects are 4979 // passed by reference. 4980 if (T->isObjCObjectType()) { 4981 SourceLocation DiagLoc, FixitLoc; 4982 if (TInfo) { 4983 DiagLoc = TInfo->getTypeLoc().getBeginLoc(); 4984 FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getEndLoc()); 4985 } else { 4986 DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc(); 4987 FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getEndLoc()); 4988 } 4989 S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value) 4990 << 0 << T 4991 << FixItHint::CreateInsertion(FixitLoc, "*"); 4992 4993 T = Context.getObjCObjectPointerType(T); 4994 if (TInfo) { 4995 TypeLocBuilder TLB; 4996 TLB.pushFullCopy(TInfo->getTypeLoc()); 4997 ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T); 4998 TLoc.setStarLoc(FixitLoc); 4999 TInfo = TLB.getTypeSourceInfo(Context, T); 5000 } else { 5001 AreDeclaratorChunksValid = false; 5002 } 5003 5004 D.setInvalidType(true); 5005 } 5006 5007 // cv-qualifiers on return types are pointless except when the type is a 5008 // class type in C++. 5009 if ((T.getCVRQualifiers() || T->isAtomicType()) && 5010 !(S.getLangOpts().CPlusPlus && 5011 (T->isDependentType() || T->isRecordType()))) { 5012 if (T->isVoidType() && !S.getLangOpts().CPlusPlus && 5013 D.getFunctionDefinitionKind() == 5014 FunctionDefinitionKind::Definition) { 5015 // [6.9.1/3] qualified void return is invalid on a C 5016 // function definition. Apparently ok on declarations and 5017 // in C++ though (!) 5018 S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T; 5019 } else 5020 diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex); 5021 5022 // C++2a [dcl.fct]p12: 5023 // A volatile-qualified return type is deprecated 5024 if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20) 5025 S.Diag(DeclType.Loc, diag::warn_deprecated_volatile_return) << T; 5026 } 5027 5028 // Objective-C ARC ownership qualifiers are ignored on the function 5029 // return type (by type canonicalization). Complain if this attribute 5030 // was written here. 5031 if (T.getQualifiers().hasObjCLifetime()) { 5032 SourceLocation AttrLoc; 5033 if (chunkIndex + 1 < D.getNumTypeObjects()) { 5034 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1); 5035 for (const ParsedAttr &AL : ReturnTypeChunk.getAttrs()) { 5036 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) { 5037 AttrLoc = AL.getLoc(); 5038 break; 5039 } 5040 } 5041 } 5042 if (AttrLoc.isInvalid()) { 5043 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) { 5044 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) { 5045 AttrLoc = AL.getLoc(); 5046 break; 5047 } 5048 } 5049 } 5050 5051 if (AttrLoc.isValid()) { 5052 // The ownership attributes are almost always written via 5053 // the predefined 5054 // __strong/__weak/__autoreleasing/__unsafe_unretained. 5055 if (AttrLoc.isMacroID()) 5056 AttrLoc = 5057 S.SourceMgr.getImmediateExpansionRange(AttrLoc).getBegin(); 5058 5059 S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type) 5060 << T.getQualifiers().getObjCLifetime(); 5061 } 5062 } 5063 5064 if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) { 5065 // C++ [dcl.fct]p6: 5066 // Types shall not be defined in return or parameter types. 5067 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 5068 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type) 5069 << Context.getTypeDeclType(Tag); 5070 } 5071 5072 // Exception specs are not allowed in typedefs. Complain, but add it 5073 // anyway. 5074 if (IsTypedefName && FTI.getExceptionSpecType() && !LangOpts.CPlusPlus17) 5075 S.Diag(FTI.getExceptionSpecLocBeg(), 5076 diag::err_exception_spec_in_typedef) 5077 << (D.getContext() == DeclaratorContext::AliasDecl || 5078 D.getContext() == DeclaratorContext::AliasTemplate); 5079 5080 // If we see "T var();" or "T var(T());" at block scope, it is probably 5081 // an attempt to initialize a variable, not a function declaration. 5082 if (FTI.isAmbiguous) 5083 warnAboutAmbiguousFunction(S, D, DeclType, T); 5084 5085 FunctionType::ExtInfo EI( 5086 getCCForDeclaratorChunk(S, D, DeclType.getAttrs(), FTI, chunkIndex)); 5087 5088 // OpenCL disallows functions without a prototype, but it doesn't enforce 5089 // strict prototypes as in C23 because it allows a function definition to 5090 // have an identifier list. See OpenCL 3.0 6.11/g for more details. 5091 if (!FTI.NumParams && !FTI.isVariadic && 5092 !LangOpts.requiresStrictPrototypes() && !LangOpts.OpenCL) { 5093 // Simple void foo(), where the incoming T is the result type. 5094 T = Context.getFunctionNoProtoType(T, EI); 5095 } else { 5096 // We allow a zero-parameter variadic function in C if the 5097 // function is marked with the "overloadable" attribute. Scan 5098 // for this attribute now. We also allow it in C23 per WG14 N2975. 5099 if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) { 5100 if (LangOpts.C23) 5101 S.Diag(FTI.getEllipsisLoc(), 5102 diag::warn_c17_compat_ellipsis_only_parameter); 5103 else if (!D.getDeclarationAttributes().hasAttribute( 5104 ParsedAttr::AT_Overloadable) && 5105 !D.getAttributes().hasAttribute( 5106 ParsedAttr::AT_Overloadable) && 5107 !D.getDeclSpec().getAttributes().hasAttribute( 5108 ParsedAttr::AT_Overloadable)) 5109 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param); 5110 } 5111 5112 if (FTI.NumParams && FTI.Params[0].Param == nullptr) { 5113 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function 5114 // definition. 5115 S.Diag(FTI.Params[0].IdentLoc, 5116 diag::err_ident_list_in_fn_declaration); 5117 D.setInvalidType(true); 5118 // Recover by creating a K&R-style function type, if possible. 5119 T = (!LangOpts.requiresStrictPrototypes() && !LangOpts.OpenCL) 5120 ? Context.getFunctionNoProtoType(T, EI) 5121 : Context.IntTy; 5122 AreDeclaratorChunksValid = false; 5123 break; 5124 } 5125 5126 FunctionProtoType::ExtProtoInfo EPI; 5127 EPI.ExtInfo = EI; 5128 EPI.Variadic = FTI.isVariadic; 5129 EPI.EllipsisLoc = FTI.getEllipsisLoc(); 5130 EPI.HasTrailingReturn = FTI.hasTrailingReturnType(); 5131 EPI.TypeQuals.addCVRUQualifiers( 5132 FTI.MethodQualifiers ? FTI.MethodQualifiers->getTypeQualifiers() 5133 : 0); 5134 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None 5135 : FTI.RefQualifierIsLValueRef? RQ_LValue 5136 : RQ_RValue; 5137 5138 // Otherwise, we have a function with a parameter list that is 5139 // potentially variadic. 5140 SmallVector<QualType, 16> ParamTys; 5141 ParamTys.reserve(FTI.NumParams); 5142 5143 SmallVector<FunctionProtoType::ExtParameterInfo, 16> 5144 ExtParameterInfos(FTI.NumParams); 5145 bool HasAnyInterestingExtParameterInfos = false; 5146 5147 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 5148 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 5149 QualType ParamTy = Param->getType(); 5150 assert(!ParamTy.isNull() && "Couldn't parse type?"); 5151 5152 // Look for 'void'. void is allowed only as a single parameter to a 5153 // function with no other parameters (C99 6.7.5.3p10). We record 5154 // int(void) as a FunctionProtoType with an empty parameter list. 5155 if (ParamTy->isVoidType()) { 5156 // If this is something like 'float(int, void)', reject it. 'void' 5157 // is an incomplete type (C99 6.2.5p19) and function decls cannot 5158 // have parameters of incomplete type. 5159 if (FTI.NumParams != 1 || FTI.isVariadic) { 5160 S.Diag(FTI.Params[i].IdentLoc, diag::err_void_only_param); 5161 ParamTy = Context.IntTy; 5162 Param->setType(ParamTy); 5163 } else if (FTI.Params[i].Ident) { 5164 // Reject, but continue to parse 'int(void abc)'. 5165 S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type); 5166 ParamTy = Context.IntTy; 5167 Param->setType(ParamTy); 5168 } else { 5169 // Reject, but continue to parse 'float(const void)'. 5170 if (ParamTy.hasQualifiers()) 5171 S.Diag(DeclType.Loc, diag::err_void_param_qualified); 5172 5173 // Reject, but continue to parse 'float(this void)' as 5174 // 'float(void)'. 5175 if (Param->isExplicitObjectParameter()) { 5176 S.Diag(Param->getLocation(), 5177 diag::err_void_explicit_object_param); 5178 Param->setExplicitObjectParameterLoc(SourceLocation()); 5179 } 5180 5181 // Do not add 'void' to the list. 5182 break; 5183 } 5184 } else if (ParamTy->isHalfType()) { 5185 // Disallow half FP parameters. 5186 // FIXME: This really should be in BuildFunctionType. 5187 if (S.getLangOpts().OpenCL) { 5188 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", 5189 S.getLangOpts())) { 5190 S.Diag(Param->getLocation(), diag::err_opencl_invalid_param) 5191 << ParamTy << 0; 5192 D.setInvalidType(); 5193 Param->setInvalidDecl(); 5194 } 5195 } else if (!S.getLangOpts().NativeHalfArgsAndReturns && 5196 !S.Context.getTargetInfo().allowHalfArgsAndReturns()) { 5197 S.Diag(Param->getLocation(), 5198 diag::err_parameters_retval_cannot_have_fp16_type) << 0; 5199 D.setInvalidType(); 5200 } 5201 } else if (!FTI.hasPrototype) { 5202 if (Context.isPromotableIntegerType(ParamTy)) { 5203 ParamTy = Context.getPromotedIntegerType(ParamTy); 5204 Param->setKNRPromoted(true); 5205 } else if (const BuiltinType *BTy = ParamTy->getAs<BuiltinType>()) { 5206 if (BTy->getKind() == BuiltinType::Float) { 5207 ParamTy = Context.DoubleTy; 5208 Param->setKNRPromoted(true); 5209 } 5210 } 5211 } else if (S.getLangOpts().OpenCL && ParamTy->isBlockPointerType()) { 5212 // OpenCL 2.0 s6.12.5: A block cannot be a parameter of a function. 5213 S.Diag(Param->getLocation(), diag::err_opencl_invalid_param) 5214 << ParamTy << 1 /*hint off*/; 5215 D.setInvalidType(); 5216 } 5217 5218 if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) { 5219 ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(true); 5220 HasAnyInterestingExtParameterInfos = true; 5221 } 5222 5223 if (auto attr = Param->getAttr<ParameterABIAttr>()) { 5224 ExtParameterInfos[i] = 5225 ExtParameterInfos[i].withABI(attr->getABI()); 5226 HasAnyInterestingExtParameterInfos = true; 5227 } 5228 5229 if (Param->hasAttr<PassObjectSizeAttr>()) { 5230 ExtParameterInfos[i] = ExtParameterInfos[i].withHasPassObjectSize(); 5231 HasAnyInterestingExtParameterInfos = true; 5232 } 5233 5234 if (Param->hasAttr<NoEscapeAttr>()) { 5235 ExtParameterInfos[i] = ExtParameterInfos[i].withIsNoEscape(true); 5236 HasAnyInterestingExtParameterInfos = true; 5237 } 5238 5239 ParamTys.push_back(ParamTy); 5240 } 5241 5242 if (HasAnyInterestingExtParameterInfos) { 5243 EPI.ExtParameterInfos = ExtParameterInfos.data(); 5244 checkExtParameterInfos(S, ParamTys, EPI, 5245 [&](unsigned i) { return FTI.Params[i].Param->getLocation(); }); 5246 } 5247 5248 SmallVector<QualType, 4> Exceptions; 5249 SmallVector<ParsedType, 2> DynamicExceptions; 5250 SmallVector<SourceRange, 2> DynamicExceptionRanges; 5251 Expr *NoexceptExpr = nullptr; 5252 5253 if (FTI.getExceptionSpecType() == EST_Dynamic) { 5254 // FIXME: It's rather inefficient to have to split into two vectors 5255 // here. 5256 unsigned N = FTI.getNumExceptions(); 5257 DynamicExceptions.reserve(N); 5258 DynamicExceptionRanges.reserve(N); 5259 for (unsigned I = 0; I != N; ++I) { 5260 DynamicExceptions.push_back(FTI.Exceptions[I].Ty); 5261 DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range); 5262 } 5263 } else if (isComputedNoexcept(FTI.getExceptionSpecType())) { 5264 NoexceptExpr = FTI.NoexceptExpr; 5265 } 5266 5267 S.checkExceptionSpecification(D.isFunctionDeclarationContext(), 5268 FTI.getExceptionSpecType(), 5269 DynamicExceptions, 5270 DynamicExceptionRanges, 5271 NoexceptExpr, 5272 Exceptions, 5273 EPI.ExceptionSpec); 5274 5275 // FIXME: Set address space from attrs for C++ mode here. 5276 // OpenCLCPlusPlus: A class member function has an address space. 5277 auto IsClassMember = [&]() { 5278 return (!state.getDeclarator().getCXXScopeSpec().isEmpty() && 5279 state.getDeclarator() 5280 .getCXXScopeSpec() 5281 .getScopeRep() 5282 ->getKind() == NestedNameSpecifier::TypeSpec) || 5283 state.getDeclarator().getContext() == 5284 DeclaratorContext::Member || 5285 state.getDeclarator().getContext() == 5286 DeclaratorContext::LambdaExpr; 5287 }; 5288 5289 if (state.getSema().getLangOpts().OpenCLCPlusPlus && IsClassMember()) { 5290 LangAS ASIdx = LangAS::Default; 5291 // Take address space attr if any and mark as invalid to avoid adding 5292 // them later while creating QualType. 5293 if (FTI.MethodQualifiers) 5294 for (ParsedAttr &attr : FTI.MethodQualifiers->getAttributes()) { 5295 LangAS ASIdxNew = attr.asOpenCLLangAS(); 5296 if (DiagnoseMultipleAddrSpaceAttributes(S, ASIdx, ASIdxNew, 5297 attr.getLoc())) 5298 D.setInvalidType(true); 5299 else 5300 ASIdx = ASIdxNew; 5301 } 5302 // If a class member function's address space is not set, set it to 5303 // __generic. 5304 LangAS AS = 5305 (ASIdx == LangAS::Default ? S.getDefaultCXXMethodAddrSpace() 5306 : ASIdx); 5307 EPI.TypeQuals.addAddressSpace(AS); 5308 } 5309 T = Context.getFunctionType(T, ParamTys, EPI); 5310 } 5311 break; 5312 } 5313 case DeclaratorChunk::MemberPointer: { 5314 // The scope spec must refer to a class, or be dependent. 5315 CXXScopeSpec &SS = DeclType.Mem.Scope(); 5316 QualType ClsType; 5317 5318 // Handle pointer nullability. 5319 inferPointerNullability(SimplePointerKind::MemberPointer, DeclType.Loc, 5320 DeclType.EndLoc, DeclType.getAttrs(), 5321 state.getDeclarator().getAttributePool()); 5322 5323 if (SS.isInvalid()) { 5324 // Avoid emitting extra errors if we already errored on the scope. 5325 D.setInvalidType(true); 5326 } else if (S.isDependentScopeSpecifier(SS) || 5327 isa_and_nonnull<CXXRecordDecl>(S.computeDeclContext(SS))) { 5328 NestedNameSpecifier *NNS = SS.getScopeRep(); 5329 NestedNameSpecifier *NNSPrefix = NNS->getPrefix(); 5330 switch (NNS->getKind()) { 5331 case NestedNameSpecifier::Identifier: 5332 ClsType = Context.getDependentNameType( 5333 ElaboratedTypeKeyword::None, NNSPrefix, NNS->getAsIdentifier()); 5334 break; 5335 5336 case NestedNameSpecifier::Namespace: 5337 case NestedNameSpecifier::NamespaceAlias: 5338 case NestedNameSpecifier::Global: 5339 case NestedNameSpecifier::Super: 5340 llvm_unreachable("Nested-name-specifier must name a type"); 5341 5342 case NestedNameSpecifier::TypeSpec: 5343 case NestedNameSpecifier::TypeSpecWithTemplate: 5344 ClsType = QualType(NNS->getAsType(), 0); 5345 // Note: if the NNS has a prefix and ClsType is a nondependent 5346 // TemplateSpecializationType, then the NNS prefix is NOT included 5347 // in ClsType; hence we wrap ClsType into an ElaboratedType. 5348 // NOTE: in particular, no wrap occurs if ClsType already is an 5349 // Elaborated, DependentName, or DependentTemplateSpecialization. 5350 if (isa<TemplateSpecializationType>(NNS->getAsType())) 5351 ClsType = Context.getElaboratedType(ElaboratedTypeKeyword::None, 5352 NNSPrefix, ClsType); 5353 break; 5354 } 5355 } else { 5356 S.Diag(DeclType.Mem.Scope().getBeginLoc(), 5357 diag::err_illegal_decl_mempointer_in_nonclass) 5358 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name") 5359 << DeclType.Mem.Scope().getRange(); 5360 D.setInvalidType(true); 5361 } 5362 5363 if (!ClsType.isNull()) 5364 T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc, 5365 D.getIdentifier()); 5366 else 5367 AreDeclaratorChunksValid = false; 5368 5369 if (T.isNull()) { 5370 T = Context.IntTy; 5371 D.setInvalidType(true); 5372 AreDeclaratorChunksValid = false; 5373 } else if (DeclType.Mem.TypeQuals) { 5374 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals); 5375 } 5376 break; 5377 } 5378 5379 case DeclaratorChunk::Pipe: { 5380 T = S.BuildReadPipeType(T, DeclType.Loc); 5381 processTypeAttrs(state, T, TAL_DeclSpec, 5382 D.getMutableDeclSpec().getAttributes()); 5383 break; 5384 } 5385 } 5386 5387 if (T.isNull()) { 5388 D.setInvalidType(true); 5389 T = Context.IntTy; 5390 AreDeclaratorChunksValid = false; 5391 } 5392 5393 // See if there are any attributes on this declarator chunk. 5394 processTypeAttrs(state, T, TAL_DeclChunk, DeclType.getAttrs(), 5395 S.CUDA().IdentifyTarget(D.getAttributes())); 5396 5397 if (DeclType.Kind != DeclaratorChunk::Paren) { 5398 if (ExpectNoDerefChunk && !IsNoDerefableChunk(DeclType)) 5399 S.Diag(DeclType.Loc, diag::warn_noderef_on_non_pointer_or_array); 5400 5401 ExpectNoDerefChunk = state.didParseNoDeref(); 5402 } 5403 } 5404 5405 if (ExpectNoDerefChunk) 5406 S.Diag(state.getDeclarator().getBeginLoc(), 5407 diag::warn_noderef_on_non_pointer_or_array); 5408 5409 // GNU warning -Wstrict-prototypes 5410 // Warn if a function declaration or definition is without a prototype. 5411 // This warning is issued for all kinds of unprototyped function 5412 // declarations (i.e. function type typedef, function pointer etc.) 5413 // C99 6.7.5.3p14: 5414 // The empty list in a function declarator that is not part of a definition 5415 // of that function specifies that no information about the number or types 5416 // of the parameters is supplied. 5417 // See ActOnFinishFunctionBody() and MergeFunctionDecl() for handling of 5418 // function declarations whose behavior changes in C23. 5419 if (!LangOpts.requiresStrictPrototypes()) { 5420 bool IsBlock = false; 5421 for (const DeclaratorChunk &DeclType : D.type_objects()) { 5422 switch (DeclType.Kind) { 5423 case DeclaratorChunk::BlockPointer: 5424 IsBlock = true; 5425 break; 5426 case DeclaratorChunk::Function: { 5427 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 5428 // We suppress the warning when there's no LParen location, as this 5429 // indicates the declaration was an implicit declaration, which gets 5430 // warned about separately via -Wimplicit-function-declaration. We also 5431 // suppress the warning when we know the function has a prototype. 5432 if (!FTI.hasPrototype && FTI.NumParams == 0 && !FTI.isVariadic && 5433 FTI.getLParenLoc().isValid()) 5434 S.Diag(DeclType.Loc, diag::warn_strict_prototypes) 5435 << IsBlock 5436 << FixItHint::CreateInsertion(FTI.getRParenLoc(), "void"); 5437 IsBlock = false; 5438 break; 5439 } 5440 default: 5441 break; 5442 } 5443 } 5444 } 5445 5446 assert(!T.isNull() && "T must not be null after this point"); 5447 5448 if (LangOpts.CPlusPlus && T->isFunctionType()) { 5449 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>(); 5450 assert(FnTy && "Why oh why is there not a FunctionProtoType here?"); 5451 5452 // C++ 8.3.5p4: 5453 // A cv-qualifier-seq shall only be part of the function type 5454 // for a nonstatic member function, the function type to which a pointer 5455 // to member refers, or the top-level function type of a function typedef 5456 // declaration. 5457 // 5458 // Core issue 547 also allows cv-qualifiers on function types that are 5459 // top-level template type arguments. 5460 enum { 5461 NonMember, 5462 Member, 5463 ExplicitObjectMember, 5464 DeductionGuide 5465 } Kind = NonMember; 5466 if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName) 5467 Kind = DeductionGuide; 5468 else if (!D.getCXXScopeSpec().isSet()) { 5469 if ((D.getContext() == DeclaratorContext::Member || 5470 D.getContext() == DeclaratorContext::LambdaExpr) && 5471 !D.getDeclSpec().isFriendSpecified()) 5472 Kind = Member; 5473 } else { 5474 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec()); 5475 if (!DC || DC->isRecord()) 5476 Kind = Member; 5477 } 5478 5479 if (Kind == Member) { 5480 unsigned I; 5481 if (D.isFunctionDeclarator(I)) { 5482 const DeclaratorChunk &Chunk = D.getTypeObject(I); 5483 if (Chunk.Fun.NumParams) { 5484 auto *P = dyn_cast_or_null<ParmVarDecl>(Chunk.Fun.Params->Param); 5485 if (P && P->isExplicitObjectParameter()) 5486 Kind = ExplicitObjectMember; 5487 } 5488 } 5489 } 5490 5491 // C++11 [dcl.fct]p6 (w/DR1417): 5492 // An attempt to specify a function type with a cv-qualifier-seq or a 5493 // ref-qualifier (including by typedef-name) is ill-formed unless it is: 5494 // - the function type for a non-static member function, 5495 // - the function type to which a pointer to member refers, 5496 // - the top-level function type of a function typedef declaration or 5497 // alias-declaration, 5498 // - the type-id in the default argument of a type-parameter, or 5499 // - the type-id of a template-argument for a type-parameter 5500 // 5501 // C++23 [dcl.fct]p6 (P0847R7) 5502 // ... A member-declarator with an explicit-object-parameter-declaration 5503 // shall not include a ref-qualifier or a cv-qualifier-seq and shall not be 5504 // declared static or virtual ... 5505 // 5506 // FIXME: Checking this here is insufficient. We accept-invalid on: 5507 // 5508 // template<typename T> struct S { void f(T); }; 5509 // S<int() const> s; 5510 // 5511 // ... for instance. 5512 if (IsQualifiedFunction && 5513 // Check for non-static member function and not and 5514 // explicit-object-parameter-declaration 5515 (Kind != Member || D.isExplicitObjectMemberFunction() || 5516 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static || 5517 (D.getContext() == clang::DeclaratorContext::Member && 5518 D.isStaticMember())) && 5519 !IsTypedefName && D.getContext() != DeclaratorContext::TemplateArg && 5520 D.getContext() != DeclaratorContext::TemplateTypeArg) { 5521 SourceLocation Loc = D.getBeginLoc(); 5522 SourceRange RemovalRange; 5523 unsigned I; 5524 if (D.isFunctionDeclarator(I)) { 5525 SmallVector<SourceLocation, 4> RemovalLocs; 5526 const DeclaratorChunk &Chunk = D.getTypeObject(I); 5527 assert(Chunk.Kind == DeclaratorChunk::Function); 5528 5529 if (Chunk.Fun.hasRefQualifier()) 5530 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc()); 5531 5532 if (Chunk.Fun.hasMethodTypeQualifiers()) 5533 Chunk.Fun.MethodQualifiers->forEachQualifier( 5534 [&](DeclSpec::TQ TypeQual, StringRef QualName, 5535 SourceLocation SL) { RemovalLocs.push_back(SL); }); 5536 5537 if (!RemovalLocs.empty()) { 5538 llvm::sort(RemovalLocs, 5539 BeforeThanCompare<SourceLocation>(S.getSourceManager())); 5540 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back()); 5541 Loc = RemovalLocs.front(); 5542 } 5543 } 5544 5545 S.Diag(Loc, diag::err_invalid_qualified_function_type) 5546 << Kind << D.isFunctionDeclarator() << T 5547 << getFunctionQualifiersAsString(FnTy) 5548 << FixItHint::CreateRemoval(RemovalRange); 5549 5550 // Strip the cv-qualifiers and ref-qualifiers from the type. 5551 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo(); 5552 EPI.TypeQuals.removeCVRQualifiers(); 5553 EPI.RefQualifier = RQ_None; 5554 5555 T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(), 5556 EPI); 5557 // Rebuild any parens around the identifier in the function type. 5558 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 5559 if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren) 5560 break; 5561 T = S.BuildParenType(T); 5562 } 5563 } 5564 } 5565 5566 // Apply any undistributed attributes from the declaration or declarator. 5567 ParsedAttributesView NonSlidingAttrs; 5568 for (ParsedAttr &AL : D.getDeclarationAttributes()) { 5569 if (!AL.slidesFromDeclToDeclSpecLegacyBehavior()) { 5570 NonSlidingAttrs.addAtEnd(&AL); 5571 } 5572 } 5573 processTypeAttrs(state, T, TAL_DeclName, NonSlidingAttrs); 5574 processTypeAttrs(state, T, TAL_DeclName, D.getAttributes()); 5575 5576 // Diagnose any ignored type attributes. 5577 state.diagnoseIgnoredTypeAttrs(T); 5578 5579 // C++0x [dcl.constexpr]p9: 5580 // A constexpr specifier used in an object declaration declares the object 5581 // as const. 5582 if (D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Constexpr && 5583 T->isObjectType()) 5584 T.addConst(); 5585 5586 // C++2a [dcl.fct]p4: 5587 // A parameter with volatile-qualified type is deprecated 5588 if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20 && 5589 (D.getContext() == DeclaratorContext::Prototype || 5590 D.getContext() == DeclaratorContext::LambdaExprParameter)) 5591 S.Diag(D.getIdentifierLoc(), diag::warn_deprecated_volatile_param) << T; 5592 5593 // If there was an ellipsis in the declarator, the declaration declares a 5594 // parameter pack whose type may be a pack expansion type. 5595 if (D.hasEllipsis()) { 5596 // C++0x [dcl.fct]p13: 5597 // A declarator-id or abstract-declarator containing an ellipsis shall 5598 // only be used in a parameter-declaration. Such a parameter-declaration 5599 // is a parameter pack (14.5.3). [...] 5600 switch (D.getContext()) { 5601 case DeclaratorContext::Prototype: 5602 case DeclaratorContext::LambdaExprParameter: 5603 case DeclaratorContext::RequiresExpr: 5604 // C++0x [dcl.fct]p13: 5605 // [...] When it is part of a parameter-declaration-clause, the 5606 // parameter pack is a function parameter pack (14.5.3). The type T 5607 // of the declarator-id of the function parameter pack shall contain 5608 // a template parameter pack; each template parameter pack in T is 5609 // expanded by the function parameter pack. 5610 // 5611 // We represent function parameter packs as function parameters whose 5612 // type is a pack expansion. 5613 if (!T->containsUnexpandedParameterPack() && 5614 (!LangOpts.CPlusPlus20 || !T->getContainedAutoType())) { 5615 S.Diag(D.getEllipsisLoc(), 5616 diag::err_function_parameter_pack_without_parameter_packs) 5617 << T << D.getSourceRange(); 5618 D.setEllipsisLoc(SourceLocation()); 5619 } else { 5620 T = Context.getPackExpansionType(T, std::nullopt, 5621 /*ExpectPackInType=*/false); 5622 } 5623 break; 5624 case DeclaratorContext::TemplateParam: 5625 // C++0x [temp.param]p15: 5626 // If a template-parameter is a [...] is a parameter-declaration that 5627 // declares a parameter pack (8.3.5), then the template-parameter is a 5628 // template parameter pack (14.5.3). 5629 // 5630 // Note: core issue 778 clarifies that, if there are any unexpanded 5631 // parameter packs in the type of the non-type template parameter, then 5632 // it expands those parameter packs. 5633 if (T->containsUnexpandedParameterPack()) 5634 T = Context.getPackExpansionType(T, std::nullopt); 5635 else 5636 S.Diag(D.getEllipsisLoc(), 5637 LangOpts.CPlusPlus11 5638 ? diag::warn_cxx98_compat_variadic_templates 5639 : diag::ext_variadic_templates); 5640 break; 5641 5642 case DeclaratorContext::File: 5643 case DeclaratorContext::KNRTypeList: 5644 case DeclaratorContext::ObjCParameter: // FIXME: special diagnostic here? 5645 case DeclaratorContext::ObjCResult: // FIXME: special diagnostic here? 5646 case DeclaratorContext::TypeName: 5647 case DeclaratorContext::FunctionalCast: 5648 case DeclaratorContext::CXXNew: 5649 case DeclaratorContext::AliasDecl: 5650 case DeclaratorContext::AliasTemplate: 5651 case DeclaratorContext::Member: 5652 case DeclaratorContext::Block: 5653 case DeclaratorContext::ForInit: 5654 case DeclaratorContext::SelectionInit: 5655 case DeclaratorContext::Condition: 5656 case DeclaratorContext::CXXCatch: 5657 case DeclaratorContext::ObjCCatch: 5658 case DeclaratorContext::BlockLiteral: 5659 case DeclaratorContext::LambdaExpr: 5660 case DeclaratorContext::ConversionId: 5661 case DeclaratorContext::TrailingReturn: 5662 case DeclaratorContext::TrailingReturnVar: 5663 case DeclaratorContext::TemplateArg: 5664 case DeclaratorContext::TemplateTypeArg: 5665 case DeclaratorContext::Association: 5666 // FIXME: We may want to allow parameter packs in block-literal contexts 5667 // in the future. 5668 S.Diag(D.getEllipsisLoc(), 5669 diag::err_ellipsis_in_declarator_not_parameter); 5670 D.setEllipsisLoc(SourceLocation()); 5671 break; 5672 } 5673 } 5674 5675 assert(!T.isNull() && "T must not be null at the end of this function"); 5676 if (!AreDeclaratorChunksValid) 5677 return Context.getTrivialTypeSourceInfo(T); 5678 return GetTypeSourceInfoForDeclarator(state, T, TInfo); 5679 } 5680 5681 TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D) { 5682 // Determine the type of the declarator. Not all forms of declarator 5683 // have a type. 5684 5685 TypeProcessingState state(*this, D); 5686 5687 TypeSourceInfo *ReturnTypeInfo = nullptr; 5688 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); 5689 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount) 5690 inferARCWriteback(state, T); 5691 5692 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo); 5693 } 5694 5695 static void transferARCOwnershipToDeclSpec(Sema &S, 5696 QualType &declSpecTy, 5697 Qualifiers::ObjCLifetime ownership) { 5698 if (declSpecTy->isObjCRetainableType() && 5699 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) { 5700 Qualifiers qs; 5701 qs.addObjCLifetime(ownership); 5702 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs); 5703 } 5704 } 5705 5706 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, 5707 Qualifiers::ObjCLifetime ownership, 5708 unsigned chunkIndex) { 5709 Sema &S = state.getSema(); 5710 Declarator &D = state.getDeclarator(); 5711 5712 // Look for an explicit lifetime attribute. 5713 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex); 5714 if (chunk.getAttrs().hasAttribute(ParsedAttr::AT_ObjCOwnership)) 5715 return; 5716 5717 const char *attrStr = nullptr; 5718 switch (ownership) { 5719 case Qualifiers::OCL_None: llvm_unreachable("no ownership!"); 5720 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break; 5721 case Qualifiers::OCL_Strong: attrStr = "strong"; break; 5722 case Qualifiers::OCL_Weak: attrStr = "weak"; break; 5723 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break; 5724 } 5725 5726 IdentifierLoc *Arg = new (S.Context) IdentifierLoc; 5727 Arg->Ident = &S.Context.Idents.get(attrStr); 5728 Arg->Loc = SourceLocation(); 5729 5730 ArgsUnion Args(Arg); 5731 5732 // If there wasn't one, add one (with an invalid source location 5733 // so that we don't make an AttributedType for it). 5734 ParsedAttr *attr = D.getAttributePool().create( 5735 &S.Context.Idents.get("objc_ownership"), SourceLocation(), 5736 /*scope*/ nullptr, SourceLocation(), 5737 /*args*/ &Args, 1, ParsedAttr::Form::GNU()); 5738 chunk.getAttrs().addAtEnd(attr); 5739 // TODO: mark whether we did this inference? 5740 } 5741 5742 /// Used for transferring ownership in casts resulting in l-values. 5743 static void transferARCOwnership(TypeProcessingState &state, 5744 QualType &declSpecTy, 5745 Qualifiers::ObjCLifetime ownership) { 5746 Sema &S = state.getSema(); 5747 Declarator &D = state.getDeclarator(); 5748 5749 int inner = -1; 5750 bool hasIndirection = false; 5751 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 5752 DeclaratorChunk &chunk = D.getTypeObject(i); 5753 switch (chunk.Kind) { 5754 case DeclaratorChunk::Paren: 5755 // Ignore parens. 5756 break; 5757 5758 case DeclaratorChunk::Array: 5759 case DeclaratorChunk::Reference: 5760 case DeclaratorChunk::Pointer: 5761 if (inner != -1) 5762 hasIndirection = true; 5763 inner = i; 5764 break; 5765 5766 case DeclaratorChunk::BlockPointer: 5767 if (inner != -1) 5768 transferARCOwnershipToDeclaratorChunk(state, ownership, i); 5769 return; 5770 5771 case DeclaratorChunk::Function: 5772 case DeclaratorChunk::MemberPointer: 5773 case DeclaratorChunk::Pipe: 5774 return; 5775 } 5776 } 5777 5778 if (inner == -1) 5779 return; 5780 5781 DeclaratorChunk &chunk = D.getTypeObject(inner); 5782 if (chunk.Kind == DeclaratorChunk::Pointer) { 5783 if (declSpecTy->isObjCRetainableType()) 5784 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); 5785 if (declSpecTy->isObjCObjectType() && hasIndirection) 5786 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner); 5787 } else { 5788 assert(chunk.Kind == DeclaratorChunk::Array || 5789 chunk.Kind == DeclaratorChunk::Reference); 5790 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); 5791 } 5792 } 5793 5794 TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) { 5795 TypeProcessingState state(*this, D); 5796 5797 TypeSourceInfo *ReturnTypeInfo = nullptr; 5798 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); 5799 5800 if (getLangOpts().ObjC) { 5801 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy); 5802 if (ownership != Qualifiers::OCL_None) 5803 transferARCOwnership(state, declSpecTy, ownership); 5804 } 5805 5806 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo); 5807 } 5808 5809 static void fillAttributedTypeLoc(AttributedTypeLoc TL, 5810 TypeProcessingState &State) { 5811 TL.setAttr(State.takeAttrForAttributedType(TL.getTypePtr())); 5812 } 5813 5814 static void fillHLSLAttributedResourceTypeLoc(HLSLAttributedResourceTypeLoc TL, 5815 TypeProcessingState &State) { 5816 HLSLAttributedResourceLocInfo LocInfo = 5817 State.getSema().HLSL().TakeLocForHLSLAttribute(TL.getTypePtr()); 5818 TL.setSourceRange(LocInfo.Range); 5819 TL.setContainedTypeSourceInfo(LocInfo.ContainedTyInfo); 5820 } 5821 5822 static void fillMatrixTypeLoc(MatrixTypeLoc MTL, 5823 const ParsedAttributesView &Attrs) { 5824 for (const ParsedAttr &AL : Attrs) { 5825 if (AL.getKind() == ParsedAttr::AT_MatrixType) { 5826 MTL.setAttrNameLoc(AL.getLoc()); 5827 MTL.setAttrRowOperand(AL.getArgAsExpr(0)); 5828 MTL.setAttrColumnOperand(AL.getArgAsExpr(1)); 5829 MTL.setAttrOperandParensRange(SourceRange()); 5830 return; 5831 } 5832 } 5833 5834 llvm_unreachable("no matrix_type attribute found at the expected location!"); 5835 } 5836 5837 namespace { 5838 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> { 5839 Sema &SemaRef; 5840 ASTContext &Context; 5841 TypeProcessingState &State; 5842 const DeclSpec &DS; 5843 5844 public: 5845 TypeSpecLocFiller(Sema &S, ASTContext &Context, TypeProcessingState &State, 5846 const DeclSpec &DS) 5847 : SemaRef(S), Context(Context), State(State), DS(DS) {} 5848 5849 void VisitAttributedTypeLoc(AttributedTypeLoc TL) { 5850 Visit(TL.getModifiedLoc()); 5851 fillAttributedTypeLoc(TL, State); 5852 } 5853 void VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) { 5854 Visit(TL.getWrappedLoc()); 5855 } 5856 void VisitHLSLAttributedResourceTypeLoc(HLSLAttributedResourceTypeLoc TL) { 5857 Visit(TL.getWrappedLoc()); 5858 fillHLSLAttributedResourceTypeLoc(TL, State); 5859 } 5860 void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) { 5861 Visit(TL.getInnerLoc()); 5862 TL.setExpansionLoc( 5863 State.getExpansionLocForMacroQualifiedType(TL.getTypePtr())); 5864 } 5865 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 5866 Visit(TL.getUnqualifiedLoc()); 5867 } 5868 // Allow to fill pointee's type locations, e.g., 5869 // int __attr * __attr * __attr *p; 5870 void VisitPointerTypeLoc(PointerTypeLoc TL) { Visit(TL.getNextTypeLoc()); } 5871 void VisitTypedefTypeLoc(TypedefTypeLoc TL) { 5872 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 5873 } 5874 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { 5875 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 5876 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires 5877 // addition field. What we have is good enough for display of location 5878 // of 'fixit' on interface name. 5879 TL.setNameEndLoc(DS.getEndLoc()); 5880 } 5881 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { 5882 TypeSourceInfo *RepTInfo = nullptr; 5883 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo); 5884 TL.copy(RepTInfo->getTypeLoc()); 5885 } 5886 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 5887 TypeSourceInfo *RepTInfo = nullptr; 5888 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo); 5889 TL.copy(RepTInfo->getTypeLoc()); 5890 } 5891 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) { 5892 TypeSourceInfo *TInfo = nullptr; 5893 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 5894 5895 // If we got no declarator info from previous Sema routines, 5896 // just fill with the typespec loc. 5897 if (!TInfo) { 5898 TL.initialize(Context, DS.getTypeSpecTypeNameLoc()); 5899 return; 5900 } 5901 5902 TypeLoc OldTL = TInfo->getTypeLoc(); 5903 if (TInfo->getType()->getAs<ElaboratedType>()) { 5904 ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>(); 5905 TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc() 5906 .castAs<TemplateSpecializationTypeLoc>(); 5907 TL.copy(NamedTL); 5908 } else { 5909 TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>()); 5910 assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc()); 5911 } 5912 5913 } 5914 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { 5915 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr || 5916 DS.getTypeSpecType() == DeclSpec::TST_typeof_unqualExpr); 5917 TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); 5918 TL.setParensRange(DS.getTypeofParensRange()); 5919 } 5920 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { 5921 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType || 5922 DS.getTypeSpecType() == DeclSpec::TST_typeof_unqualType); 5923 TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); 5924 TL.setParensRange(DS.getTypeofParensRange()); 5925 assert(DS.getRepAsType()); 5926 TypeSourceInfo *TInfo = nullptr; 5927 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 5928 TL.setUnmodifiedTInfo(TInfo); 5929 } 5930 void VisitDecltypeTypeLoc(DecltypeTypeLoc TL) { 5931 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype); 5932 TL.setDecltypeLoc(DS.getTypeSpecTypeLoc()); 5933 TL.setRParenLoc(DS.getTypeofParensRange().getEnd()); 5934 } 5935 void VisitPackIndexingTypeLoc(PackIndexingTypeLoc TL) { 5936 assert(DS.getTypeSpecType() == DeclSpec::TST_typename_pack_indexing); 5937 TL.setEllipsisLoc(DS.getEllipsisLoc()); 5938 } 5939 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) { 5940 assert(DS.isTransformTypeTrait(DS.getTypeSpecType())); 5941 TL.setKWLoc(DS.getTypeSpecTypeLoc()); 5942 TL.setParensRange(DS.getTypeofParensRange()); 5943 assert(DS.getRepAsType()); 5944 TypeSourceInfo *TInfo = nullptr; 5945 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 5946 TL.setUnderlyingTInfo(TInfo); 5947 } 5948 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { 5949 // By default, use the source location of the type specifier. 5950 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc()); 5951 if (TL.needsExtraLocalData()) { 5952 // Set info for the written builtin specifiers. 5953 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs(); 5954 // Try to have a meaningful source location. 5955 if (TL.getWrittenSignSpec() != TypeSpecifierSign::Unspecified) 5956 TL.expandBuiltinRange(DS.getTypeSpecSignLoc()); 5957 if (TL.getWrittenWidthSpec() != TypeSpecifierWidth::Unspecified) 5958 TL.expandBuiltinRange(DS.getTypeSpecWidthRange()); 5959 } 5960 } 5961 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { 5962 if (DS.getTypeSpecType() == TST_typename) { 5963 TypeSourceInfo *TInfo = nullptr; 5964 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 5965 if (TInfo) 5966 if (auto ETL = TInfo->getTypeLoc().getAs<ElaboratedTypeLoc>()) { 5967 TL.copy(ETL); 5968 return; 5969 } 5970 } 5971 const ElaboratedType *T = TL.getTypePtr(); 5972 TL.setElaboratedKeywordLoc(T->getKeyword() != ElaboratedTypeKeyword::None 5973 ? DS.getTypeSpecTypeLoc() 5974 : SourceLocation()); 5975 const CXXScopeSpec& SS = DS.getTypeSpecScope(); 5976 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 5977 Visit(TL.getNextTypeLoc().getUnqualifiedLoc()); 5978 } 5979 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { 5980 assert(DS.getTypeSpecType() == TST_typename); 5981 TypeSourceInfo *TInfo = nullptr; 5982 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 5983 assert(TInfo); 5984 TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>()); 5985 } 5986 void VisitDependentTemplateSpecializationTypeLoc( 5987 DependentTemplateSpecializationTypeLoc TL) { 5988 assert(DS.getTypeSpecType() == TST_typename); 5989 TypeSourceInfo *TInfo = nullptr; 5990 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 5991 assert(TInfo); 5992 TL.copy( 5993 TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>()); 5994 } 5995 void VisitAutoTypeLoc(AutoTypeLoc TL) { 5996 assert(DS.getTypeSpecType() == TST_auto || 5997 DS.getTypeSpecType() == TST_decltype_auto || 5998 DS.getTypeSpecType() == TST_auto_type || 5999 DS.getTypeSpecType() == TST_unspecified); 6000 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 6001 if (DS.getTypeSpecType() == TST_decltype_auto) 6002 TL.setRParenLoc(DS.getTypeofParensRange().getEnd()); 6003 if (!DS.isConstrainedAuto()) 6004 return; 6005 TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId(); 6006 if (!TemplateId) 6007 return; 6008 6009 NestedNameSpecifierLoc NNS = 6010 (DS.getTypeSpecScope().isNotEmpty() 6011 ? DS.getTypeSpecScope().getWithLocInContext(Context) 6012 : NestedNameSpecifierLoc()); 6013 TemplateArgumentListInfo TemplateArgsInfo(TemplateId->LAngleLoc, 6014 TemplateId->RAngleLoc); 6015 if (TemplateId->NumArgs > 0) { 6016 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 6017 TemplateId->NumArgs); 6018 SemaRef.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo); 6019 } 6020 DeclarationNameInfo DNI = DeclarationNameInfo( 6021 TL.getTypePtr()->getTypeConstraintConcept()->getDeclName(), 6022 TemplateId->TemplateNameLoc); 6023 6024 NamedDecl *FoundDecl; 6025 if (auto TN = TemplateId->Template.get(); 6026 UsingShadowDecl *USD = TN.getAsUsingShadowDecl()) 6027 FoundDecl = cast<NamedDecl>(USD); 6028 else 6029 FoundDecl = cast_if_present<NamedDecl>(TN.getAsTemplateDecl()); 6030 6031 auto *CR = ConceptReference::Create( 6032 Context, NNS, TemplateId->TemplateKWLoc, DNI, FoundDecl, 6033 /*NamedDecl=*/TL.getTypePtr()->getTypeConstraintConcept(), 6034 ASTTemplateArgumentListInfo::Create(Context, TemplateArgsInfo)); 6035 TL.setConceptReference(CR); 6036 } 6037 void VisitTagTypeLoc(TagTypeLoc TL) { 6038 TL.setNameLoc(DS.getTypeSpecTypeNameLoc()); 6039 } 6040 void VisitAtomicTypeLoc(AtomicTypeLoc TL) { 6041 // An AtomicTypeLoc can come from either an _Atomic(...) type specifier 6042 // or an _Atomic qualifier. 6043 if (DS.getTypeSpecType() == DeclSpec::TST_atomic) { 6044 TL.setKWLoc(DS.getTypeSpecTypeLoc()); 6045 TL.setParensRange(DS.getTypeofParensRange()); 6046 6047 TypeSourceInfo *TInfo = nullptr; 6048 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 6049 assert(TInfo); 6050 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc()); 6051 } else { 6052 TL.setKWLoc(DS.getAtomicSpecLoc()); 6053 // No parens, to indicate this was spelled as an _Atomic qualifier. 6054 TL.setParensRange(SourceRange()); 6055 Visit(TL.getValueLoc()); 6056 } 6057 } 6058 6059 void VisitPipeTypeLoc(PipeTypeLoc TL) { 6060 TL.setKWLoc(DS.getTypeSpecTypeLoc()); 6061 6062 TypeSourceInfo *TInfo = nullptr; 6063 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 6064 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc()); 6065 } 6066 6067 void VisitExtIntTypeLoc(BitIntTypeLoc TL) { 6068 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 6069 } 6070 6071 void VisitDependentExtIntTypeLoc(DependentBitIntTypeLoc TL) { 6072 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 6073 } 6074 6075 void VisitTypeLoc(TypeLoc TL) { 6076 // FIXME: add other typespec types and change this to an assert. 6077 TL.initialize(Context, DS.getTypeSpecTypeLoc()); 6078 } 6079 }; 6080 6081 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> { 6082 ASTContext &Context; 6083 TypeProcessingState &State; 6084 const DeclaratorChunk &Chunk; 6085 6086 public: 6087 DeclaratorLocFiller(ASTContext &Context, TypeProcessingState &State, 6088 const DeclaratorChunk &Chunk) 6089 : Context(Context), State(State), Chunk(Chunk) {} 6090 6091 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 6092 llvm_unreachable("qualified type locs not expected here!"); 6093 } 6094 void VisitDecayedTypeLoc(DecayedTypeLoc TL) { 6095 llvm_unreachable("decayed type locs not expected here!"); 6096 } 6097 void VisitArrayParameterTypeLoc(ArrayParameterTypeLoc TL) { 6098 llvm_unreachable("array parameter type locs not expected here!"); 6099 } 6100 6101 void VisitAttributedTypeLoc(AttributedTypeLoc TL) { 6102 fillAttributedTypeLoc(TL, State); 6103 } 6104 void VisitCountAttributedTypeLoc(CountAttributedTypeLoc TL) { 6105 // nothing 6106 } 6107 void VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) { 6108 // nothing 6109 } 6110 void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) { 6111 // nothing 6112 } 6113 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { 6114 assert(Chunk.Kind == DeclaratorChunk::BlockPointer); 6115 TL.setCaretLoc(Chunk.Loc); 6116 } 6117 void VisitPointerTypeLoc(PointerTypeLoc TL) { 6118 assert(Chunk.Kind == DeclaratorChunk::Pointer); 6119 TL.setStarLoc(Chunk.Loc); 6120 } 6121 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 6122 assert(Chunk.Kind == DeclaratorChunk::Pointer); 6123 TL.setStarLoc(Chunk.Loc); 6124 } 6125 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { 6126 assert(Chunk.Kind == DeclaratorChunk::MemberPointer); 6127 const CXXScopeSpec& SS = Chunk.Mem.Scope(); 6128 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context); 6129 6130 const Type* ClsTy = TL.getClass(); 6131 QualType ClsQT = QualType(ClsTy, 0); 6132 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0); 6133 // Now copy source location info into the type loc component. 6134 TypeLoc ClsTL = ClsTInfo->getTypeLoc(); 6135 switch (NNSLoc.getNestedNameSpecifier()->getKind()) { 6136 case NestedNameSpecifier::Identifier: 6137 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc"); 6138 { 6139 DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>(); 6140 DNTLoc.setElaboratedKeywordLoc(SourceLocation()); 6141 DNTLoc.setQualifierLoc(NNSLoc.getPrefix()); 6142 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc()); 6143 } 6144 break; 6145 6146 case NestedNameSpecifier::TypeSpec: 6147 case NestedNameSpecifier::TypeSpecWithTemplate: 6148 if (isa<ElaboratedType>(ClsTy)) { 6149 ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>(); 6150 ETLoc.setElaboratedKeywordLoc(SourceLocation()); 6151 ETLoc.setQualifierLoc(NNSLoc.getPrefix()); 6152 TypeLoc NamedTL = ETLoc.getNamedTypeLoc(); 6153 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc()); 6154 } else { 6155 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc()); 6156 } 6157 break; 6158 6159 case NestedNameSpecifier::Namespace: 6160 case NestedNameSpecifier::NamespaceAlias: 6161 case NestedNameSpecifier::Global: 6162 case NestedNameSpecifier::Super: 6163 llvm_unreachable("Nested-name-specifier must name a type"); 6164 } 6165 6166 // Finally fill in MemberPointerLocInfo fields. 6167 TL.setStarLoc(Chunk.Mem.StarLoc); 6168 TL.setClassTInfo(ClsTInfo); 6169 } 6170 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { 6171 assert(Chunk.Kind == DeclaratorChunk::Reference); 6172 // 'Amp' is misleading: this might have been originally 6173 /// spelled with AmpAmp. 6174 TL.setAmpLoc(Chunk.Loc); 6175 } 6176 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { 6177 assert(Chunk.Kind == DeclaratorChunk::Reference); 6178 assert(!Chunk.Ref.LValueRef); 6179 TL.setAmpAmpLoc(Chunk.Loc); 6180 } 6181 void VisitArrayTypeLoc(ArrayTypeLoc TL) { 6182 assert(Chunk.Kind == DeclaratorChunk::Array); 6183 TL.setLBracketLoc(Chunk.Loc); 6184 TL.setRBracketLoc(Chunk.EndLoc); 6185 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts)); 6186 } 6187 void VisitFunctionTypeLoc(FunctionTypeLoc TL) { 6188 assert(Chunk.Kind == DeclaratorChunk::Function); 6189 TL.setLocalRangeBegin(Chunk.Loc); 6190 TL.setLocalRangeEnd(Chunk.EndLoc); 6191 6192 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun; 6193 TL.setLParenLoc(FTI.getLParenLoc()); 6194 TL.setRParenLoc(FTI.getRParenLoc()); 6195 for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) { 6196 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 6197 TL.setParam(tpi++, Param); 6198 } 6199 TL.setExceptionSpecRange(FTI.getExceptionSpecRange()); 6200 } 6201 void VisitParenTypeLoc(ParenTypeLoc TL) { 6202 assert(Chunk.Kind == DeclaratorChunk::Paren); 6203 TL.setLParenLoc(Chunk.Loc); 6204 TL.setRParenLoc(Chunk.EndLoc); 6205 } 6206 void VisitPipeTypeLoc(PipeTypeLoc TL) { 6207 assert(Chunk.Kind == DeclaratorChunk::Pipe); 6208 TL.setKWLoc(Chunk.Loc); 6209 } 6210 void VisitBitIntTypeLoc(BitIntTypeLoc TL) { 6211 TL.setNameLoc(Chunk.Loc); 6212 } 6213 void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) { 6214 TL.setExpansionLoc(Chunk.Loc); 6215 } 6216 void VisitVectorTypeLoc(VectorTypeLoc TL) { TL.setNameLoc(Chunk.Loc); } 6217 void VisitDependentVectorTypeLoc(DependentVectorTypeLoc TL) { 6218 TL.setNameLoc(Chunk.Loc); 6219 } 6220 void VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) { 6221 TL.setNameLoc(Chunk.Loc); 6222 } 6223 void 6224 VisitDependentSizedExtVectorTypeLoc(DependentSizedExtVectorTypeLoc TL) { 6225 TL.setNameLoc(Chunk.Loc); 6226 } 6227 void VisitMatrixTypeLoc(MatrixTypeLoc TL) { 6228 fillMatrixTypeLoc(TL, Chunk.getAttrs()); 6229 } 6230 6231 void VisitTypeLoc(TypeLoc TL) { 6232 llvm_unreachable("unsupported TypeLoc kind in declarator!"); 6233 } 6234 }; 6235 } // end anonymous namespace 6236 6237 static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) { 6238 SourceLocation Loc; 6239 switch (Chunk.Kind) { 6240 case DeclaratorChunk::Function: 6241 case DeclaratorChunk::Array: 6242 case DeclaratorChunk::Paren: 6243 case DeclaratorChunk::Pipe: 6244 llvm_unreachable("cannot be _Atomic qualified"); 6245 6246 case DeclaratorChunk::Pointer: 6247 Loc = Chunk.Ptr.AtomicQualLoc; 6248 break; 6249 6250 case DeclaratorChunk::BlockPointer: 6251 case DeclaratorChunk::Reference: 6252 case DeclaratorChunk::MemberPointer: 6253 // FIXME: Provide a source location for the _Atomic keyword. 6254 break; 6255 } 6256 6257 ATL.setKWLoc(Loc); 6258 ATL.setParensRange(SourceRange()); 6259 } 6260 6261 static void 6262 fillDependentAddressSpaceTypeLoc(DependentAddressSpaceTypeLoc DASTL, 6263 const ParsedAttributesView &Attrs) { 6264 for (const ParsedAttr &AL : Attrs) { 6265 if (AL.getKind() == ParsedAttr::AT_AddressSpace) { 6266 DASTL.setAttrNameLoc(AL.getLoc()); 6267 DASTL.setAttrExprOperand(AL.getArgAsExpr(0)); 6268 DASTL.setAttrOperandParensRange(SourceRange()); 6269 return; 6270 } 6271 } 6272 6273 llvm_unreachable( 6274 "no address_space attribute found at the expected location!"); 6275 } 6276 6277 /// Create and instantiate a TypeSourceInfo with type source information. 6278 /// 6279 /// \param T QualType referring to the type as written in source code. 6280 /// 6281 /// \param ReturnTypeInfo For declarators whose return type does not show 6282 /// up in the normal place in the declaration specifiers (such as a C++ 6283 /// conversion function), this pointer will refer to a type source information 6284 /// for that return type. 6285 static TypeSourceInfo * 6286 GetTypeSourceInfoForDeclarator(TypeProcessingState &State, 6287 QualType T, TypeSourceInfo *ReturnTypeInfo) { 6288 Sema &S = State.getSema(); 6289 Declarator &D = State.getDeclarator(); 6290 6291 TypeSourceInfo *TInfo = S.Context.CreateTypeSourceInfo(T); 6292 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc(); 6293 6294 // Handle parameter packs whose type is a pack expansion. 6295 if (isa<PackExpansionType>(T)) { 6296 CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc()); 6297 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); 6298 } 6299 6300 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 6301 // Microsoft property fields can have multiple sizeless array chunks 6302 // (i.e. int x[][][]). Don't create more than one level of incomplete array. 6303 if (CurrTL.getTypeLocClass() == TypeLoc::IncompleteArray && e != 1 && 6304 D.getDeclSpec().getAttributes().hasMSPropertyAttr()) 6305 continue; 6306 6307 // An AtomicTypeLoc might be produced by an atomic qualifier in this 6308 // declarator chunk. 6309 if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) { 6310 fillAtomicQualLoc(ATL, D.getTypeObject(i)); 6311 CurrTL = ATL.getValueLoc().getUnqualifiedLoc(); 6312 } 6313 6314 bool HasDesugaredTypeLoc = true; 6315 while (HasDesugaredTypeLoc) { 6316 switch (CurrTL.getTypeLocClass()) { 6317 case TypeLoc::MacroQualified: { 6318 auto TL = CurrTL.castAs<MacroQualifiedTypeLoc>(); 6319 TL.setExpansionLoc( 6320 State.getExpansionLocForMacroQualifiedType(TL.getTypePtr())); 6321 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); 6322 break; 6323 } 6324 6325 case TypeLoc::Attributed: { 6326 auto TL = CurrTL.castAs<AttributedTypeLoc>(); 6327 fillAttributedTypeLoc(TL, State); 6328 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); 6329 break; 6330 } 6331 6332 case TypeLoc::Adjusted: 6333 case TypeLoc::BTFTagAttributed: { 6334 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); 6335 break; 6336 } 6337 6338 case TypeLoc::DependentAddressSpace: { 6339 auto TL = CurrTL.castAs<DependentAddressSpaceTypeLoc>(); 6340 fillDependentAddressSpaceTypeLoc(TL, D.getTypeObject(i).getAttrs()); 6341 CurrTL = TL.getPointeeTypeLoc().getUnqualifiedLoc(); 6342 break; 6343 } 6344 6345 default: 6346 HasDesugaredTypeLoc = false; 6347 break; 6348 } 6349 } 6350 6351 DeclaratorLocFiller(S.Context, State, D.getTypeObject(i)).Visit(CurrTL); 6352 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); 6353 } 6354 6355 // If we have different source information for the return type, use 6356 // that. This really only applies to C++ conversion functions. 6357 if (ReturnTypeInfo) { 6358 TypeLoc TL = ReturnTypeInfo->getTypeLoc(); 6359 assert(TL.getFullDataSize() == CurrTL.getFullDataSize()); 6360 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize()); 6361 } else { 6362 TypeSpecLocFiller(S, S.Context, State, D.getDeclSpec()).Visit(CurrTL); 6363 } 6364 6365 return TInfo; 6366 } 6367 6368 /// Create a LocInfoType to hold the given QualType and TypeSourceInfo. 6369 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) { 6370 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser 6371 // and Sema during declaration parsing. Try deallocating/caching them when 6372 // it's appropriate, instead of allocating them and keeping them around. 6373 LocInfoType *LocT = (LocInfoType *)BumpAlloc.Allocate(sizeof(LocInfoType), 6374 alignof(LocInfoType)); 6375 new (LocT) LocInfoType(T, TInfo); 6376 assert(LocT->getTypeClass() != T->getTypeClass() && 6377 "LocInfoType's TypeClass conflicts with an existing Type class"); 6378 return ParsedType::make(QualType(LocT, 0)); 6379 } 6380 6381 void LocInfoType::getAsStringInternal(std::string &Str, 6382 const PrintingPolicy &Policy) const { 6383 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*" 6384 " was used directly instead of getting the QualType through" 6385 " GetTypeFromParser"); 6386 } 6387 6388 TypeResult Sema::ActOnTypeName(Declarator &D) { 6389 // C99 6.7.6: Type names have no identifier. This is already validated by 6390 // the parser. 6391 assert(D.getIdentifier() == nullptr && 6392 "Type name should have no identifier!"); 6393 6394 TypeSourceInfo *TInfo = GetTypeForDeclarator(D); 6395 QualType T = TInfo->getType(); 6396 if (D.isInvalidType()) 6397 return true; 6398 6399 // Make sure there are no unused decl attributes on the declarator. 6400 // We don't want to do this for ObjC parameters because we're going 6401 // to apply them to the actual parameter declaration. 6402 // Likewise, we don't want to do this for alias declarations, because 6403 // we are actually going to build a declaration from this eventually. 6404 if (D.getContext() != DeclaratorContext::ObjCParameter && 6405 D.getContext() != DeclaratorContext::AliasDecl && 6406 D.getContext() != DeclaratorContext::AliasTemplate) 6407 checkUnusedDeclAttributes(D); 6408 6409 if (getLangOpts().CPlusPlus) { 6410 // Check that there are no default arguments (C++ only). 6411 CheckExtraCXXDefaultArguments(D); 6412 } 6413 6414 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) { 6415 const AutoType *AT = TL.getTypePtr(); 6416 CheckConstrainedAuto(AT, TL.getConceptNameLoc()); 6417 } 6418 return CreateParsedType(T, TInfo); 6419 } 6420 6421 //===----------------------------------------------------------------------===// 6422 // Type Attribute Processing 6423 //===----------------------------------------------------------------------===// 6424 6425 /// Build an AddressSpace index from a constant expression and diagnose any 6426 /// errors related to invalid address_spaces. Returns true on successfully 6427 /// building an AddressSpace index. 6428 static bool BuildAddressSpaceIndex(Sema &S, LangAS &ASIdx, 6429 const Expr *AddrSpace, 6430 SourceLocation AttrLoc) { 6431 if (!AddrSpace->isValueDependent()) { 6432 std::optional<llvm::APSInt> OptAddrSpace = 6433 AddrSpace->getIntegerConstantExpr(S.Context); 6434 if (!OptAddrSpace) { 6435 S.Diag(AttrLoc, diag::err_attribute_argument_type) 6436 << "'address_space'" << AANT_ArgumentIntegerConstant 6437 << AddrSpace->getSourceRange(); 6438 return false; 6439 } 6440 llvm::APSInt &addrSpace = *OptAddrSpace; 6441 6442 // Bounds checking. 6443 if (addrSpace.isSigned()) { 6444 if (addrSpace.isNegative()) { 6445 S.Diag(AttrLoc, diag::err_attribute_address_space_negative) 6446 << AddrSpace->getSourceRange(); 6447 return false; 6448 } 6449 addrSpace.setIsSigned(false); 6450 } 6451 6452 llvm::APSInt max(addrSpace.getBitWidth()); 6453 max = 6454 Qualifiers::MaxAddressSpace - (unsigned)LangAS::FirstTargetAddressSpace; 6455 6456 if (addrSpace > max) { 6457 S.Diag(AttrLoc, diag::err_attribute_address_space_too_high) 6458 << (unsigned)max.getZExtValue() << AddrSpace->getSourceRange(); 6459 return false; 6460 } 6461 6462 ASIdx = 6463 getLangASFromTargetAS(static_cast<unsigned>(addrSpace.getZExtValue())); 6464 return true; 6465 } 6466 6467 // Default value for DependentAddressSpaceTypes 6468 ASIdx = LangAS::Default; 6469 return true; 6470 } 6471 6472 QualType Sema::BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace, 6473 SourceLocation AttrLoc) { 6474 if (!AddrSpace->isValueDependent()) { 6475 if (DiagnoseMultipleAddrSpaceAttributes(*this, T.getAddressSpace(), ASIdx, 6476 AttrLoc)) 6477 return QualType(); 6478 6479 return Context.getAddrSpaceQualType(T, ASIdx); 6480 } 6481 6482 // A check with similar intentions as checking if a type already has an 6483 // address space except for on a dependent types, basically if the 6484 // current type is already a DependentAddressSpaceType then its already 6485 // lined up to have another address space on it and we can't have 6486 // multiple address spaces on the one pointer indirection 6487 if (T->getAs<DependentAddressSpaceType>()) { 6488 Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers); 6489 return QualType(); 6490 } 6491 6492 return Context.getDependentAddressSpaceType(T, AddrSpace, AttrLoc); 6493 } 6494 6495 QualType Sema::BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace, 6496 SourceLocation AttrLoc) { 6497 LangAS ASIdx; 6498 if (!BuildAddressSpaceIndex(*this, ASIdx, AddrSpace, AttrLoc)) 6499 return QualType(); 6500 return BuildAddressSpaceAttr(T, ASIdx, AddrSpace, AttrLoc); 6501 } 6502 6503 static void HandleBTFTypeTagAttribute(QualType &Type, const ParsedAttr &Attr, 6504 TypeProcessingState &State) { 6505 Sema &S = State.getSema(); 6506 6507 // This attribute is only supported in C. 6508 // FIXME: we should implement checkCommonAttributeFeatures() in SemaAttr.cpp 6509 // such that it handles type attributes, and then call that from 6510 // processTypeAttrs() instead of one-off checks like this. 6511 if (!Attr.diagnoseLangOpts(S)) { 6512 Attr.setInvalid(); 6513 return; 6514 } 6515 6516 // Check the number of attribute arguments. 6517 if (Attr.getNumArgs() != 1) { 6518 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 6519 << Attr << 1; 6520 Attr.setInvalid(); 6521 return; 6522 } 6523 6524 // Ensure the argument is a string. 6525 auto *StrLiteral = dyn_cast<StringLiteral>(Attr.getArgAsExpr(0)); 6526 if (!StrLiteral) { 6527 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) 6528 << Attr << AANT_ArgumentString; 6529 Attr.setInvalid(); 6530 return; 6531 } 6532 6533 ASTContext &Ctx = S.Context; 6534 StringRef BTFTypeTag = StrLiteral->getString(); 6535 Type = State.getBTFTagAttributedType( 6536 ::new (Ctx) BTFTypeTagAttr(Ctx, Attr, BTFTypeTag), Type); 6537 } 6538 6539 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the 6540 /// specified type. The attribute contains 1 argument, the id of the address 6541 /// space for the type. 6542 static void HandleAddressSpaceTypeAttribute(QualType &Type, 6543 const ParsedAttr &Attr, 6544 TypeProcessingState &State) { 6545 Sema &S = State.getSema(); 6546 6547 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be 6548 // qualified by an address-space qualifier." 6549 if (Type->isFunctionType()) { 6550 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type); 6551 Attr.setInvalid(); 6552 return; 6553 } 6554 6555 LangAS ASIdx; 6556 if (Attr.getKind() == ParsedAttr::AT_AddressSpace) { 6557 6558 // Check the attribute arguments. 6559 if (Attr.getNumArgs() != 1) { 6560 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr 6561 << 1; 6562 Attr.setInvalid(); 6563 return; 6564 } 6565 6566 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); 6567 LangAS ASIdx; 6568 if (!BuildAddressSpaceIndex(S, ASIdx, ASArgExpr, Attr.getLoc())) { 6569 Attr.setInvalid(); 6570 return; 6571 } 6572 6573 ASTContext &Ctx = S.Context; 6574 auto *ASAttr = 6575 ::new (Ctx) AddressSpaceAttr(Ctx, Attr, static_cast<unsigned>(ASIdx)); 6576 6577 // If the expression is not value dependent (not templated), then we can 6578 // apply the address space qualifiers just to the equivalent type. 6579 // Otherwise, we make an AttributedType with the modified and equivalent 6580 // type the same, and wrap it in a DependentAddressSpaceType. When this 6581 // dependent type is resolved, the qualifier is added to the equivalent type 6582 // later. 6583 QualType T; 6584 if (!ASArgExpr->isValueDependent()) { 6585 QualType EquivType = 6586 S.BuildAddressSpaceAttr(Type, ASIdx, ASArgExpr, Attr.getLoc()); 6587 if (EquivType.isNull()) { 6588 Attr.setInvalid(); 6589 return; 6590 } 6591 T = State.getAttributedType(ASAttr, Type, EquivType); 6592 } else { 6593 T = State.getAttributedType(ASAttr, Type, Type); 6594 T = S.BuildAddressSpaceAttr(T, ASIdx, ASArgExpr, Attr.getLoc()); 6595 } 6596 6597 if (!T.isNull()) 6598 Type = T; 6599 else 6600 Attr.setInvalid(); 6601 } else { 6602 // The keyword-based type attributes imply which address space to use. 6603 ASIdx = S.getLangOpts().SYCLIsDevice ? Attr.asSYCLLangAS() 6604 : Attr.asOpenCLLangAS(); 6605 if (S.getLangOpts().HLSL) 6606 ASIdx = Attr.asHLSLLangAS(); 6607 6608 if (ASIdx == LangAS::Default) 6609 llvm_unreachable("Invalid address space"); 6610 6611 if (DiagnoseMultipleAddrSpaceAttributes(S, Type.getAddressSpace(), ASIdx, 6612 Attr.getLoc())) { 6613 Attr.setInvalid(); 6614 return; 6615 } 6616 6617 Type = S.Context.getAddrSpaceQualType(Type, ASIdx); 6618 } 6619 } 6620 6621 /// handleObjCOwnershipTypeAttr - Process an objc_ownership 6622 /// attribute on the specified type. 6623 /// 6624 /// Returns 'true' if the attribute was handled. 6625 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state, 6626 ParsedAttr &attr, QualType &type) { 6627 bool NonObjCPointer = false; 6628 6629 if (!type->isDependentType() && !type->isUndeducedType()) { 6630 if (const PointerType *ptr = type->getAs<PointerType>()) { 6631 QualType pointee = ptr->getPointeeType(); 6632 if (pointee->isObjCRetainableType() || pointee->isPointerType()) 6633 return false; 6634 // It is important not to lose the source info that there was an attribute 6635 // applied to non-objc pointer. We will create an attributed type but 6636 // its type will be the same as the original type. 6637 NonObjCPointer = true; 6638 } else if (!type->isObjCRetainableType()) { 6639 return false; 6640 } 6641 6642 // Don't accept an ownership attribute in the declspec if it would 6643 // just be the return type of a block pointer. 6644 if (state.isProcessingDeclSpec()) { 6645 Declarator &D = state.getDeclarator(); 6646 if (maybeMovePastReturnType(D, D.getNumTypeObjects(), 6647 /*onlyBlockPointers=*/true)) 6648 return false; 6649 } 6650 } 6651 6652 Sema &S = state.getSema(); 6653 SourceLocation AttrLoc = attr.getLoc(); 6654 if (AttrLoc.isMacroID()) 6655 AttrLoc = 6656 S.getSourceManager().getImmediateExpansionRange(AttrLoc).getBegin(); 6657 6658 if (!attr.isArgIdent(0)) { 6659 S.Diag(AttrLoc, diag::err_attribute_argument_type) << attr 6660 << AANT_ArgumentString; 6661 attr.setInvalid(); 6662 return true; 6663 } 6664 6665 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident; 6666 Qualifiers::ObjCLifetime lifetime; 6667 if (II->isStr("none")) 6668 lifetime = Qualifiers::OCL_ExplicitNone; 6669 else if (II->isStr("strong")) 6670 lifetime = Qualifiers::OCL_Strong; 6671 else if (II->isStr("weak")) 6672 lifetime = Qualifiers::OCL_Weak; 6673 else if (II->isStr("autoreleasing")) 6674 lifetime = Qualifiers::OCL_Autoreleasing; 6675 else { 6676 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported) << attr << II; 6677 attr.setInvalid(); 6678 return true; 6679 } 6680 6681 // Just ignore lifetime attributes other than __weak and __unsafe_unretained 6682 // outside of ARC mode. 6683 if (!S.getLangOpts().ObjCAutoRefCount && 6684 lifetime != Qualifiers::OCL_Weak && 6685 lifetime != Qualifiers::OCL_ExplicitNone) { 6686 return true; 6687 } 6688 6689 SplitQualType underlyingType = type.split(); 6690 6691 // Check for redundant/conflicting ownership qualifiers. 6692 if (Qualifiers::ObjCLifetime previousLifetime 6693 = type.getQualifiers().getObjCLifetime()) { 6694 // If it's written directly, that's an error. 6695 if (S.Context.hasDirectOwnershipQualifier(type)) { 6696 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant) 6697 << type; 6698 return true; 6699 } 6700 6701 // Otherwise, if the qualifiers actually conflict, pull sugar off 6702 // and remove the ObjCLifetime qualifiers. 6703 if (previousLifetime != lifetime) { 6704 // It's possible to have multiple local ObjCLifetime qualifiers. We 6705 // can't stop after we reach a type that is directly qualified. 6706 const Type *prevTy = nullptr; 6707 while (!prevTy || prevTy != underlyingType.Ty) { 6708 prevTy = underlyingType.Ty; 6709 underlyingType = underlyingType.getSingleStepDesugaredType(); 6710 } 6711 underlyingType.Quals.removeObjCLifetime(); 6712 } 6713 } 6714 6715 underlyingType.Quals.addObjCLifetime(lifetime); 6716 6717 if (NonObjCPointer) { 6718 StringRef name = attr.getAttrName()->getName(); 6719 switch (lifetime) { 6720 case Qualifiers::OCL_None: 6721 case Qualifiers::OCL_ExplicitNone: 6722 break; 6723 case Qualifiers::OCL_Strong: name = "__strong"; break; 6724 case Qualifiers::OCL_Weak: name = "__weak"; break; 6725 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break; 6726 } 6727 S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name 6728 << TDS_ObjCObjOrBlock << type; 6729 } 6730 6731 // Don't actually add the __unsafe_unretained qualifier in non-ARC files, 6732 // because having both 'T' and '__unsafe_unretained T' exist in the type 6733 // system causes unfortunate widespread consistency problems. (For example, 6734 // they're not considered compatible types, and we mangle them identicially 6735 // as template arguments.) These problems are all individually fixable, 6736 // but it's easier to just not add the qualifier and instead sniff it out 6737 // in specific places using isObjCInertUnsafeUnretainedType(). 6738 // 6739 // Doing this does means we miss some trivial consistency checks that 6740 // would've triggered in ARC, but that's better than trying to solve all 6741 // the coexistence problems with __unsafe_unretained. 6742 if (!S.getLangOpts().ObjCAutoRefCount && 6743 lifetime == Qualifiers::OCL_ExplicitNone) { 6744 type = state.getAttributedType( 6745 createSimpleAttr<ObjCInertUnsafeUnretainedAttr>(S.Context, attr), 6746 type, type); 6747 return true; 6748 } 6749 6750 QualType origType = type; 6751 if (!NonObjCPointer) 6752 type = S.Context.getQualifiedType(underlyingType); 6753 6754 // If we have a valid source location for the attribute, use an 6755 // AttributedType instead. 6756 if (AttrLoc.isValid()) { 6757 type = state.getAttributedType(::new (S.Context) 6758 ObjCOwnershipAttr(S.Context, attr, II), 6759 origType, type); 6760 } 6761 6762 auto diagnoseOrDelay = [](Sema &S, SourceLocation loc, 6763 unsigned diagnostic, QualType type) { 6764 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) { 6765 S.DelayedDiagnostics.add( 6766 sema::DelayedDiagnostic::makeForbiddenType( 6767 S.getSourceManager().getExpansionLoc(loc), 6768 diagnostic, type, /*ignored*/ 0)); 6769 } else { 6770 S.Diag(loc, diagnostic); 6771 } 6772 }; 6773 6774 // Sometimes, __weak isn't allowed. 6775 if (lifetime == Qualifiers::OCL_Weak && 6776 !S.getLangOpts().ObjCWeak && !NonObjCPointer) { 6777 6778 // Use a specialized diagnostic if the runtime just doesn't support them. 6779 unsigned diagnostic = 6780 (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled 6781 : diag::err_arc_weak_no_runtime); 6782 6783 // In any case, delay the diagnostic until we know what we're parsing. 6784 diagnoseOrDelay(S, AttrLoc, diagnostic, type); 6785 6786 attr.setInvalid(); 6787 return true; 6788 } 6789 6790 // Forbid __weak for class objects marked as 6791 // objc_arc_weak_reference_unavailable 6792 if (lifetime == Qualifiers::OCL_Weak) { 6793 if (const ObjCObjectPointerType *ObjT = 6794 type->getAs<ObjCObjectPointerType>()) { 6795 if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) { 6796 if (Class->isArcWeakrefUnavailable()) { 6797 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class); 6798 S.Diag(ObjT->getInterfaceDecl()->getLocation(), 6799 diag::note_class_declared); 6800 } 6801 } 6802 } 6803 } 6804 6805 return true; 6806 } 6807 6808 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type 6809 /// attribute on the specified type. Returns true to indicate that 6810 /// the attribute was handled, false to indicate that the type does 6811 /// not permit the attribute. 6812 static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr, 6813 QualType &type) { 6814 Sema &S = state.getSema(); 6815 6816 // Delay if this isn't some kind of pointer. 6817 if (!type->isPointerType() && 6818 !type->isObjCObjectPointerType() && 6819 !type->isBlockPointerType()) 6820 return false; 6821 6822 if (type.getObjCGCAttr() != Qualifiers::GCNone) { 6823 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc); 6824 attr.setInvalid(); 6825 return true; 6826 } 6827 6828 // Check the attribute arguments. 6829 if (!attr.isArgIdent(0)) { 6830 S.Diag(attr.getLoc(), diag::err_attribute_argument_type) 6831 << attr << AANT_ArgumentString; 6832 attr.setInvalid(); 6833 return true; 6834 } 6835 Qualifiers::GC GCAttr; 6836 if (attr.getNumArgs() > 1) { 6837 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << attr 6838 << 1; 6839 attr.setInvalid(); 6840 return true; 6841 } 6842 6843 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident; 6844 if (II->isStr("weak")) 6845 GCAttr = Qualifiers::Weak; 6846 else if (II->isStr("strong")) 6847 GCAttr = Qualifiers::Strong; 6848 else { 6849 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported) 6850 << attr << II; 6851 attr.setInvalid(); 6852 return true; 6853 } 6854 6855 QualType origType = type; 6856 type = S.Context.getObjCGCQualType(origType, GCAttr); 6857 6858 // Make an attributed type to preserve the source information. 6859 if (attr.getLoc().isValid()) 6860 type = state.getAttributedType( 6861 ::new (S.Context) ObjCGCAttr(S.Context, attr, II), origType, type); 6862 6863 return true; 6864 } 6865 6866 namespace { 6867 /// A helper class to unwrap a type down to a function for the 6868 /// purposes of applying attributes there. 6869 /// 6870 /// Use: 6871 /// FunctionTypeUnwrapper unwrapped(SemaRef, T); 6872 /// if (unwrapped.isFunctionType()) { 6873 /// const FunctionType *fn = unwrapped.get(); 6874 /// // change fn somehow 6875 /// T = unwrapped.wrap(fn); 6876 /// } 6877 struct FunctionTypeUnwrapper { 6878 enum WrapKind { 6879 Desugar, 6880 Attributed, 6881 Parens, 6882 Array, 6883 Pointer, 6884 BlockPointer, 6885 Reference, 6886 MemberPointer, 6887 MacroQualified, 6888 }; 6889 6890 QualType Original; 6891 const FunctionType *Fn; 6892 SmallVector<unsigned char /*WrapKind*/, 8> Stack; 6893 6894 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) { 6895 while (true) { 6896 const Type *Ty = T.getTypePtr(); 6897 if (isa<FunctionType>(Ty)) { 6898 Fn = cast<FunctionType>(Ty); 6899 return; 6900 } else if (isa<ParenType>(Ty)) { 6901 T = cast<ParenType>(Ty)->getInnerType(); 6902 Stack.push_back(Parens); 6903 } else if (isa<ConstantArrayType>(Ty) || isa<VariableArrayType>(Ty) || 6904 isa<IncompleteArrayType>(Ty)) { 6905 T = cast<ArrayType>(Ty)->getElementType(); 6906 Stack.push_back(Array); 6907 } else if (isa<PointerType>(Ty)) { 6908 T = cast<PointerType>(Ty)->getPointeeType(); 6909 Stack.push_back(Pointer); 6910 } else if (isa<BlockPointerType>(Ty)) { 6911 T = cast<BlockPointerType>(Ty)->getPointeeType(); 6912 Stack.push_back(BlockPointer); 6913 } else if (isa<MemberPointerType>(Ty)) { 6914 T = cast<MemberPointerType>(Ty)->getPointeeType(); 6915 Stack.push_back(MemberPointer); 6916 } else if (isa<ReferenceType>(Ty)) { 6917 T = cast<ReferenceType>(Ty)->getPointeeType(); 6918 Stack.push_back(Reference); 6919 } else if (isa<AttributedType>(Ty)) { 6920 T = cast<AttributedType>(Ty)->getEquivalentType(); 6921 Stack.push_back(Attributed); 6922 } else if (isa<MacroQualifiedType>(Ty)) { 6923 T = cast<MacroQualifiedType>(Ty)->getUnderlyingType(); 6924 Stack.push_back(MacroQualified); 6925 } else { 6926 const Type *DTy = Ty->getUnqualifiedDesugaredType(); 6927 if (Ty == DTy) { 6928 Fn = nullptr; 6929 return; 6930 } 6931 6932 T = QualType(DTy, 0); 6933 Stack.push_back(Desugar); 6934 } 6935 } 6936 } 6937 6938 bool isFunctionType() const { return (Fn != nullptr); } 6939 const FunctionType *get() const { return Fn; } 6940 6941 QualType wrap(Sema &S, const FunctionType *New) { 6942 // If T wasn't modified from the unwrapped type, do nothing. 6943 if (New == get()) return Original; 6944 6945 Fn = New; 6946 return wrap(S.Context, Original, 0); 6947 } 6948 6949 private: 6950 QualType wrap(ASTContext &C, QualType Old, unsigned I) { 6951 if (I == Stack.size()) 6952 return C.getQualifiedType(Fn, Old.getQualifiers()); 6953 6954 // Build up the inner type, applying the qualifiers from the old 6955 // type to the new type. 6956 SplitQualType SplitOld = Old.split(); 6957 6958 // As a special case, tail-recurse if there are no qualifiers. 6959 if (SplitOld.Quals.empty()) 6960 return wrap(C, SplitOld.Ty, I); 6961 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals); 6962 } 6963 6964 QualType wrap(ASTContext &C, const Type *Old, unsigned I) { 6965 if (I == Stack.size()) return QualType(Fn, 0); 6966 6967 switch (static_cast<WrapKind>(Stack[I++])) { 6968 case Desugar: 6969 // This is the point at which we potentially lose source 6970 // information. 6971 return wrap(C, Old->getUnqualifiedDesugaredType(), I); 6972 6973 case Attributed: 6974 return wrap(C, cast<AttributedType>(Old)->getEquivalentType(), I); 6975 6976 case Parens: { 6977 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I); 6978 return C.getParenType(New); 6979 } 6980 6981 case MacroQualified: 6982 return wrap(C, cast<MacroQualifiedType>(Old)->getUnderlyingType(), I); 6983 6984 case Array: { 6985 if (const auto *CAT = dyn_cast<ConstantArrayType>(Old)) { 6986 QualType New = wrap(C, CAT->getElementType(), I); 6987 return C.getConstantArrayType(New, CAT->getSize(), CAT->getSizeExpr(), 6988 CAT->getSizeModifier(), 6989 CAT->getIndexTypeCVRQualifiers()); 6990 } 6991 6992 if (const auto *VAT = dyn_cast<VariableArrayType>(Old)) { 6993 QualType New = wrap(C, VAT->getElementType(), I); 6994 return C.getVariableArrayType( 6995 New, VAT->getSizeExpr(), VAT->getSizeModifier(), 6996 VAT->getIndexTypeCVRQualifiers(), VAT->getBracketsRange()); 6997 } 6998 6999 const auto *IAT = cast<IncompleteArrayType>(Old); 7000 QualType New = wrap(C, IAT->getElementType(), I); 7001 return C.getIncompleteArrayType(New, IAT->getSizeModifier(), 7002 IAT->getIndexTypeCVRQualifiers()); 7003 } 7004 7005 case Pointer: { 7006 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I); 7007 return C.getPointerType(New); 7008 } 7009 7010 case BlockPointer: { 7011 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I); 7012 return C.getBlockPointerType(New); 7013 } 7014 7015 case MemberPointer: { 7016 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old); 7017 QualType New = wrap(C, OldMPT->getPointeeType(), I); 7018 return C.getMemberPointerType(New, OldMPT->getClass()); 7019 } 7020 7021 case Reference: { 7022 const ReferenceType *OldRef = cast<ReferenceType>(Old); 7023 QualType New = wrap(C, OldRef->getPointeeType(), I); 7024 if (isa<LValueReferenceType>(OldRef)) 7025 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue()); 7026 else 7027 return C.getRValueReferenceType(New); 7028 } 7029 } 7030 7031 llvm_unreachable("unknown wrapping kind"); 7032 } 7033 }; 7034 } // end anonymous namespace 7035 7036 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State, 7037 ParsedAttr &PAttr, QualType &Type) { 7038 Sema &S = State.getSema(); 7039 7040 Attr *A; 7041 switch (PAttr.getKind()) { 7042 default: llvm_unreachable("Unknown attribute kind"); 7043 case ParsedAttr::AT_Ptr32: 7044 A = createSimpleAttr<Ptr32Attr>(S.Context, PAttr); 7045 break; 7046 case ParsedAttr::AT_Ptr64: 7047 A = createSimpleAttr<Ptr64Attr>(S.Context, PAttr); 7048 break; 7049 case ParsedAttr::AT_SPtr: 7050 A = createSimpleAttr<SPtrAttr>(S.Context, PAttr); 7051 break; 7052 case ParsedAttr::AT_UPtr: 7053 A = createSimpleAttr<UPtrAttr>(S.Context, PAttr); 7054 break; 7055 } 7056 7057 std::bitset<attr::LastAttr> Attrs; 7058 QualType Desugared = Type; 7059 for (;;) { 7060 if (const TypedefType *TT = dyn_cast<TypedefType>(Desugared)) { 7061 Desugared = TT->desugar(); 7062 continue; 7063 } else if (const ElaboratedType *ET = dyn_cast<ElaboratedType>(Desugared)) { 7064 Desugared = ET->desugar(); 7065 continue; 7066 } 7067 const AttributedType *AT = dyn_cast<AttributedType>(Desugared); 7068 if (!AT) 7069 break; 7070 Attrs[AT->getAttrKind()] = true; 7071 Desugared = AT->getModifiedType(); 7072 } 7073 7074 // You cannot specify duplicate type attributes, so if the attribute has 7075 // already been applied, flag it. 7076 attr::Kind NewAttrKind = A->getKind(); 7077 if (Attrs[NewAttrKind]) { 7078 S.Diag(PAttr.getLoc(), diag::warn_duplicate_attribute_exact) << PAttr; 7079 return true; 7080 } 7081 Attrs[NewAttrKind] = true; 7082 7083 // You cannot have both __sptr and __uptr on the same type, nor can you 7084 // have __ptr32 and __ptr64. 7085 if (Attrs[attr::Ptr32] && Attrs[attr::Ptr64]) { 7086 S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible) 7087 << "'__ptr32'" 7088 << "'__ptr64'" << /*isRegularKeyword=*/0; 7089 return true; 7090 } else if (Attrs[attr::SPtr] && Attrs[attr::UPtr]) { 7091 S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible) 7092 << "'__sptr'" 7093 << "'__uptr'" << /*isRegularKeyword=*/0; 7094 return true; 7095 } 7096 7097 // Check the raw (i.e., desugared) Canonical type to see if it 7098 // is a pointer type. 7099 if (!isa<PointerType>(Desugared)) { 7100 // Pointer type qualifiers can only operate on pointer types, but not 7101 // pointer-to-member types. 7102 if (Type->isMemberPointerType()) 7103 S.Diag(PAttr.getLoc(), diag::err_attribute_no_member_pointers) << PAttr; 7104 else 7105 S.Diag(PAttr.getLoc(), diag::err_attribute_pointers_only) << PAttr << 0; 7106 return true; 7107 } 7108 7109 // Add address space to type based on its attributes. 7110 LangAS ASIdx = LangAS::Default; 7111 uint64_t PtrWidth = 7112 S.Context.getTargetInfo().getPointerWidth(LangAS::Default); 7113 if (PtrWidth == 32) { 7114 if (Attrs[attr::Ptr64]) 7115 ASIdx = LangAS::ptr64; 7116 else if (Attrs[attr::UPtr]) 7117 ASIdx = LangAS::ptr32_uptr; 7118 } else if (PtrWidth == 64 && Attrs[attr::Ptr32]) { 7119 if (S.Context.getTargetInfo().getTriple().isOSzOS() || Attrs[attr::UPtr]) 7120 ASIdx = LangAS::ptr32_uptr; 7121 else 7122 ASIdx = LangAS::ptr32_sptr; 7123 } 7124 7125 QualType Pointee = Type->getPointeeType(); 7126 if (ASIdx != LangAS::Default) 7127 Pointee = S.Context.getAddrSpaceQualType( 7128 S.Context.removeAddrSpaceQualType(Pointee), ASIdx); 7129 Type = State.getAttributedType(A, Type, S.Context.getPointerType(Pointee)); 7130 return false; 7131 } 7132 7133 static bool HandleWebAssemblyFuncrefAttr(TypeProcessingState &State, 7134 QualType &QT, ParsedAttr &PAttr) { 7135 assert(PAttr.getKind() == ParsedAttr::AT_WebAssemblyFuncref); 7136 7137 Sema &S = State.getSema(); 7138 Attr *A = createSimpleAttr<WebAssemblyFuncrefAttr>(S.Context, PAttr); 7139 7140 std::bitset<attr::LastAttr> Attrs; 7141 attr::Kind NewAttrKind = A->getKind(); 7142 const auto *AT = dyn_cast<AttributedType>(QT); 7143 while (AT) { 7144 Attrs[AT->getAttrKind()] = true; 7145 AT = dyn_cast<AttributedType>(AT->getModifiedType()); 7146 } 7147 7148 // You cannot specify duplicate type attributes, so if the attribute has 7149 // already been applied, flag it. 7150 if (Attrs[NewAttrKind]) { 7151 S.Diag(PAttr.getLoc(), diag::warn_duplicate_attribute_exact) << PAttr; 7152 return true; 7153 } 7154 7155 // Add address space to type based on its attributes. 7156 LangAS ASIdx = LangAS::wasm_funcref; 7157 QualType Pointee = QT->getPointeeType(); 7158 Pointee = S.Context.getAddrSpaceQualType( 7159 S.Context.removeAddrSpaceQualType(Pointee), ASIdx); 7160 QT = State.getAttributedType(A, QT, S.Context.getPointerType(Pointee)); 7161 return false; 7162 } 7163 7164 static void HandleSwiftAttr(TypeProcessingState &State, TypeAttrLocation TAL, 7165 QualType &QT, ParsedAttr &PAttr) { 7166 if (TAL == TAL_DeclName) 7167 return; 7168 7169 Sema &S = State.getSema(); 7170 auto &D = State.getDeclarator(); 7171 7172 // If the attribute appears in declaration specifiers 7173 // it should be handled as a declaration attribute, 7174 // unless it's associated with a type or a function 7175 // prototype (i.e. appears on a parameter or result type). 7176 if (State.isProcessingDeclSpec()) { 7177 if (!(D.isPrototypeContext() || 7178 D.getContext() == DeclaratorContext::TypeName)) 7179 return; 7180 7181 if (auto *chunk = D.getInnermostNonParenChunk()) { 7182 moveAttrFromListToList(PAttr, State.getCurrentAttributes(), 7183 const_cast<DeclaratorChunk *>(chunk)->getAttrs()); 7184 return; 7185 } 7186 } 7187 7188 StringRef Str; 7189 if (!S.checkStringLiteralArgumentAttr(PAttr, 0, Str)) { 7190 PAttr.setInvalid(); 7191 return; 7192 } 7193 7194 // If the attribute as attached to a paren move it closer to 7195 // the declarator. This can happen in block declarations when 7196 // an attribute is placed before `^` i.e. `(__attribute__((...)) ^)`. 7197 // 7198 // Note that it's actually invalid to use GNU style attributes 7199 // in a block but such cases are currently handled gracefully 7200 // but the parser and behavior should be consistent between 7201 // cases when attribute appears before/after block's result 7202 // type and inside (^). 7203 if (TAL == TAL_DeclChunk) { 7204 auto chunkIdx = State.getCurrentChunkIndex(); 7205 if (chunkIdx >= 1 && 7206 D.getTypeObject(chunkIdx).Kind == DeclaratorChunk::Paren) { 7207 moveAttrFromListToList(PAttr, State.getCurrentAttributes(), 7208 D.getTypeObject(chunkIdx - 1).getAttrs()); 7209 return; 7210 } 7211 } 7212 7213 auto *A = ::new (S.Context) SwiftAttrAttr(S.Context, PAttr, Str); 7214 QT = State.getAttributedType(A, QT, QT); 7215 PAttr.setUsedAsTypeAttr(); 7216 } 7217 7218 /// Rebuild an attributed type without the nullability attribute on it. 7219 static QualType rebuildAttributedTypeWithoutNullability(ASTContext &Ctx, 7220 QualType Type) { 7221 auto Attributed = dyn_cast<AttributedType>(Type.getTypePtr()); 7222 if (!Attributed) 7223 return Type; 7224 7225 // Skip the nullability attribute; we're done. 7226 if (Attributed->getImmediateNullability()) 7227 return Attributed->getModifiedType(); 7228 7229 // Build the modified type. 7230 QualType Modified = rebuildAttributedTypeWithoutNullability( 7231 Ctx, Attributed->getModifiedType()); 7232 assert(Modified.getTypePtr() != Attributed->getModifiedType().getTypePtr()); 7233 return Ctx.getAttributedType(Attributed->getAttrKind(), Modified, 7234 Attributed->getEquivalentType(), 7235 Attributed->getAttr()); 7236 } 7237 7238 /// Map a nullability attribute kind to a nullability kind. 7239 static NullabilityKind mapNullabilityAttrKind(ParsedAttr::Kind kind) { 7240 switch (kind) { 7241 case ParsedAttr::AT_TypeNonNull: 7242 return NullabilityKind::NonNull; 7243 7244 case ParsedAttr::AT_TypeNullable: 7245 return NullabilityKind::Nullable; 7246 7247 case ParsedAttr::AT_TypeNullableResult: 7248 return NullabilityKind::NullableResult; 7249 7250 case ParsedAttr::AT_TypeNullUnspecified: 7251 return NullabilityKind::Unspecified; 7252 7253 default: 7254 llvm_unreachable("not a nullability attribute kind"); 7255 } 7256 } 7257 7258 static bool CheckNullabilityTypeSpecifier( 7259 Sema &S, TypeProcessingState *State, ParsedAttr *PAttr, QualType &QT, 7260 NullabilityKind Nullability, SourceLocation NullabilityLoc, 7261 bool IsContextSensitive, bool AllowOnArrayType, bool OverrideExisting) { 7262 bool Implicit = (State == nullptr); 7263 if (!Implicit) 7264 recordNullabilitySeen(S, NullabilityLoc); 7265 7266 // Check for existing nullability attributes on the type. 7267 QualType Desugared = QT; 7268 while (auto *Attributed = dyn_cast<AttributedType>(Desugared.getTypePtr())) { 7269 // Check whether there is already a null 7270 if (auto ExistingNullability = Attributed->getImmediateNullability()) { 7271 // Duplicated nullability. 7272 if (Nullability == *ExistingNullability) { 7273 if (Implicit) 7274 break; 7275 7276 S.Diag(NullabilityLoc, diag::warn_nullability_duplicate) 7277 << DiagNullabilityKind(Nullability, IsContextSensitive) 7278 << FixItHint::CreateRemoval(NullabilityLoc); 7279 7280 break; 7281 } 7282 7283 if (!OverrideExisting) { 7284 // Conflicting nullability. 7285 S.Diag(NullabilityLoc, diag::err_nullability_conflicting) 7286 << DiagNullabilityKind(Nullability, IsContextSensitive) 7287 << DiagNullabilityKind(*ExistingNullability, false); 7288 return true; 7289 } 7290 7291 // Rebuild the attributed type, dropping the existing nullability. 7292 QT = rebuildAttributedTypeWithoutNullability(S.Context, QT); 7293 } 7294 7295 Desugared = Attributed->getModifiedType(); 7296 } 7297 7298 // If there is already a different nullability specifier, complain. 7299 // This (unlike the code above) looks through typedefs that might 7300 // have nullability specifiers on them, which means we cannot 7301 // provide a useful Fix-It. 7302 if (auto ExistingNullability = Desugared->getNullability()) { 7303 if (Nullability != *ExistingNullability && !Implicit) { 7304 S.Diag(NullabilityLoc, diag::err_nullability_conflicting) 7305 << DiagNullabilityKind(Nullability, IsContextSensitive) 7306 << DiagNullabilityKind(*ExistingNullability, false); 7307 7308 // Try to find the typedef with the existing nullability specifier. 7309 if (auto TT = Desugared->getAs<TypedefType>()) { 7310 TypedefNameDecl *typedefDecl = TT->getDecl(); 7311 QualType underlyingType = typedefDecl->getUnderlyingType(); 7312 if (auto typedefNullability = 7313 AttributedType::stripOuterNullability(underlyingType)) { 7314 if (*typedefNullability == *ExistingNullability) { 7315 S.Diag(typedefDecl->getLocation(), diag::note_nullability_here) 7316 << DiagNullabilityKind(*ExistingNullability, false); 7317 } 7318 } 7319 } 7320 7321 return true; 7322 } 7323 } 7324 7325 // If this definitely isn't a pointer type, reject the specifier. 7326 if (!Desugared->canHaveNullability() && 7327 !(AllowOnArrayType && Desugared->isArrayType())) { 7328 if (!Implicit) 7329 S.Diag(NullabilityLoc, diag::err_nullability_nonpointer) 7330 << DiagNullabilityKind(Nullability, IsContextSensitive) << QT; 7331 7332 return true; 7333 } 7334 7335 // For the context-sensitive keywords/Objective-C property 7336 // attributes, require that the type be a single-level pointer. 7337 if (IsContextSensitive) { 7338 // Make sure that the pointee isn't itself a pointer type. 7339 const Type *pointeeType = nullptr; 7340 if (Desugared->isArrayType()) 7341 pointeeType = Desugared->getArrayElementTypeNoTypeQual(); 7342 else if (Desugared->isAnyPointerType()) 7343 pointeeType = Desugared->getPointeeType().getTypePtr(); 7344 7345 if (pointeeType && (pointeeType->isAnyPointerType() || 7346 pointeeType->isObjCObjectPointerType() || 7347 pointeeType->isMemberPointerType())) { 7348 S.Diag(NullabilityLoc, diag::err_nullability_cs_multilevel) 7349 << DiagNullabilityKind(Nullability, true) << QT; 7350 S.Diag(NullabilityLoc, diag::note_nullability_type_specifier) 7351 << DiagNullabilityKind(Nullability, false) << QT 7352 << FixItHint::CreateReplacement(NullabilityLoc, 7353 getNullabilitySpelling(Nullability)); 7354 return true; 7355 } 7356 } 7357 7358 // Form the attributed type. 7359 if (State) { 7360 assert(PAttr); 7361 Attr *A = createNullabilityAttr(S.Context, *PAttr, Nullability); 7362 QT = State->getAttributedType(A, QT, QT); 7363 } else { 7364 QT = S.Context.getAttributedType(Nullability, QT, QT); 7365 } 7366 return false; 7367 } 7368 7369 static bool CheckNullabilityTypeSpecifier(TypeProcessingState &State, 7370 QualType &Type, ParsedAttr &Attr, 7371 bool AllowOnArrayType) { 7372 NullabilityKind Nullability = mapNullabilityAttrKind(Attr.getKind()); 7373 SourceLocation NullabilityLoc = Attr.getLoc(); 7374 bool IsContextSensitive = Attr.isContextSensitiveKeywordAttribute(); 7375 7376 return CheckNullabilityTypeSpecifier(State.getSema(), &State, &Attr, Type, 7377 Nullability, NullabilityLoc, 7378 IsContextSensitive, AllowOnArrayType, 7379 /*overrideExisting*/ false); 7380 } 7381 7382 bool Sema::CheckImplicitNullabilityTypeSpecifier(QualType &Type, 7383 NullabilityKind Nullability, 7384 SourceLocation DiagLoc, 7385 bool AllowArrayTypes, 7386 bool OverrideExisting) { 7387 return CheckNullabilityTypeSpecifier( 7388 *this, nullptr, nullptr, Type, Nullability, DiagLoc, 7389 /*isContextSensitive*/ false, AllowArrayTypes, OverrideExisting); 7390 } 7391 7392 /// Check the application of the Objective-C '__kindof' qualifier to 7393 /// the given type. 7394 static bool checkObjCKindOfType(TypeProcessingState &state, QualType &type, 7395 ParsedAttr &attr) { 7396 Sema &S = state.getSema(); 7397 7398 if (isa<ObjCTypeParamType>(type)) { 7399 // Build the attributed type to record where __kindof occurred. 7400 type = state.getAttributedType( 7401 createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, type); 7402 return false; 7403 } 7404 7405 // Find out if it's an Objective-C object or object pointer type; 7406 const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>(); 7407 const ObjCObjectType *objType = ptrType ? ptrType->getObjectType() 7408 : type->getAs<ObjCObjectType>(); 7409 7410 // If not, we can't apply __kindof. 7411 if (!objType) { 7412 // FIXME: Handle dependent types that aren't yet object types. 7413 S.Diag(attr.getLoc(), diag::err_objc_kindof_nonobject) 7414 << type; 7415 return true; 7416 } 7417 7418 // Rebuild the "equivalent" type, which pushes __kindof down into 7419 // the object type. 7420 // There is no need to apply kindof on an unqualified id type. 7421 QualType equivType = S.Context.getObjCObjectType( 7422 objType->getBaseType(), objType->getTypeArgsAsWritten(), 7423 objType->getProtocols(), 7424 /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true); 7425 7426 // If we started with an object pointer type, rebuild it. 7427 if (ptrType) { 7428 equivType = S.Context.getObjCObjectPointerType(equivType); 7429 if (auto nullability = type->getNullability()) { 7430 // We create a nullability attribute from the __kindof attribute. 7431 // Make sure that will make sense. 7432 assert(attr.getAttributeSpellingListIndex() == 0 && 7433 "multiple spellings for __kindof?"); 7434 Attr *A = createNullabilityAttr(S.Context, attr, *nullability); 7435 A->setImplicit(true); 7436 equivType = state.getAttributedType(A, equivType, equivType); 7437 } 7438 } 7439 7440 // Build the attributed type to record where __kindof occurred. 7441 type = state.getAttributedType( 7442 createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, equivType); 7443 return false; 7444 } 7445 7446 /// Distribute a nullability type attribute that cannot be applied to 7447 /// the type specifier to a pointer, block pointer, or member pointer 7448 /// declarator, complaining if necessary. 7449 /// 7450 /// \returns true if the nullability annotation was distributed, false 7451 /// otherwise. 7452 static bool distributeNullabilityTypeAttr(TypeProcessingState &state, 7453 QualType type, ParsedAttr &attr) { 7454 Declarator &declarator = state.getDeclarator(); 7455 7456 /// Attempt to move the attribute to the specified chunk. 7457 auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool { 7458 // If there is already a nullability attribute there, don't add 7459 // one. 7460 if (hasNullabilityAttr(chunk.getAttrs())) 7461 return false; 7462 7463 // Complain about the nullability qualifier being in the wrong 7464 // place. 7465 enum { 7466 PK_Pointer, 7467 PK_BlockPointer, 7468 PK_MemberPointer, 7469 PK_FunctionPointer, 7470 PK_MemberFunctionPointer, 7471 } pointerKind 7472 = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer 7473 : PK_Pointer) 7474 : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer 7475 : inFunction? PK_MemberFunctionPointer : PK_MemberPointer; 7476 7477 auto diag = state.getSema().Diag(attr.getLoc(), 7478 diag::warn_nullability_declspec) 7479 << DiagNullabilityKind(mapNullabilityAttrKind(attr.getKind()), 7480 attr.isContextSensitiveKeywordAttribute()) 7481 << type 7482 << static_cast<unsigned>(pointerKind); 7483 7484 // FIXME: MemberPointer chunks don't carry the location of the *. 7485 if (chunk.Kind != DeclaratorChunk::MemberPointer) { 7486 diag << FixItHint::CreateRemoval(attr.getLoc()) 7487 << FixItHint::CreateInsertion( 7488 state.getSema().getPreprocessor().getLocForEndOfToken( 7489 chunk.Loc), 7490 " " + attr.getAttrName()->getName().str() + " "); 7491 } 7492 7493 moveAttrFromListToList(attr, state.getCurrentAttributes(), 7494 chunk.getAttrs()); 7495 return true; 7496 }; 7497 7498 // Move it to the outermost pointer, member pointer, or block 7499 // pointer declarator. 7500 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { 7501 DeclaratorChunk &chunk = declarator.getTypeObject(i-1); 7502 switch (chunk.Kind) { 7503 case DeclaratorChunk::Pointer: 7504 case DeclaratorChunk::BlockPointer: 7505 case DeclaratorChunk::MemberPointer: 7506 return moveToChunk(chunk, false); 7507 7508 case DeclaratorChunk::Paren: 7509 case DeclaratorChunk::Array: 7510 continue; 7511 7512 case DeclaratorChunk::Function: 7513 // Try to move past the return type to a function/block/member 7514 // function pointer. 7515 if (DeclaratorChunk *dest = maybeMovePastReturnType( 7516 declarator, i, 7517 /*onlyBlockPointers=*/false)) { 7518 return moveToChunk(*dest, true); 7519 } 7520 7521 return false; 7522 7523 // Don't walk through these. 7524 case DeclaratorChunk::Reference: 7525 case DeclaratorChunk::Pipe: 7526 return false; 7527 } 7528 } 7529 7530 return false; 7531 } 7532 7533 static Attr *getCCTypeAttr(ASTContext &Ctx, ParsedAttr &Attr) { 7534 assert(!Attr.isInvalid()); 7535 switch (Attr.getKind()) { 7536 default: 7537 llvm_unreachable("not a calling convention attribute"); 7538 case ParsedAttr::AT_CDecl: 7539 return createSimpleAttr<CDeclAttr>(Ctx, Attr); 7540 case ParsedAttr::AT_FastCall: 7541 return createSimpleAttr<FastCallAttr>(Ctx, Attr); 7542 case ParsedAttr::AT_StdCall: 7543 return createSimpleAttr<StdCallAttr>(Ctx, Attr); 7544 case ParsedAttr::AT_ThisCall: 7545 return createSimpleAttr<ThisCallAttr>(Ctx, Attr); 7546 case ParsedAttr::AT_RegCall: 7547 return createSimpleAttr<RegCallAttr>(Ctx, Attr); 7548 case ParsedAttr::AT_Pascal: 7549 return createSimpleAttr<PascalAttr>(Ctx, Attr); 7550 case ParsedAttr::AT_SwiftCall: 7551 return createSimpleAttr<SwiftCallAttr>(Ctx, Attr); 7552 case ParsedAttr::AT_SwiftAsyncCall: 7553 return createSimpleAttr<SwiftAsyncCallAttr>(Ctx, Attr); 7554 case ParsedAttr::AT_VectorCall: 7555 return createSimpleAttr<VectorCallAttr>(Ctx, Attr); 7556 case ParsedAttr::AT_AArch64VectorPcs: 7557 return createSimpleAttr<AArch64VectorPcsAttr>(Ctx, Attr); 7558 case ParsedAttr::AT_AArch64SVEPcs: 7559 return createSimpleAttr<AArch64SVEPcsAttr>(Ctx, Attr); 7560 case ParsedAttr::AT_ArmStreaming: 7561 return createSimpleAttr<ArmStreamingAttr>(Ctx, Attr); 7562 case ParsedAttr::AT_AMDGPUKernelCall: 7563 return createSimpleAttr<AMDGPUKernelCallAttr>(Ctx, Attr); 7564 case ParsedAttr::AT_Pcs: { 7565 // The attribute may have had a fixit applied where we treated an 7566 // identifier as a string literal. The contents of the string are valid, 7567 // but the form may not be. 7568 StringRef Str; 7569 if (Attr.isArgExpr(0)) 7570 Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString(); 7571 else 7572 Str = Attr.getArgAsIdent(0)->Ident->getName(); 7573 PcsAttr::PCSType Type; 7574 if (!PcsAttr::ConvertStrToPCSType(Str, Type)) 7575 llvm_unreachable("already validated the attribute"); 7576 return ::new (Ctx) PcsAttr(Ctx, Attr, Type); 7577 } 7578 case ParsedAttr::AT_IntelOclBicc: 7579 return createSimpleAttr<IntelOclBiccAttr>(Ctx, Attr); 7580 case ParsedAttr::AT_MSABI: 7581 return createSimpleAttr<MSABIAttr>(Ctx, Attr); 7582 case ParsedAttr::AT_SysVABI: 7583 return createSimpleAttr<SysVABIAttr>(Ctx, Attr); 7584 case ParsedAttr::AT_PreserveMost: 7585 return createSimpleAttr<PreserveMostAttr>(Ctx, Attr); 7586 case ParsedAttr::AT_PreserveAll: 7587 return createSimpleAttr<PreserveAllAttr>(Ctx, Attr); 7588 case ParsedAttr::AT_M68kRTD: 7589 return createSimpleAttr<M68kRTDAttr>(Ctx, Attr); 7590 case ParsedAttr::AT_PreserveNone: 7591 return createSimpleAttr<PreserveNoneAttr>(Ctx, Attr); 7592 case ParsedAttr::AT_RISCVVectorCC: 7593 return createSimpleAttr<RISCVVectorCCAttr>(Ctx, Attr); 7594 } 7595 llvm_unreachable("unexpected attribute kind!"); 7596 } 7597 7598 std::optional<FunctionEffectMode> 7599 Sema::ActOnEffectExpression(Expr *CondExpr, StringRef AttributeName) { 7600 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) 7601 return FunctionEffectMode::Dependent; 7602 7603 std::optional<llvm::APSInt> ConditionValue = 7604 CondExpr->getIntegerConstantExpr(Context); 7605 if (!ConditionValue) { 7606 // FIXME: err_attribute_argument_type doesn't quote the attribute 7607 // name but needs to; users are inconsistent. 7608 Diag(CondExpr->getExprLoc(), diag::err_attribute_argument_type) 7609 << AttributeName << AANT_ArgumentIntegerConstant 7610 << CondExpr->getSourceRange(); 7611 return std::nullopt; 7612 } 7613 return !ConditionValue->isZero() ? FunctionEffectMode::True 7614 : FunctionEffectMode::False; 7615 } 7616 7617 static bool 7618 handleNonBlockingNonAllocatingTypeAttr(TypeProcessingState &TPState, 7619 ParsedAttr &PAttr, QualType &QT, 7620 FunctionTypeUnwrapper &Unwrapped) { 7621 // Delay if this is not a function type. 7622 if (!Unwrapped.isFunctionType()) 7623 return false; 7624 7625 Sema &S = TPState.getSema(); 7626 7627 // Require FunctionProtoType. 7628 auto *FPT = Unwrapped.get()->getAs<FunctionProtoType>(); 7629 if (FPT == nullptr) { 7630 S.Diag(PAttr.getLoc(), diag::err_func_with_effects_no_prototype) 7631 << PAttr.getAttrName()->getName(); 7632 return true; 7633 } 7634 7635 // Parse the new attribute. 7636 // non/blocking or non/allocating? Or conditional (computed)? 7637 bool IsNonBlocking = PAttr.getKind() == ParsedAttr::AT_NonBlocking || 7638 PAttr.getKind() == ParsedAttr::AT_Blocking; 7639 7640 FunctionEffectMode NewMode = FunctionEffectMode::None; 7641 Expr *CondExpr = nullptr; // only valid if dependent 7642 7643 if (PAttr.getKind() == ParsedAttr::AT_NonBlocking || 7644 PAttr.getKind() == ParsedAttr::AT_NonAllocating) { 7645 if (!PAttr.checkAtMostNumArgs(S, 1)) { 7646 PAttr.setInvalid(); 7647 return true; 7648 } 7649 7650 // Parse the condition, if any. 7651 if (PAttr.getNumArgs() == 1) { 7652 CondExpr = PAttr.getArgAsExpr(0); 7653 std::optional<FunctionEffectMode> MaybeMode = 7654 S.ActOnEffectExpression(CondExpr, PAttr.getAttrName()->getName()); 7655 if (!MaybeMode) { 7656 PAttr.setInvalid(); 7657 return true; 7658 } 7659 NewMode = *MaybeMode; 7660 if (NewMode != FunctionEffectMode::Dependent) 7661 CondExpr = nullptr; 7662 } else { 7663 NewMode = FunctionEffectMode::True; 7664 } 7665 } else { 7666 // This is the `blocking` or `allocating` attribute. 7667 if (S.CheckAttrNoArgs(PAttr)) { 7668 // The attribute has been marked invalid. 7669 return true; 7670 } 7671 NewMode = FunctionEffectMode::False; 7672 } 7673 7674 const FunctionEffect::Kind FEKind = 7675 (NewMode == FunctionEffectMode::False) 7676 ? (IsNonBlocking ? FunctionEffect::Kind::Blocking 7677 : FunctionEffect::Kind::Allocating) 7678 : (IsNonBlocking ? FunctionEffect::Kind::NonBlocking 7679 : FunctionEffect::Kind::NonAllocating); 7680 const FunctionEffectWithCondition NewEC{FunctionEffect(FEKind), 7681 EffectConditionExpr(CondExpr)}; 7682 7683 if (S.diagnoseConflictingFunctionEffect(FPT->getFunctionEffects(), NewEC, 7684 PAttr.getLoc())) { 7685 PAttr.setInvalid(); 7686 return true; 7687 } 7688 7689 // Add the effect to the FunctionProtoType. 7690 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 7691 FunctionEffectSet FX(EPI.FunctionEffects); 7692 FunctionEffectSet::Conflicts Errs; 7693 [[maybe_unused]] bool Success = FX.insert(NewEC, Errs); 7694 assert(Success && "effect conflicts should have been diagnosed above"); 7695 EPI.FunctionEffects = FunctionEffectsRef(FX); 7696 7697 QualType NewType = S.Context.getFunctionType(FPT->getReturnType(), 7698 FPT->getParamTypes(), EPI); 7699 QT = Unwrapped.wrap(S, NewType->getAs<FunctionType>()); 7700 return true; 7701 } 7702 7703 static bool checkMutualExclusion(TypeProcessingState &state, 7704 const FunctionProtoType::ExtProtoInfo &EPI, 7705 ParsedAttr &Attr, 7706 AttributeCommonInfo::Kind OtherKind) { 7707 auto OtherAttr = std::find_if( 7708 state.getCurrentAttributes().begin(), state.getCurrentAttributes().end(), 7709 [OtherKind](const ParsedAttr &A) { return A.getKind() == OtherKind; }); 7710 if (OtherAttr == state.getCurrentAttributes().end() || OtherAttr->isInvalid()) 7711 return false; 7712 7713 Sema &S = state.getSema(); 7714 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible) 7715 << *OtherAttr << Attr 7716 << (OtherAttr->isRegularKeywordAttribute() || 7717 Attr.isRegularKeywordAttribute()); 7718 S.Diag(OtherAttr->getLoc(), diag::note_conflicting_attribute); 7719 Attr.setInvalid(); 7720 return true; 7721 } 7722 7723 static bool handleArmStateAttribute(Sema &S, 7724 FunctionProtoType::ExtProtoInfo &EPI, 7725 ParsedAttr &Attr, 7726 FunctionType::ArmStateValue State) { 7727 if (!Attr.getNumArgs()) { 7728 S.Diag(Attr.getLoc(), diag::err_missing_arm_state) << Attr; 7729 Attr.setInvalid(); 7730 return true; 7731 } 7732 7733 for (unsigned I = 0; I < Attr.getNumArgs(); ++I) { 7734 StringRef StateName; 7735 SourceLocation LiteralLoc; 7736 if (!S.checkStringLiteralArgumentAttr(Attr, I, StateName, &LiteralLoc)) 7737 return true; 7738 7739 unsigned Shift; 7740 FunctionType::ArmStateValue ExistingState; 7741 if (StateName == "za") { 7742 Shift = FunctionType::SME_ZAShift; 7743 ExistingState = FunctionType::getArmZAState(EPI.AArch64SMEAttributes); 7744 } else if (StateName == "zt0") { 7745 Shift = FunctionType::SME_ZT0Shift; 7746 ExistingState = FunctionType::getArmZT0State(EPI.AArch64SMEAttributes); 7747 } else { 7748 S.Diag(LiteralLoc, diag::err_unknown_arm_state) << StateName; 7749 Attr.setInvalid(); 7750 return true; 7751 } 7752 7753 // __arm_in(S), __arm_out(S), __arm_inout(S) and __arm_preserves(S) 7754 // are all mutually exclusive for the same S, so check if there are 7755 // conflicting attributes. 7756 if (ExistingState != FunctionType::ARM_None && ExistingState != State) { 7757 S.Diag(LiteralLoc, diag::err_conflicting_attributes_arm_state) 7758 << StateName; 7759 Attr.setInvalid(); 7760 return true; 7761 } 7762 7763 EPI.setArmSMEAttribute( 7764 (FunctionType::AArch64SMETypeAttributes)((State << Shift))); 7765 } 7766 return false; 7767 } 7768 7769 /// Process an individual function attribute. Returns true to 7770 /// indicate that the attribute was handled, false if it wasn't. 7771 static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr, 7772 QualType &type, CUDAFunctionTarget CFT) { 7773 Sema &S = state.getSema(); 7774 7775 FunctionTypeUnwrapper unwrapped(S, type); 7776 7777 if (attr.getKind() == ParsedAttr::AT_NoReturn) { 7778 if (S.CheckAttrNoArgs(attr)) 7779 return true; 7780 7781 // Delay if this is not a function type. 7782 if (!unwrapped.isFunctionType()) 7783 return false; 7784 7785 // Otherwise we can process right away. 7786 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true); 7787 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 7788 return true; 7789 } 7790 7791 if (attr.getKind() == ParsedAttr::AT_CmseNSCall) { 7792 // Delay if this is not a function type. 7793 if (!unwrapped.isFunctionType()) 7794 return false; 7795 7796 // Ignore if we don't have CMSE enabled. 7797 if (!S.getLangOpts().Cmse) { 7798 S.Diag(attr.getLoc(), diag::warn_attribute_ignored) << attr; 7799 attr.setInvalid(); 7800 return true; 7801 } 7802 7803 // Otherwise we can process right away. 7804 FunctionType::ExtInfo EI = 7805 unwrapped.get()->getExtInfo().withCmseNSCall(true); 7806 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 7807 return true; 7808 } 7809 7810 // ns_returns_retained is not always a type attribute, but if we got 7811 // here, we're treating it as one right now. 7812 if (attr.getKind() == ParsedAttr::AT_NSReturnsRetained) { 7813 if (attr.getNumArgs()) return true; 7814 7815 // Delay if this is not a function type. 7816 if (!unwrapped.isFunctionType()) 7817 return false; 7818 7819 // Check whether the return type is reasonable. 7820 if (S.ObjC().checkNSReturnsRetainedReturnType( 7821 attr.getLoc(), unwrapped.get()->getReturnType())) 7822 return true; 7823 7824 // Only actually change the underlying type in ARC builds. 7825 QualType origType = type; 7826 if (state.getSema().getLangOpts().ObjCAutoRefCount) { 7827 FunctionType::ExtInfo EI 7828 = unwrapped.get()->getExtInfo().withProducesResult(true); 7829 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 7830 } 7831 type = state.getAttributedType( 7832 createSimpleAttr<NSReturnsRetainedAttr>(S.Context, attr), 7833 origType, type); 7834 return true; 7835 } 7836 7837 if (attr.getKind() == ParsedAttr::AT_AnyX86NoCallerSavedRegisters) { 7838 if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr)) 7839 return true; 7840 7841 // Delay if this is not a function type. 7842 if (!unwrapped.isFunctionType()) 7843 return false; 7844 7845 FunctionType::ExtInfo EI = 7846 unwrapped.get()->getExtInfo().withNoCallerSavedRegs(true); 7847 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 7848 return true; 7849 } 7850 7851 if (attr.getKind() == ParsedAttr::AT_AnyX86NoCfCheck) { 7852 if (!S.getLangOpts().CFProtectionBranch) { 7853 S.Diag(attr.getLoc(), diag::warn_nocf_check_attribute_ignored); 7854 attr.setInvalid(); 7855 return true; 7856 } 7857 7858 if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr)) 7859 return true; 7860 7861 // If this is not a function type, warning will be asserted by subject 7862 // check. 7863 if (!unwrapped.isFunctionType()) 7864 return true; 7865 7866 FunctionType::ExtInfo EI = 7867 unwrapped.get()->getExtInfo().withNoCfCheck(true); 7868 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 7869 return true; 7870 } 7871 7872 if (attr.getKind() == ParsedAttr::AT_Regparm) { 7873 unsigned value; 7874 if (S.CheckRegparmAttr(attr, value)) 7875 return true; 7876 7877 // Delay if this is not a function type. 7878 if (!unwrapped.isFunctionType()) 7879 return false; 7880 7881 // Diagnose regparm with fastcall. 7882 const FunctionType *fn = unwrapped.get(); 7883 CallingConv CC = fn->getCallConv(); 7884 if (CC == CC_X86FastCall) { 7885 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 7886 << FunctionType::getNameForCallConv(CC) << "regparm" 7887 << attr.isRegularKeywordAttribute(); 7888 attr.setInvalid(); 7889 return true; 7890 } 7891 7892 FunctionType::ExtInfo EI = 7893 unwrapped.get()->getExtInfo().withRegParm(value); 7894 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 7895 return true; 7896 } 7897 7898 if (attr.getKind() == ParsedAttr::AT_ArmStreaming || 7899 attr.getKind() == ParsedAttr::AT_ArmStreamingCompatible || 7900 attr.getKind() == ParsedAttr::AT_ArmPreserves || 7901 attr.getKind() == ParsedAttr::AT_ArmIn || 7902 attr.getKind() == ParsedAttr::AT_ArmOut || 7903 attr.getKind() == ParsedAttr::AT_ArmInOut) { 7904 if (S.CheckAttrTarget(attr)) 7905 return true; 7906 7907 if (attr.getKind() == ParsedAttr::AT_ArmStreaming || 7908 attr.getKind() == ParsedAttr::AT_ArmStreamingCompatible) 7909 if (S.CheckAttrNoArgs(attr)) 7910 return true; 7911 7912 if (!unwrapped.isFunctionType()) 7913 return false; 7914 7915 const auto *FnTy = unwrapped.get()->getAs<FunctionProtoType>(); 7916 if (!FnTy) { 7917 // SME ACLE attributes are not supported on K&R-style unprototyped C 7918 // functions. 7919 S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type) << 7920 attr << attr.isRegularKeywordAttribute() << ExpectedFunctionWithProtoType; 7921 attr.setInvalid(); 7922 return false; 7923 } 7924 7925 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo(); 7926 switch (attr.getKind()) { 7927 case ParsedAttr::AT_ArmStreaming: 7928 if (checkMutualExclusion(state, EPI, attr, 7929 ParsedAttr::AT_ArmStreamingCompatible)) 7930 return true; 7931 EPI.setArmSMEAttribute(FunctionType::SME_PStateSMEnabledMask); 7932 break; 7933 case ParsedAttr::AT_ArmStreamingCompatible: 7934 if (checkMutualExclusion(state, EPI, attr, ParsedAttr::AT_ArmStreaming)) 7935 return true; 7936 EPI.setArmSMEAttribute(FunctionType::SME_PStateSMCompatibleMask); 7937 break; 7938 case ParsedAttr::AT_ArmPreserves: 7939 if (handleArmStateAttribute(S, EPI, attr, FunctionType::ARM_Preserves)) 7940 return true; 7941 break; 7942 case ParsedAttr::AT_ArmIn: 7943 if (handleArmStateAttribute(S, EPI, attr, FunctionType::ARM_In)) 7944 return true; 7945 break; 7946 case ParsedAttr::AT_ArmOut: 7947 if (handleArmStateAttribute(S, EPI, attr, FunctionType::ARM_Out)) 7948 return true; 7949 break; 7950 case ParsedAttr::AT_ArmInOut: 7951 if (handleArmStateAttribute(S, EPI, attr, FunctionType::ARM_InOut)) 7952 return true; 7953 break; 7954 default: 7955 llvm_unreachable("Unsupported attribute"); 7956 } 7957 7958 QualType newtype = S.Context.getFunctionType(FnTy->getReturnType(), 7959 FnTy->getParamTypes(), EPI); 7960 type = unwrapped.wrap(S, newtype->getAs<FunctionType>()); 7961 return true; 7962 } 7963 7964 if (attr.getKind() == ParsedAttr::AT_NoThrow) { 7965 // Delay if this is not a function type. 7966 if (!unwrapped.isFunctionType()) 7967 return false; 7968 7969 if (S.CheckAttrNoArgs(attr)) { 7970 attr.setInvalid(); 7971 return true; 7972 } 7973 7974 // Otherwise we can process right away. 7975 auto *Proto = unwrapped.get()->castAs<FunctionProtoType>(); 7976 7977 // MSVC ignores nothrow if it is in conflict with an explicit exception 7978 // specification. 7979 if (Proto->hasExceptionSpec()) { 7980 switch (Proto->getExceptionSpecType()) { 7981 case EST_None: 7982 llvm_unreachable("This doesn't have an exception spec!"); 7983 7984 case EST_DynamicNone: 7985 case EST_BasicNoexcept: 7986 case EST_NoexceptTrue: 7987 case EST_NoThrow: 7988 // Exception spec doesn't conflict with nothrow, so don't warn. 7989 [[fallthrough]]; 7990 case EST_Unparsed: 7991 case EST_Uninstantiated: 7992 case EST_DependentNoexcept: 7993 case EST_Unevaluated: 7994 // We don't have enough information to properly determine if there is a 7995 // conflict, so suppress the warning. 7996 break; 7997 case EST_Dynamic: 7998 case EST_MSAny: 7999 case EST_NoexceptFalse: 8000 S.Diag(attr.getLoc(), diag::warn_nothrow_attribute_ignored); 8001 break; 8002 } 8003 return true; 8004 } 8005 8006 type = unwrapped.wrap( 8007 S, S.Context 8008 .getFunctionTypeWithExceptionSpec( 8009 QualType{Proto, 0}, 8010 FunctionProtoType::ExceptionSpecInfo{EST_NoThrow}) 8011 ->getAs<FunctionType>()); 8012 return true; 8013 } 8014 8015 if (attr.getKind() == ParsedAttr::AT_NonBlocking || 8016 attr.getKind() == ParsedAttr::AT_NonAllocating || 8017 attr.getKind() == ParsedAttr::AT_Blocking || 8018 attr.getKind() == ParsedAttr::AT_Allocating) { 8019 return handleNonBlockingNonAllocatingTypeAttr(state, attr, type, unwrapped); 8020 } 8021 8022 // Delay if the type didn't work out to a function. 8023 if (!unwrapped.isFunctionType()) return false; 8024 8025 // Otherwise, a calling convention. 8026 CallingConv CC; 8027 if (S.CheckCallingConvAttr(attr, CC, /*FunctionDecl=*/nullptr, CFT)) 8028 return true; 8029 8030 const FunctionType *fn = unwrapped.get(); 8031 CallingConv CCOld = fn->getCallConv(); 8032 Attr *CCAttr = getCCTypeAttr(S.Context, attr); 8033 8034 if (CCOld != CC) { 8035 // Error out on when there's already an attribute on the type 8036 // and the CCs don't match. 8037 if (S.getCallingConvAttributedType(type)) { 8038 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 8039 << FunctionType::getNameForCallConv(CC) 8040 << FunctionType::getNameForCallConv(CCOld) 8041 << attr.isRegularKeywordAttribute(); 8042 attr.setInvalid(); 8043 return true; 8044 } 8045 } 8046 8047 // Diagnose use of variadic functions with calling conventions that 8048 // don't support them (e.g. because they're callee-cleanup). 8049 // We delay warning about this on unprototyped function declarations 8050 // until after redeclaration checking, just in case we pick up a 8051 // prototype that way. And apparently we also "delay" warning about 8052 // unprototyped function types in general, despite not necessarily having 8053 // much ability to diagnose it later. 8054 if (!supportsVariadicCall(CC)) { 8055 const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn); 8056 if (FnP && FnP->isVariadic()) { 8057 // stdcall and fastcall are ignored with a warning for GCC and MS 8058 // compatibility. 8059 if (CC == CC_X86StdCall || CC == CC_X86FastCall) 8060 return S.Diag(attr.getLoc(), diag::warn_cconv_unsupported) 8061 << FunctionType::getNameForCallConv(CC) 8062 << (int)Sema::CallingConventionIgnoredReason::VariadicFunction; 8063 8064 attr.setInvalid(); 8065 return S.Diag(attr.getLoc(), diag::err_cconv_varargs) 8066 << FunctionType::getNameForCallConv(CC); 8067 } 8068 } 8069 8070 // Also diagnose fastcall with regparm. 8071 if (CC == CC_X86FastCall && fn->getHasRegParm()) { 8072 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 8073 << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall) 8074 << attr.isRegularKeywordAttribute(); 8075 attr.setInvalid(); 8076 return true; 8077 } 8078 8079 // Modify the CC from the wrapped function type, wrap it all back, and then 8080 // wrap the whole thing in an AttributedType as written. The modified type 8081 // might have a different CC if we ignored the attribute. 8082 QualType Equivalent; 8083 if (CCOld == CC) { 8084 Equivalent = type; 8085 } else { 8086 auto EI = unwrapped.get()->getExtInfo().withCallingConv(CC); 8087 Equivalent = 8088 unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 8089 } 8090 type = state.getAttributedType(CCAttr, type, Equivalent); 8091 return true; 8092 } 8093 8094 bool Sema::hasExplicitCallingConv(QualType T) { 8095 const AttributedType *AT; 8096 8097 // Stop if we'd be stripping off a typedef sugar node to reach the 8098 // AttributedType. 8099 while ((AT = T->getAs<AttributedType>()) && 8100 AT->getAs<TypedefType>() == T->getAs<TypedefType>()) { 8101 if (AT->isCallingConv()) 8102 return true; 8103 T = AT->getModifiedType(); 8104 } 8105 return false; 8106 } 8107 8108 void Sema::adjustMemberFunctionCC(QualType &T, bool HasThisPointer, 8109 bool IsCtorOrDtor, SourceLocation Loc) { 8110 FunctionTypeUnwrapper Unwrapped(*this, T); 8111 const FunctionType *FT = Unwrapped.get(); 8112 bool IsVariadic = (isa<FunctionProtoType>(FT) && 8113 cast<FunctionProtoType>(FT)->isVariadic()); 8114 CallingConv CurCC = FT->getCallConv(); 8115 CallingConv ToCC = 8116 Context.getDefaultCallingConvention(IsVariadic, HasThisPointer); 8117 8118 if (CurCC == ToCC) 8119 return; 8120 8121 // MS compiler ignores explicit calling convention attributes on structors. We 8122 // should do the same. 8123 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) { 8124 // Issue a warning on ignored calling convention -- except of __stdcall. 8125 // Again, this is what MS compiler does. 8126 if (CurCC != CC_X86StdCall) 8127 Diag(Loc, diag::warn_cconv_unsupported) 8128 << FunctionType::getNameForCallConv(CurCC) 8129 << (int)Sema::CallingConventionIgnoredReason::ConstructorDestructor; 8130 // Default adjustment. 8131 } else { 8132 // Only adjust types with the default convention. For example, on Windows 8133 // we should adjust a __cdecl type to __thiscall for instance methods, and a 8134 // __thiscall type to __cdecl for static methods. 8135 CallingConv DefaultCC = 8136 Context.getDefaultCallingConvention(IsVariadic, !HasThisPointer); 8137 8138 if (CurCC != DefaultCC) 8139 return; 8140 8141 if (hasExplicitCallingConv(T)) 8142 return; 8143 } 8144 8145 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC)); 8146 QualType Wrapped = Unwrapped.wrap(*this, FT); 8147 T = Context.getAdjustedType(T, Wrapped); 8148 } 8149 8150 /// HandleVectorSizeAttribute - this attribute is only applicable to integral 8151 /// and float scalars, although arrays, pointers, and function return values are 8152 /// allowed in conjunction with this construct. Aggregates with this attribute 8153 /// are invalid, even if they are of the same size as a corresponding scalar. 8154 /// The raw attribute should contain precisely 1 argument, the vector size for 8155 /// the variable, measured in bytes. If curType and rawAttr are well formed, 8156 /// this routine will return a new vector type. 8157 static void HandleVectorSizeAttr(QualType &CurType, const ParsedAttr &Attr, 8158 Sema &S) { 8159 // Check the attribute arguments. 8160 if (Attr.getNumArgs() != 1) { 8161 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr 8162 << 1; 8163 Attr.setInvalid(); 8164 return; 8165 } 8166 8167 Expr *SizeExpr = Attr.getArgAsExpr(0); 8168 QualType T = S.BuildVectorType(CurType, SizeExpr, Attr.getLoc()); 8169 if (!T.isNull()) 8170 CurType = T; 8171 else 8172 Attr.setInvalid(); 8173 } 8174 8175 /// Process the OpenCL-like ext_vector_type attribute when it occurs on 8176 /// a type. 8177 static void HandleExtVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr, 8178 Sema &S) { 8179 // check the attribute arguments. 8180 if (Attr.getNumArgs() != 1) { 8181 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr 8182 << 1; 8183 return; 8184 } 8185 8186 Expr *SizeExpr = Attr.getArgAsExpr(0); 8187 QualType T = S.BuildExtVectorType(CurType, SizeExpr, Attr.getLoc()); 8188 if (!T.isNull()) 8189 CurType = T; 8190 } 8191 8192 static bool isPermittedNeonBaseType(QualType &Ty, VectorKind VecKind, Sema &S) { 8193 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 8194 if (!BTy) 8195 return false; 8196 8197 llvm::Triple Triple = S.Context.getTargetInfo().getTriple(); 8198 8199 // Signed poly is mathematically wrong, but has been baked into some ABIs by 8200 // now. 8201 bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 || 8202 Triple.getArch() == llvm::Triple::aarch64_32 || 8203 Triple.getArch() == llvm::Triple::aarch64_be; 8204 if (VecKind == VectorKind::NeonPoly) { 8205 if (IsPolyUnsigned) { 8206 // AArch64 polynomial vectors are unsigned. 8207 return BTy->getKind() == BuiltinType::UChar || 8208 BTy->getKind() == BuiltinType::UShort || 8209 BTy->getKind() == BuiltinType::ULong || 8210 BTy->getKind() == BuiltinType::ULongLong; 8211 } else { 8212 // AArch32 polynomial vectors are signed. 8213 return BTy->getKind() == BuiltinType::SChar || 8214 BTy->getKind() == BuiltinType::Short || 8215 BTy->getKind() == BuiltinType::LongLong; 8216 } 8217 } 8218 8219 // Non-polynomial vector types: the usual suspects are allowed, as well as 8220 // float64_t on AArch64. 8221 if ((Triple.isArch64Bit() || Triple.getArch() == llvm::Triple::aarch64_32) && 8222 BTy->getKind() == BuiltinType::Double) 8223 return true; 8224 8225 return BTy->getKind() == BuiltinType::SChar || 8226 BTy->getKind() == BuiltinType::UChar || 8227 BTy->getKind() == BuiltinType::Short || 8228 BTy->getKind() == BuiltinType::UShort || 8229 BTy->getKind() == BuiltinType::Int || 8230 BTy->getKind() == BuiltinType::UInt || 8231 BTy->getKind() == BuiltinType::Long || 8232 BTy->getKind() == BuiltinType::ULong || 8233 BTy->getKind() == BuiltinType::LongLong || 8234 BTy->getKind() == BuiltinType::ULongLong || 8235 BTy->getKind() == BuiltinType::Float || 8236 BTy->getKind() == BuiltinType::Half || 8237 BTy->getKind() == BuiltinType::BFloat16; 8238 } 8239 8240 static bool verifyValidIntegerConstantExpr(Sema &S, const ParsedAttr &Attr, 8241 llvm::APSInt &Result) { 8242 const auto *AttrExpr = Attr.getArgAsExpr(0); 8243 if (!AttrExpr->isTypeDependent()) { 8244 if (std::optional<llvm::APSInt> Res = 8245 AttrExpr->getIntegerConstantExpr(S.Context)) { 8246 Result = *Res; 8247 return true; 8248 } 8249 } 8250 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) 8251 << Attr << AANT_ArgumentIntegerConstant << AttrExpr->getSourceRange(); 8252 Attr.setInvalid(); 8253 return false; 8254 } 8255 8256 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and 8257 /// "neon_polyvector_type" attributes are used to create vector types that 8258 /// are mangled according to ARM's ABI. Otherwise, these types are identical 8259 /// to those created with the "vector_size" attribute. Unlike "vector_size" 8260 /// the argument to these Neon attributes is the number of vector elements, 8261 /// not the vector size in bytes. The vector width and element type must 8262 /// match one of the standard Neon vector types. 8263 static void HandleNeonVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr, 8264 Sema &S, VectorKind VecKind) { 8265 bool IsTargetCUDAAndHostARM = false; 8266 if (S.getLangOpts().CUDAIsDevice) { 8267 const TargetInfo *AuxTI = S.getASTContext().getAuxTargetInfo(); 8268 IsTargetCUDAAndHostARM = 8269 AuxTI && (AuxTI->getTriple().isAArch64() || AuxTI->getTriple().isARM()); 8270 } 8271 8272 // Target must have NEON (or MVE, whose vectors are similar enough 8273 // not to need a separate attribute) 8274 if (!S.Context.getTargetInfo().hasFeature("mve") && 8275 VecKind == VectorKind::Neon && 8276 S.Context.getTargetInfo().getTriple().isArmMClass()) { 8277 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported_m_profile) 8278 << Attr << "'mve'"; 8279 Attr.setInvalid(); 8280 return; 8281 } 8282 if (!S.Context.getTargetInfo().hasFeature("mve") && 8283 VecKind == VectorKind::NeonPoly && 8284 S.Context.getTargetInfo().getTriple().isArmMClass()) { 8285 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported_m_profile) 8286 << Attr << "'mve'"; 8287 Attr.setInvalid(); 8288 return; 8289 } 8290 8291 // Check the attribute arguments. 8292 if (Attr.getNumArgs() != 1) { 8293 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 8294 << Attr << 1; 8295 Attr.setInvalid(); 8296 return; 8297 } 8298 // The number of elements must be an ICE. 8299 llvm::APSInt numEltsInt(32); 8300 if (!verifyValidIntegerConstantExpr(S, Attr, numEltsInt)) 8301 return; 8302 8303 // Only certain element types are supported for Neon vectors. 8304 if (!isPermittedNeonBaseType(CurType, VecKind, S) && 8305 !IsTargetCUDAAndHostARM) { 8306 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType; 8307 Attr.setInvalid(); 8308 return; 8309 } 8310 8311 // The total size of the vector must be 64 or 128 bits. 8312 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType)); 8313 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue()); 8314 unsigned vecSize = typeSize * numElts; 8315 if (vecSize != 64 && vecSize != 128) { 8316 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType; 8317 Attr.setInvalid(); 8318 return; 8319 } 8320 8321 CurType = S.Context.getVectorType(CurType, numElts, VecKind); 8322 } 8323 8324 /// HandleArmSveVectorBitsTypeAttr - The "arm_sve_vector_bits" attribute is 8325 /// used to create fixed-length versions of sizeless SVE types defined by 8326 /// the ACLE, such as svint32_t and svbool_t. 8327 static void HandleArmSveVectorBitsTypeAttr(QualType &CurType, ParsedAttr &Attr, 8328 Sema &S) { 8329 // Target must have SVE. 8330 if (!S.Context.getTargetInfo().hasFeature("sve")) { 8331 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr << "'sve'"; 8332 Attr.setInvalid(); 8333 return; 8334 } 8335 8336 // Attribute is unsupported if '-msve-vector-bits=<bits>' isn't specified, or 8337 // if <bits>+ syntax is used. 8338 if (!S.getLangOpts().VScaleMin || 8339 S.getLangOpts().VScaleMin != S.getLangOpts().VScaleMax) { 8340 S.Diag(Attr.getLoc(), diag::err_attribute_arm_feature_sve_bits_unsupported) 8341 << Attr; 8342 Attr.setInvalid(); 8343 return; 8344 } 8345 8346 // Check the attribute arguments. 8347 if (Attr.getNumArgs() != 1) { 8348 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 8349 << Attr << 1; 8350 Attr.setInvalid(); 8351 return; 8352 } 8353 8354 // The vector size must be an integer constant expression. 8355 llvm::APSInt SveVectorSizeInBits(32); 8356 if (!verifyValidIntegerConstantExpr(S, Attr, SveVectorSizeInBits)) 8357 return; 8358 8359 unsigned VecSize = static_cast<unsigned>(SveVectorSizeInBits.getZExtValue()); 8360 8361 // The attribute vector size must match -msve-vector-bits. 8362 if (VecSize != S.getLangOpts().VScaleMin * 128) { 8363 S.Diag(Attr.getLoc(), diag::err_attribute_bad_sve_vector_size) 8364 << VecSize << S.getLangOpts().VScaleMin * 128; 8365 Attr.setInvalid(); 8366 return; 8367 } 8368 8369 // Attribute can only be attached to a single SVE vector or predicate type. 8370 if (!CurType->isSveVLSBuiltinType()) { 8371 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_sve_type) 8372 << Attr << CurType; 8373 Attr.setInvalid(); 8374 return; 8375 } 8376 8377 const auto *BT = CurType->castAs<BuiltinType>(); 8378 8379 QualType EltType = CurType->getSveEltType(S.Context); 8380 unsigned TypeSize = S.Context.getTypeSize(EltType); 8381 VectorKind VecKind = VectorKind::SveFixedLengthData; 8382 if (BT->getKind() == BuiltinType::SveBool) { 8383 // Predicates are represented as i8. 8384 VecSize /= S.Context.getCharWidth() * S.Context.getCharWidth(); 8385 VecKind = VectorKind::SveFixedLengthPredicate; 8386 } else 8387 VecSize /= TypeSize; 8388 CurType = S.Context.getVectorType(EltType, VecSize, VecKind); 8389 } 8390 8391 static void HandleArmMveStrictPolymorphismAttr(TypeProcessingState &State, 8392 QualType &CurType, 8393 ParsedAttr &Attr) { 8394 const VectorType *VT = dyn_cast<VectorType>(CurType); 8395 if (!VT || VT->getVectorKind() != VectorKind::Neon) { 8396 State.getSema().Diag(Attr.getLoc(), 8397 diag::err_attribute_arm_mve_polymorphism); 8398 Attr.setInvalid(); 8399 return; 8400 } 8401 8402 CurType = 8403 State.getAttributedType(createSimpleAttr<ArmMveStrictPolymorphismAttr>( 8404 State.getSema().Context, Attr), 8405 CurType, CurType); 8406 } 8407 8408 /// HandleRISCVRVVVectorBitsTypeAttr - The "riscv_rvv_vector_bits" attribute is 8409 /// used to create fixed-length versions of sizeless RVV types such as 8410 /// vint8m1_t_t. 8411 static void HandleRISCVRVVVectorBitsTypeAttr(QualType &CurType, 8412 ParsedAttr &Attr, Sema &S) { 8413 // Target must have vector extension. 8414 if (!S.Context.getTargetInfo().hasFeature("zve32x")) { 8415 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) 8416 << Attr << "'zve32x'"; 8417 Attr.setInvalid(); 8418 return; 8419 } 8420 8421 auto VScale = S.Context.getTargetInfo().getVScaleRange(S.getLangOpts()); 8422 if (!VScale || !VScale->first || VScale->first != VScale->second) { 8423 S.Diag(Attr.getLoc(), diag::err_attribute_riscv_rvv_bits_unsupported) 8424 << Attr; 8425 Attr.setInvalid(); 8426 return; 8427 } 8428 8429 // Check the attribute arguments. 8430 if (Attr.getNumArgs() != 1) { 8431 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 8432 << Attr << 1; 8433 Attr.setInvalid(); 8434 return; 8435 } 8436 8437 // The vector size must be an integer constant expression. 8438 llvm::APSInt RVVVectorSizeInBits(32); 8439 if (!verifyValidIntegerConstantExpr(S, Attr, RVVVectorSizeInBits)) 8440 return; 8441 8442 // Attribute can only be attached to a single RVV vector type. 8443 if (!CurType->isRVVVLSBuiltinType()) { 8444 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_rvv_type) 8445 << Attr << CurType; 8446 Attr.setInvalid(); 8447 return; 8448 } 8449 8450 unsigned VecSize = static_cast<unsigned>(RVVVectorSizeInBits.getZExtValue()); 8451 8452 ASTContext::BuiltinVectorTypeInfo Info = 8453 S.Context.getBuiltinVectorTypeInfo(CurType->castAs<BuiltinType>()); 8454 unsigned MinElts = Info.EC.getKnownMinValue(); 8455 8456 VectorKind VecKind = VectorKind::RVVFixedLengthData; 8457 unsigned ExpectedSize = VScale->first * MinElts; 8458 QualType EltType = CurType->getRVVEltType(S.Context); 8459 unsigned EltSize = S.Context.getTypeSize(EltType); 8460 unsigned NumElts; 8461 if (Info.ElementType == S.Context.BoolTy) { 8462 NumElts = VecSize / S.Context.getCharWidth(); 8463 if (!NumElts) { 8464 NumElts = 1; 8465 switch (VecSize) { 8466 case 1: 8467 VecKind = VectorKind::RVVFixedLengthMask_1; 8468 break; 8469 case 2: 8470 VecKind = VectorKind::RVVFixedLengthMask_2; 8471 break; 8472 case 4: 8473 VecKind = VectorKind::RVVFixedLengthMask_4; 8474 break; 8475 } 8476 } else 8477 VecKind = VectorKind::RVVFixedLengthMask; 8478 } else { 8479 ExpectedSize *= EltSize; 8480 NumElts = VecSize / EltSize; 8481 } 8482 8483 // The attribute vector size must match -mrvv-vector-bits. 8484 if (VecSize != ExpectedSize) { 8485 S.Diag(Attr.getLoc(), diag::err_attribute_bad_rvv_vector_size) 8486 << VecSize << ExpectedSize; 8487 Attr.setInvalid(); 8488 return; 8489 } 8490 8491 CurType = S.Context.getVectorType(EltType, NumElts, VecKind); 8492 } 8493 8494 /// Handle OpenCL Access Qualifier Attribute. 8495 static void HandleOpenCLAccessAttr(QualType &CurType, const ParsedAttr &Attr, 8496 Sema &S) { 8497 // OpenCL v2.0 s6.6 - Access qualifier can be used only for image and pipe type. 8498 if (!(CurType->isImageType() || CurType->isPipeType())) { 8499 S.Diag(Attr.getLoc(), diag::err_opencl_invalid_access_qualifier); 8500 Attr.setInvalid(); 8501 return; 8502 } 8503 8504 if (const TypedefType* TypedefTy = CurType->getAs<TypedefType>()) { 8505 QualType BaseTy = TypedefTy->desugar(); 8506 8507 std::string PrevAccessQual; 8508 if (BaseTy->isPipeType()) { 8509 if (TypedefTy->getDecl()->hasAttr<OpenCLAccessAttr>()) { 8510 OpenCLAccessAttr *Attr = 8511 TypedefTy->getDecl()->getAttr<OpenCLAccessAttr>(); 8512 PrevAccessQual = Attr->getSpelling(); 8513 } else { 8514 PrevAccessQual = "read_only"; 8515 } 8516 } else if (const BuiltinType* ImgType = BaseTy->getAs<BuiltinType>()) { 8517 8518 switch (ImgType->getKind()) { 8519 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 8520 case BuiltinType::Id: \ 8521 PrevAccessQual = #Access; \ 8522 break; 8523 #include "clang/Basic/OpenCLImageTypes.def" 8524 default: 8525 llvm_unreachable("Unable to find corresponding image type."); 8526 } 8527 } else { 8528 llvm_unreachable("unexpected type"); 8529 } 8530 StringRef AttrName = Attr.getAttrName()->getName(); 8531 if (PrevAccessQual == AttrName.ltrim("_")) { 8532 // Duplicated qualifiers 8533 S.Diag(Attr.getLoc(), diag::warn_duplicate_declspec) 8534 << AttrName << Attr.getRange(); 8535 } else { 8536 // Contradicting qualifiers 8537 S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers); 8538 } 8539 8540 S.Diag(TypedefTy->getDecl()->getBeginLoc(), 8541 diag::note_opencl_typedef_access_qualifier) << PrevAccessQual; 8542 } else if (CurType->isPipeType()) { 8543 if (Attr.getSemanticSpelling() == OpenCLAccessAttr::Keyword_write_only) { 8544 QualType ElemType = CurType->castAs<PipeType>()->getElementType(); 8545 CurType = S.Context.getWritePipeType(ElemType); 8546 } 8547 } 8548 } 8549 8550 /// HandleMatrixTypeAttr - "matrix_type" attribute, like ext_vector_type 8551 static void HandleMatrixTypeAttr(QualType &CurType, const ParsedAttr &Attr, 8552 Sema &S) { 8553 if (!S.getLangOpts().MatrixTypes) { 8554 S.Diag(Attr.getLoc(), diag::err_builtin_matrix_disabled); 8555 return; 8556 } 8557 8558 if (Attr.getNumArgs() != 2) { 8559 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 8560 << Attr << 2; 8561 return; 8562 } 8563 8564 Expr *RowsExpr = Attr.getArgAsExpr(0); 8565 Expr *ColsExpr = Attr.getArgAsExpr(1); 8566 QualType T = S.BuildMatrixType(CurType, RowsExpr, ColsExpr, Attr.getLoc()); 8567 if (!T.isNull()) 8568 CurType = T; 8569 } 8570 8571 static void HandleAnnotateTypeAttr(TypeProcessingState &State, 8572 QualType &CurType, const ParsedAttr &PA) { 8573 Sema &S = State.getSema(); 8574 8575 if (PA.getNumArgs() < 1) { 8576 S.Diag(PA.getLoc(), diag::err_attribute_too_few_arguments) << PA << 1; 8577 return; 8578 } 8579 8580 // Make sure that there is a string literal as the annotation's first 8581 // argument. 8582 StringRef Str; 8583 if (!S.checkStringLiteralArgumentAttr(PA, 0, Str)) 8584 return; 8585 8586 llvm::SmallVector<Expr *, 4> Args; 8587 Args.reserve(PA.getNumArgs() - 1); 8588 for (unsigned Idx = 1; Idx < PA.getNumArgs(); Idx++) { 8589 assert(!PA.isArgIdent(Idx)); 8590 Args.push_back(PA.getArgAsExpr(Idx)); 8591 } 8592 if (!S.ConstantFoldAttrArgs(PA, Args)) 8593 return; 8594 auto *AnnotateTypeAttr = 8595 AnnotateTypeAttr::Create(S.Context, Str, Args.data(), Args.size(), PA); 8596 CurType = State.getAttributedType(AnnotateTypeAttr, CurType, CurType); 8597 } 8598 8599 static void HandleLifetimeBoundAttr(TypeProcessingState &State, 8600 QualType &CurType, 8601 ParsedAttr &Attr) { 8602 if (State.getDeclarator().isDeclarationOfFunction()) { 8603 CurType = State.getAttributedType( 8604 createSimpleAttr<LifetimeBoundAttr>(State.getSema().Context, Attr), 8605 CurType, CurType); 8606 } 8607 } 8608 8609 static void HandleHLSLParamModifierAttr(TypeProcessingState &State, 8610 QualType &CurType, 8611 const ParsedAttr &Attr, Sema &S) { 8612 // Don't apply this attribute to template dependent types. It is applied on 8613 // substitution during template instantiation. Also skip parsing this if we've 8614 // already modified the type based on an earlier attribute. 8615 if (CurType->isDependentType() || State.didParseHLSLParamMod()) 8616 return; 8617 if (Attr.getSemanticSpelling() == HLSLParamModifierAttr::Keyword_inout || 8618 Attr.getSemanticSpelling() == HLSLParamModifierAttr::Keyword_out) { 8619 CurType = S.HLSL().getInoutParameterType(CurType); 8620 State.setParsedHLSLParamMod(true); 8621 } 8622 } 8623 8624 static void processTypeAttrs(TypeProcessingState &state, QualType &type, 8625 TypeAttrLocation TAL, 8626 const ParsedAttributesView &attrs, 8627 CUDAFunctionTarget CFT) { 8628 8629 state.setParsedNoDeref(false); 8630 if (attrs.empty()) 8631 return; 8632 8633 // Scan through and apply attributes to this type where it makes sense. Some 8634 // attributes (such as __address_space__, __vector_size__, etc) apply to the 8635 // type, but others can be present in the type specifiers even though they 8636 // apply to the decl. Here we apply type attributes and ignore the rest. 8637 8638 // This loop modifies the list pretty frequently, but we still need to make 8639 // sure we visit every element once. Copy the attributes list, and iterate 8640 // over that. 8641 ParsedAttributesView AttrsCopy{attrs}; 8642 for (ParsedAttr &attr : AttrsCopy) { 8643 8644 // Skip attributes that were marked to be invalid. 8645 if (attr.isInvalid()) 8646 continue; 8647 8648 if (attr.isStandardAttributeSyntax() || attr.isRegularKeywordAttribute()) { 8649 // [[gnu::...]] attributes are treated as declaration attributes, so may 8650 // not appertain to a DeclaratorChunk. If we handle them as type 8651 // attributes, accept them in that position and diagnose the GCC 8652 // incompatibility. 8653 if (attr.isGNUScope()) { 8654 assert(attr.isStandardAttributeSyntax()); 8655 bool IsTypeAttr = attr.isTypeAttr(); 8656 if (TAL == TAL_DeclChunk) { 8657 state.getSema().Diag(attr.getLoc(), 8658 IsTypeAttr 8659 ? diag::warn_gcc_ignores_type_attr 8660 : diag::warn_cxx11_gnu_attribute_on_type) 8661 << attr; 8662 if (!IsTypeAttr) 8663 continue; 8664 } 8665 } else if (TAL != TAL_DeclSpec && TAL != TAL_DeclChunk && 8666 !attr.isTypeAttr()) { 8667 // Otherwise, only consider type processing for a C++11 attribute if 8668 // - it has actually been applied to a type (decl-specifier-seq or 8669 // declarator chunk), or 8670 // - it is a type attribute, irrespective of where it was applied (so 8671 // that we can support the legacy behavior of some type attributes 8672 // that can be applied to the declaration name). 8673 continue; 8674 } 8675 } 8676 8677 // If this is an attribute we can handle, do so now, 8678 // otherwise, add it to the FnAttrs list for rechaining. 8679 switch (attr.getKind()) { 8680 default: 8681 // A [[]] attribute on a declarator chunk must appertain to a type. 8682 if ((attr.isStandardAttributeSyntax() || 8683 attr.isRegularKeywordAttribute()) && 8684 TAL == TAL_DeclChunk) { 8685 state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr) 8686 << attr << attr.isRegularKeywordAttribute(); 8687 attr.setUsedAsTypeAttr(); 8688 } 8689 break; 8690 8691 case ParsedAttr::UnknownAttribute: 8692 if (attr.isStandardAttributeSyntax()) { 8693 state.getSema().Diag(attr.getLoc(), 8694 diag::warn_unknown_attribute_ignored) 8695 << attr << attr.getRange(); 8696 // Mark the attribute as invalid so we don't emit the same diagnostic 8697 // multiple times. 8698 attr.setInvalid(); 8699 } 8700 break; 8701 8702 case ParsedAttr::IgnoredAttribute: 8703 break; 8704 8705 case ParsedAttr::AT_BTFTypeTag: 8706 HandleBTFTypeTagAttribute(type, attr, state); 8707 attr.setUsedAsTypeAttr(); 8708 break; 8709 8710 case ParsedAttr::AT_MayAlias: 8711 // FIXME: This attribute needs to actually be handled, but if we ignore 8712 // it it breaks large amounts of Linux software. 8713 attr.setUsedAsTypeAttr(); 8714 break; 8715 case ParsedAttr::AT_OpenCLPrivateAddressSpace: 8716 case ParsedAttr::AT_OpenCLGlobalAddressSpace: 8717 case ParsedAttr::AT_OpenCLGlobalDeviceAddressSpace: 8718 case ParsedAttr::AT_OpenCLGlobalHostAddressSpace: 8719 case ParsedAttr::AT_OpenCLLocalAddressSpace: 8720 case ParsedAttr::AT_OpenCLConstantAddressSpace: 8721 case ParsedAttr::AT_OpenCLGenericAddressSpace: 8722 case ParsedAttr::AT_HLSLGroupSharedAddressSpace: 8723 case ParsedAttr::AT_AddressSpace: 8724 HandleAddressSpaceTypeAttribute(type, attr, state); 8725 attr.setUsedAsTypeAttr(); 8726 break; 8727 OBJC_POINTER_TYPE_ATTRS_CASELIST: 8728 if (!handleObjCPointerTypeAttr(state, attr, type)) 8729 distributeObjCPointerTypeAttr(state, attr, type); 8730 attr.setUsedAsTypeAttr(); 8731 break; 8732 case ParsedAttr::AT_VectorSize: 8733 HandleVectorSizeAttr(type, attr, state.getSema()); 8734 attr.setUsedAsTypeAttr(); 8735 break; 8736 case ParsedAttr::AT_ExtVectorType: 8737 HandleExtVectorTypeAttr(type, attr, state.getSema()); 8738 attr.setUsedAsTypeAttr(); 8739 break; 8740 case ParsedAttr::AT_NeonVectorType: 8741 HandleNeonVectorTypeAttr(type, attr, state.getSema(), VectorKind::Neon); 8742 attr.setUsedAsTypeAttr(); 8743 break; 8744 case ParsedAttr::AT_NeonPolyVectorType: 8745 HandleNeonVectorTypeAttr(type, attr, state.getSema(), 8746 VectorKind::NeonPoly); 8747 attr.setUsedAsTypeAttr(); 8748 break; 8749 case ParsedAttr::AT_ArmSveVectorBits: 8750 HandleArmSveVectorBitsTypeAttr(type, attr, state.getSema()); 8751 attr.setUsedAsTypeAttr(); 8752 break; 8753 case ParsedAttr::AT_ArmMveStrictPolymorphism: { 8754 HandleArmMveStrictPolymorphismAttr(state, type, attr); 8755 attr.setUsedAsTypeAttr(); 8756 break; 8757 } 8758 case ParsedAttr::AT_RISCVRVVVectorBits: 8759 HandleRISCVRVVVectorBitsTypeAttr(type, attr, state.getSema()); 8760 attr.setUsedAsTypeAttr(); 8761 break; 8762 case ParsedAttr::AT_OpenCLAccess: 8763 HandleOpenCLAccessAttr(type, attr, state.getSema()); 8764 attr.setUsedAsTypeAttr(); 8765 break; 8766 case ParsedAttr::AT_LifetimeBound: 8767 if (TAL == TAL_DeclChunk) 8768 HandleLifetimeBoundAttr(state, type, attr); 8769 break; 8770 8771 case ParsedAttr::AT_NoDeref: { 8772 // FIXME: `noderef` currently doesn't work correctly in [[]] syntax. 8773 // See https://github.com/llvm/llvm-project/issues/55790 for details. 8774 // For the time being, we simply emit a warning that the attribute is 8775 // ignored. 8776 if (attr.isStandardAttributeSyntax()) { 8777 state.getSema().Diag(attr.getLoc(), diag::warn_attribute_ignored) 8778 << attr; 8779 break; 8780 } 8781 ASTContext &Ctx = state.getSema().Context; 8782 type = state.getAttributedType(createSimpleAttr<NoDerefAttr>(Ctx, attr), 8783 type, type); 8784 attr.setUsedAsTypeAttr(); 8785 state.setParsedNoDeref(true); 8786 break; 8787 } 8788 8789 case ParsedAttr::AT_MatrixType: 8790 HandleMatrixTypeAttr(type, attr, state.getSema()); 8791 attr.setUsedAsTypeAttr(); 8792 break; 8793 8794 case ParsedAttr::AT_WebAssemblyFuncref: { 8795 if (!HandleWebAssemblyFuncrefAttr(state, type, attr)) 8796 attr.setUsedAsTypeAttr(); 8797 break; 8798 } 8799 8800 case ParsedAttr::AT_HLSLParamModifier: { 8801 HandleHLSLParamModifierAttr(state, type, attr, state.getSema()); 8802 attr.setUsedAsTypeAttr(); 8803 break; 8804 } 8805 8806 case ParsedAttr::AT_SwiftAttr: { 8807 HandleSwiftAttr(state, TAL, type, attr); 8808 break; 8809 } 8810 8811 MS_TYPE_ATTRS_CASELIST: 8812 if (!handleMSPointerTypeQualifierAttr(state, attr, type)) 8813 attr.setUsedAsTypeAttr(); 8814 break; 8815 8816 8817 NULLABILITY_TYPE_ATTRS_CASELIST: 8818 // Either add nullability here or try to distribute it. We 8819 // don't want to distribute the nullability specifier past any 8820 // dependent type, because that complicates the user model. 8821 if (type->canHaveNullability() || type->isDependentType() || 8822 type->isArrayType() || 8823 !distributeNullabilityTypeAttr(state, type, attr)) { 8824 unsigned endIndex; 8825 if (TAL == TAL_DeclChunk) 8826 endIndex = state.getCurrentChunkIndex(); 8827 else 8828 endIndex = state.getDeclarator().getNumTypeObjects(); 8829 bool allowOnArrayType = 8830 state.getDeclarator().isPrototypeContext() && 8831 !hasOuterPointerLikeChunk(state.getDeclarator(), endIndex); 8832 if (CheckNullabilityTypeSpecifier(state, type, attr, 8833 allowOnArrayType)) { 8834 attr.setInvalid(); 8835 } 8836 8837 attr.setUsedAsTypeAttr(); 8838 } 8839 break; 8840 8841 case ParsedAttr::AT_ObjCKindOf: 8842 // '__kindof' must be part of the decl-specifiers. 8843 switch (TAL) { 8844 case TAL_DeclSpec: 8845 break; 8846 8847 case TAL_DeclChunk: 8848 case TAL_DeclName: 8849 state.getSema().Diag(attr.getLoc(), 8850 diag::err_objc_kindof_wrong_position) 8851 << FixItHint::CreateRemoval(attr.getLoc()) 8852 << FixItHint::CreateInsertion( 8853 state.getDeclarator().getDeclSpec().getBeginLoc(), 8854 "__kindof "); 8855 break; 8856 } 8857 8858 // Apply it regardless. 8859 if (checkObjCKindOfType(state, type, attr)) 8860 attr.setInvalid(); 8861 break; 8862 8863 case ParsedAttr::AT_NoThrow: 8864 // Exception Specifications aren't generally supported in C mode throughout 8865 // clang, so revert to attribute-based handling for C. 8866 if (!state.getSema().getLangOpts().CPlusPlus) 8867 break; 8868 [[fallthrough]]; 8869 FUNCTION_TYPE_ATTRS_CASELIST: 8870 attr.setUsedAsTypeAttr(); 8871 8872 // Attributes with standard syntax have strict rules for what they 8873 // appertain to and hence should not use the "distribution" logic below. 8874 if (attr.isStandardAttributeSyntax() || 8875 attr.isRegularKeywordAttribute()) { 8876 if (!handleFunctionTypeAttr(state, attr, type, CFT)) { 8877 diagnoseBadTypeAttribute(state.getSema(), attr, type); 8878 attr.setInvalid(); 8879 } 8880 break; 8881 } 8882 8883 // Never process function type attributes as part of the 8884 // declaration-specifiers. 8885 if (TAL == TAL_DeclSpec) 8886 distributeFunctionTypeAttrFromDeclSpec(state, attr, type, CFT); 8887 8888 // Otherwise, handle the possible delays. 8889 else if (!handleFunctionTypeAttr(state, attr, type, CFT)) 8890 distributeFunctionTypeAttr(state, attr, type); 8891 break; 8892 case ParsedAttr::AT_AcquireHandle: { 8893 if (!type->isFunctionType()) 8894 return; 8895 8896 if (attr.getNumArgs() != 1) { 8897 state.getSema().Diag(attr.getLoc(), 8898 diag::err_attribute_wrong_number_arguments) 8899 << attr << 1; 8900 attr.setInvalid(); 8901 return; 8902 } 8903 8904 StringRef HandleType; 8905 if (!state.getSema().checkStringLiteralArgumentAttr(attr, 0, HandleType)) 8906 return; 8907 type = state.getAttributedType( 8908 AcquireHandleAttr::Create(state.getSema().Context, HandleType, attr), 8909 type, type); 8910 attr.setUsedAsTypeAttr(); 8911 break; 8912 } 8913 case ParsedAttr::AT_AnnotateType: { 8914 HandleAnnotateTypeAttr(state, type, attr); 8915 attr.setUsedAsTypeAttr(); 8916 break; 8917 } 8918 case ParsedAttr::AT_HLSLResourceClass: 8919 case ParsedAttr::AT_HLSLROV: 8920 case ParsedAttr::AT_HLSLRawBuffer: 8921 case ParsedAttr::AT_HLSLContainedType: { 8922 // Only collect HLSL resource type attributes that are in 8923 // decl-specifier-seq; do not collect attributes on declarations or those 8924 // that get to slide after declaration name. 8925 if (TAL == TAL_DeclSpec && 8926 state.getSema().HLSL().handleResourceTypeAttr(type, attr)) 8927 attr.setUsedAsTypeAttr(); 8928 break; 8929 } 8930 } 8931 8932 // Handle attributes that are defined in a macro. We do not want this to be 8933 // applied to ObjC builtin attributes. 8934 if (isa<AttributedType>(type) && attr.hasMacroIdentifier() && 8935 !type.getQualifiers().hasObjCLifetime() && 8936 !type.getQualifiers().hasObjCGCAttr() && 8937 attr.getKind() != ParsedAttr::AT_ObjCGC && 8938 attr.getKind() != ParsedAttr::AT_ObjCOwnership) { 8939 const IdentifierInfo *MacroII = attr.getMacroIdentifier(); 8940 type = state.getSema().Context.getMacroQualifiedType(type, MacroII); 8941 state.setExpansionLocForMacroQualifiedType( 8942 cast<MacroQualifiedType>(type.getTypePtr()), 8943 attr.getMacroExpansionLoc()); 8944 } 8945 } 8946 } 8947 8948 void Sema::completeExprArrayBound(Expr *E) { 8949 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 8950 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 8951 if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) { 8952 auto *Def = Var->getDefinition(); 8953 if (!Def) { 8954 SourceLocation PointOfInstantiation = E->getExprLoc(); 8955 runWithSufficientStackSpace(PointOfInstantiation, [&] { 8956 InstantiateVariableDefinition(PointOfInstantiation, Var); 8957 }); 8958 Def = Var->getDefinition(); 8959 8960 // If we don't already have a point of instantiation, and we managed 8961 // to instantiate a definition, this is the point of instantiation. 8962 // Otherwise, we don't request an end-of-TU instantiation, so this is 8963 // not a point of instantiation. 8964 // FIXME: Is this really the right behavior? 8965 if (Var->getPointOfInstantiation().isInvalid() && Def) { 8966 assert(Var->getTemplateSpecializationKind() == 8967 TSK_ImplicitInstantiation && 8968 "explicit instantiation with no point of instantiation"); 8969 Var->setTemplateSpecializationKind( 8970 Var->getTemplateSpecializationKind(), PointOfInstantiation); 8971 } 8972 } 8973 8974 // Update the type to the definition's type both here and within the 8975 // expression. 8976 if (Def) { 8977 DRE->setDecl(Def); 8978 QualType T = Def->getType(); 8979 DRE->setType(T); 8980 // FIXME: Update the type on all intervening expressions. 8981 E->setType(T); 8982 } 8983 8984 // We still go on to try to complete the type independently, as it 8985 // may also require instantiations or diagnostics if it remains 8986 // incomplete. 8987 } 8988 } 8989 } 8990 if (const auto CastE = dyn_cast<ExplicitCastExpr>(E)) { 8991 QualType DestType = CastE->getTypeAsWritten(); 8992 if (const auto *IAT = Context.getAsIncompleteArrayType(DestType)) { 8993 // C++20 [expr.static.cast]p.4: ... If T is array of unknown bound, 8994 // this direct-initialization defines the type of the expression 8995 // as U[1] 8996 QualType ResultType = Context.getConstantArrayType( 8997 IAT->getElementType(), 8998 llvm::APInt(Context.getTypeSize(Context.getSizeType()), 1), 8999 /*SizeExpr=*/nullptr, ArraySizeModifier::Normal, 9000 /*IndexTypeQuals=*/0); 9001 E->setType(ResultType); 9002 } 9003 } 9004 } 9005 9006 QualType Sema::getCompletedType(Expr *E) { 9007 // Incomplete array types may be completed by the initializer attached to 9008 // their definitions. For static data members of class templates and for 9009 // variable templates, we need to instantiate the definition to get this 9010 // initializer and complete the type. 9011 if (E->getType()->isIncompleteArrayType()) 9012 completeExprArrayBound(E); 9013 9014 // FIXME: Are there other cases which require instantiating something other 9015 // than the type to complete the type of an expression? 9016 9017 return E->getType(); 9018 } 9019 9020 bool Sema::RequireCompleteExprType(Expr *E, CompleteTypeKind Kind, 9021 TypeDiagnoser &Diagnoser) { 9022 return RequireCompleteType(E->getExprLoc(), getCompletedType(E), Kind, 9023 Diagnoser); 9024 } 9025 9026 bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) { 9027 BoundTypeDiagnoser<> Diagnoser(DiagID); 9028 return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser); 9029 } 9030 9031 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, 9032 CompleteTypeKind Kind, 9033 TypeDiagnoser &Diagnoser) { 9034 if (RequireCompleteTypeImpl(Loc, T, Kind, &Diagnoser)) 9035 return true; 9036 if (const TagType *Tag = T->getAs<TagType>()) { 9037 if (!Tag->getDecl()->isCompleteDefinitionRequired()) { 9038 Tag->getDecl()->setCompleteDefinitionRequired(); 9039 Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl()); 9040 } 9041 } 9042 return false; 9043 } 9044 9045 bool Sema::hasStructuralCompatLayout(Decl *D, Decl *Suggested) { 9046 llvm::DenseSet<std::pair<Decl *, Decl *>> NonEquivalentDecls; 9047 if (!Suggested) 9048 return false; 9049 9050 // FIXME: Add a specific mode for C11 6.2.7/1 in StructuralEquivalenceContext 9051 // and isolate from other C++ specific checks. 9052 StructuralEquivalenceContext Ctx( 9053 D->getASTContext(), Suggested->getASTContext(), NonEquivalentDecls, 9054 StructuralEquivalenceKind::Default, 9055 false /*StrictTypeSpelling*/, true /*Complain*/, 9056 true /*ErrorOnTagTypeMismatch*/); 9057 return Ctx.IsEquivalent(D, Suggested); 9058 } 9059 9060 bool Sema::hasAcceptableDefinition(NamedDecl *D, NamedDecl **Suggested, 9061 AcceptableKind Kind, bool OnlyNeedComplete) { 9062 // Easy case: if we don't have modules, all declarations are visible. 9063 if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility) 9064 return true; 9065 9066 // If this definition was instantiated from a template, map back to the 9067 // pattern from which it was instantiated. 9068 if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined()) { 9069 // We're in the middle of defining it; this definition should be treated 9070 // as visible. 9071 return true; 9072 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 9073 if (auto *Pattern = RD->getTemplateInstantiationPattern()) 9074 RD = Pattern; 9075 D = RD->getDefinition(); 9076 } else if (auto *ED = dyn_cast<EnumDecl>(D)) { 9077 if (auto *Pattern = ED->getTemplateInstantiationPattern()) 9078 ED = Pattern; 9079 if (OnlyNeedComplete && (ED->isFixed() || getLangOpts().MSVCCompat)) { 9080 // If the enum has a fixed underlying type, it may have been forward 9081 // declared. In -fms-compatibility, `enum Foo;` will also forward declare 9082 // the enum and assign it the underlying type of `int`. Since we're only 9083 // looking for a complete type (not a definition), any visible declaration 9084 // of it will do. 9085 *Suggested = nullptr; 9086 for (auto *Redecl : ED->redecls()) { 9087 if (isAcceptable(Redecl, Kind)) 9088 return true; 9089 if (Redecl->isThisDeclarationADefinition() || 9090 (Redecl->isCanonicalDecl() && !*Suggested)) 9091 *Suggested = Redecl; 9092 } 9093 9094 return false; 9095 } 9096 D = ED->getDefinition(); 9097 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) { 9098 if (auto *Pattern = FD->getTemplateInstantiationPattern()) 9099 FD = Pattern; 9100 D = FD->getDefinition(); 9101 } else if (auto *VD = dyn_cast<VarDecl>(D)) { 9102 if (auto *Pattern = VD->getTemplateInstantiationPattern()) 9103 VD = Pattern; 9104 D = VD->getDefinition(); 9105 } 9106 9107 assert(D && "missing definition for pattern of instantiated definition"); 9108 9109 *Suggested = D; 9110 9111 auto DefinitionIsAcceptable = [&] { 9112 // The (primary) definition might be in a visible module. 9113 if (isAcceptable(D, Kind)) 9114 return true; 9115 9116 // A visible module might have a merged definition instead. 9117 if (D->isModulePrivate() ? hasMergedDefinitionInCurrentModule(D) 9118 : hasVisibleMergedDefinition(D)) { 9119 if (CodeSynthesisContexts.empty() && 9120 !getLangOpts().ModulesLocalVisibility) { 9121 // Cache the fact that this definition is implicitly visible because 9122 // there is a visible merged definition. 9123 D->setVisibleDespiteOwningModule(); 9124 } 9125 return true; 9126 } 9127 9128 return false; 9129 }; 9130 9131 if (DefinitionIsAcceptable()) 9132 return true; 9133 9134 // The external source may have additional definitions of this entity that are 9135 // visible, so complete the redeclaration chain now and ask again. 9136 if (auto *Source = Context.getExternalSource()) { 9137 Source->CompleteRedeclChain(D); 9138 return DefinitionIsAcceptable(); 9139 } 9140 9141 return false; 9142 } 9143 9144 /// Determine whether there is any declaration of \p D that was ever a 9145 /// definition (perhaps before module merging) and is currently visible. 9146 /// \param D The definition of the entity. 9147 /// \param Suggested Filled in with the declaration that should be made visible 9148 /// in order to provide a definition of this entity. 9149 /// \param OnlyNeedComplete If \c true, we only need the type to be complete, 9150 /// not defined. This only matters for enums with a fixed underlying 9151 /// type, since in all other cases, a type is complete if and only if it 9152 /// is defined. 9153 bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, 9154 bool OnlyNeedComplete) { 9155 return hasAcceptableDefinition(D, Suggested, Sema::AcceptableKind::Visible, 9156 OnlyNeedComplete); 9157 } 9158 9159 /// Determine whether there is any declaration of \p D that was ever a 9160 /// definition (perhaps before module merging) and is currently 9161 /// reachable. 9162 /// \param D The definition of the entity. 9163 /// \param Suggested Filled in with the declaration that should be made 9164 /// reachable 9165 /// in order to provide a definition of this entity. 9166 /// \param OnlyNeedComplete If \c true, we only need the type to be complete, 9167 /// not defined. This only matters for enums with a fixed underlying 9168 /// type, since in all other cases, a type is complete if and only if it 9169 /// is defined. 9170 bool Sema::hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested, 9171 bool OnlyNeedComplete) { 9172 return hasAcceptableDefinition(D, Suggested, Sema::AcceptableKind::Reachable, 9173 OnlyNeedComplete); 9174 } 9175 9176 /// Locks in the inheritance model for the given class and all of its bases. 9177 static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) { 9178 RD = RD->getMostRecentNonInjectedDecl(); 9179 if (!RD->hasAttr<MSInheritanceAttr>()) { 9180 MSInheritanceModel IM; 9181 bool BestCase = false; 9182 switch (S.MSPointerToMemberRepresentationMethod) { 9183 case LangOptions::PPTMK_BestCase: 9184 BestCase = true; 9185 IM = RD->calculateInheritanceModel(); 9186 break; 9187 case LangOptions::PPTMK_FullGeneralitySingleInheritance: 9188 IM = MSInheritanceModel::Single; 9189 break; 9190 case LangOptions::PPTMK_FullGeneralityMultipleInheritance: 9191 IM = MSInheritanceModel::Multiple; 9192 break; 9193 case LangOptions::PPTMK_FullGeneralityVirtualInheritance: 9194 IM = MSInheritanceModel::Unspecified; 9195 break; 9196 } 9197 9198 SourceRange Loc = S.ImplicitMSInheritanceAttrLoc.isValid() 9199 ? S.ImplicitMSInheritanceAttrLoc 9200 : RD->getSourceRange(); 9201 RD->addAttr(MSInheritanceAttr::CreateImplicit( 9202 S.getASTContext(), BestCase, Loc, MSInheritanceAttr::Spelling(IM))); 9203 S.Consumer.AssignInheritanceModel(RD); 9204 } 9205 } 9206 9207 bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T, 9208 CompleteTypeKind Kind, 9209 TypeDiagnoser *Diagnoser) { 9210 // FIXME: Add this assertion to make sure we always get instantiation points. 9211 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType"); 9212 // FIXME: Add this assertion to help us flush out problems with 9213 // checking for dependent types and type-dependent expressions. 9214 // 9215 // assert(!T->isDependentType() && 9216 // "Can't ask whether a dependent type is complete"); 9217 9218 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) { 9219 if (!MPTy->getClass()->isDependentType()) { 9220 if (getLangOpts().CompleteMemberPointers && 9221 !MPTy->getClass()->getAsCXXRecordDecl()->isBeingDefined() && 9222 RequireCompleteType(Loc, QualType(MPTy->getClass(), 0), Kind, 9223 diag::err_memptr_incomplete)) 9224 return true; 9225 9226 // We lock in the inheritance model once somebody has asked us to ensure 9227 // that a pointer-to-member type is complete. 9228 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 9229 (void)isCompleteType(Loc, QualType(MPTy->getClass(), 0)); 9230 assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl()); 9231 } 9232 } 9233 } 9234 9235 NamedDecl *Def = nullptr; 9236 bool AcceptSizeless = (Kind == CompleteTypeKind::AcceptSizeless); 9237 bool Incomplete = (T->isIncompleteType(&Def) || 9238 (!AcceptSizeless && T->isSizelessBuiltinType())); 9239 9240 // Check that any necessary explicit specializations are visible. For an 9241 // enum, we just need the declaration, so don't check this. 9242 if (Def && !isa<EnumDecl>(Def)) 9243 checkSpecializationReachability(Loc, Def); 9244 9245 // If we have a complete type, we're done. 9246 if (!Incomplete) { 9247 NamedDecl *Suggested = nullptr; 9248 if (Def && 9249 !hasReachableDefinition(Def, &Suggested, /*OnlyNeedComplete=*/true)) { 9250 // If the user is going to see an error here, recover by making the 9251 // definition visible. 9252 bool TreatAsComplete = Diagnoser && !isSFINAEContext(); 9253 if (Diagnoser && Suggested) 9254 diagnoseMissingImport(Loc, Suggested, MissingImportKind::Definition, 9255 /*Recover*/ TreatAsComplete); 9256 return !TreatAsComplete; 9257 } else if (Def && !TemplateInstCallbacks.empty()) { 9258 CodeSynthesisContext TempInst; 9259 TempInst.Kind = CodeSynthesisContext::Memoization; 9260 TempInst.Template = Def; 9261 TempInst.Entity = Def; 9262 TempInst.PointOfInstantiation = Loc; 9263 atTemplateBegin(TemplateInstCallbacks, *this, TempInst); 9264 atTemplateEnd(TemplateInstCallbacks, *this, TempInst); 9265 } 9266 9267 return false; 9268 } 9269 9270 TagDecl *Tag = dyn_cast_or_null<TagDecl>(Def); 9271 ObjCInterfaceDecl *IFace = dyn_cast_or_null<ObjCInterfaceDecl>(Def); 9272 9273 // Give the external source a chance to provide a definition of the type. 9274 // This is kept separate from completing the redeclaration chain so that 9275 // external sources such as LLDB can avoid synthesizing a type definition 9276 // unless it's actually needed. 9277 if (Tag || IFace) { 9278 // Avoid diagnosing invalid decls as incomplete. 9279 if (Def->isInvalidDecl()) 9280 return true; 9281 9282 // Give the external AST source a chance to complete the type. 9283 if (auto *Source = Context.getExternalSource()) { 9284 if (Tag && Tag->hasExternalLexicalStorage()) 9285 Source->CompleteType(Tag); 9286 if (IFace && IFace->hasExternalLexicalStorage()) 9287 Source->CompleteType(IFace); 9288 // If the external source completed the type, go through the motions 9289 // again to ensure we're allowed to use the completed type. 9290 if (!T->isIncompleteType()) 9291 return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser); 9292 } 9293 } 9294 9295 // If we have a class template specialization or a class member of a 9296 // class template specialization, or an array with known size of such, 9297 // try to instantiate it. 9298 if (auto *RD = dyn_cast_or_null<CXXRecordDecl>(Tag)) { 9299 bool Instantiated = false; 9300 bool Diagnosed = false; 9301 if (RD->isDependentContext()) { 9302 // Don't try to instantiate a dependent class (eg, a member template of 9303 // an instantiated class template specialization). 9304 // FIXME: Can this ever happen? 9305 } else if (auto *ClassTemplateSpec = 9306 dyn_cast<ClassTemplateSpecializationDecl>(RD)) { 9307 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) { 9308 runWithSufficientStackSpace(Loc, [&] { 9309 Diagnosed = InstantiateClassTemplateSpecialization( 9310 Loc, ClassTemplateSpec, TSK_ImplicitInstantiation, 9311 /*Complain=*/Diagnoser); 9312 }); 9313 Instantiated = true; 9314 } 9315 } else { 9316 CXXRecordDecl *Pattern = RD->getInstantiatedFromMemberClass(); 9317 if (!RD->isBeingDefined() && Pattern) { 9318 MemberSpecializationInfo *MSI = RD->getMemberSpecializationInfo(); 9319 assert(MSI && "Missing member specialization information?"); 9320 // This record was instantiated from a class within a template. 9321 if (MSI->getTemplateSpecializationKind() != 9322 TSK_ExplicitSpecialization) { 9323 runWithSufficientStackSpace(Loc, [&] { 9324 Diagnosed = InstantiateClass(Loc, RD, Pattern, 9325 getTemplateInstantiationArgs(RD), 9326 TSK_ImplicitInstantiation, 9327 /*Complain=*/Diagnoser); 9328 }); 9329 Instantiated = true; 9330 } 9331 } 9332 } 9333 9334 if (Instantiated) { 9335 // Instantiate* might have already complained that the template is not 9336 // defined, if we asked it to. 9337 if (Diagnoser && Diagnosed) 9338 return true; 9339 // If we instantiated a definition, check that it's usable, even if 9340 // instantiation produced an error, so that repeated calls to this 9341 // function give consistent answers. 9342 if (!T->isIncompleteType()) 9343 return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser); 9344 } 9345 } 9346 9347 // FIXME: If we didn't instantiate a definition because of an explicit 9348 // specialization declaration, check that it's visible. 9349 9350 if (!Diagnoser) 9351 return true; 9352 9353 Diagnoser->diagnose(*this, Loc, T); 9354 9355 // If the type was a forward declaration of a class/struct/union 9356 // type, produce a note. 9357 if (Tag && !Tag->isInvalidDecl() && !Tag->getLocation().isInvalid()) 9358 Diag(Tag->getLocation(), 9359 Tag->isBeingDefined() ? diag::note_type_being_defined 9360 : diag::note_forward_declaration) 9361 << Context.getTagDeclType(Tag); 9362 9363 // If the Objective-C class was a forward declaration, produce a note. 9364 if (IFace && !IFace->isInvalidDecl() && !IFace->getLocation().isInvalid()) 9365 Diag(IFace->getLocation(), diag::note_forward_class); 9366 9367 // If we have external information that we can use to suggest a fix, 9368 // produce a note. 9369 if (ExternalSource) 9370 ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T); 9371 9372 return true; 9373 } 9374 9375 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, 9376 CompleteTypeKind Kind, unsigned DiagID) { 9377 BoundTypeDiagnoser<> Diagnoser(DiagID); 9378 return RequireCompleteType(Loc, T, Kind, Diagnoser); 9379 } 9380 9381 /// Get diagnostic %select index for tag kind for 9382 /// literal type diagnostic message. 9383 /// WARNING: Indexes apply to particular diagnostics only! 9384 /// 9385 /// \returns diagnostic %select index. 9386 static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) { 9387 switch (Tag) { 9388 case TagTypeKind::Struct: 9389 return 0; 9390 case TagTypeKind::Interface: 9391 return 1; 9392 case TagTypeKind::Class: 9393 return 2; 9394 default: llvm_unreachable("Invalid tag kind for literal type diagnostic!"); 9395 } 9396 } 9397 9398 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, 9399 TypeDiagnoser &Diagnoser) { 9400 assert(!T->isDependentType() && "type should not be dependent"); 9401 9402 QualType ElemType = Context.getBaseElementType(T); 9403 if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) && 9404 T->isLiteralType(Context)) 9405 return false; 9406 9407 Diagnoser.diagnose(*this, Loc, T); 9408 9409 if (T->isVariableArrayType()) 9410 return true; 9411 9412 const RecordType *RT = ElemType->getAs<RecordType>(); 9413 if (!RT) 9414 return true; 9415 9416 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 9417 9418 // A partially-defined class type can't be a literal type, because a literal 9419 // class type must have a trivial destructor (which can't be checked until 9420 // the class definition is complete). 9421 if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T)) 9422 return true; 9423 9424 // [expr.prim.lambda]p3: 9425 // This class type is [not] a literal type. 9426 if (RD->isLambda() && !getLangOpts().CPlusPlus17) { 9427 Diag(RD->getLocation(), diag::note_non_literal_lambda); 9428 return true; 9429 } 9430 9431 // If the class has virtual base classes, then it's not an aggregate, and 9432 // cannot have any constexpr constructors or a trivial default constructor, 9433 // so is non-literal. This is better to diagnose than the resulting absence 9434 // of constexpr constructors. 9435 if (RD->getNumVBases()) { 9436 Diag(RD->getLocation(), diag::note_non_literal_virtual_base) 9437 << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 9438 for (const auto &I : RD->vbases()) 9439 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here) 9440 << I.getSourceRange(); 9441 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() && 9442 !RD->hasTrivialDefaultConstructor()) { 9443 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD; 9444 } else if (RD->hasNonLiteralTypeFieldsOrBases()) { 9445 for (const auto &I : RD->bases()) { 9446 if (!I.getType()->isLiteralType(Context)) { 9447 Diag(I.getBeginLoc(), diag::note_non_literal_base_class) 9448 << RD << I.getType() << I.getSourceRange(); 9449 return true; 9450 } 9451 } 9452 for (const auto *I : RD->fields()) { 9453 if (!I->getType()->isLiteralType(Context) || 9454 I->getType().isVolatileQualified()) { 9455 Diag(I->getLocation(), diag::note_non_literal_field) 9456 << RD << I << I->getType() 9457 << I->getType().isVolatileQualified(); 9458 return true; 9459 } 9460 } 9461 } else if (getLangOpts().CPlusPlus20 ? !RD->hasConstexprDestructor() 9462 : !RD->hasTrivialDestructor()) { 9463 // All fields and bases are of literal types, so have trivial or constexpr 9464 // destructors. If this class's destructor is non-trivial / non-constexpr, 9465 // it must be user-declared. 9466 CXXDestructorDecl *Dtor = RD->getDestructor(); 9467 assert(Dtor && "class has literal fields and bases but no dtor?"); 9468 if (!Dtor) 9469 return true; 9470 9471 if (getLangOpts().CPlusPlus20) { 9472 Diag(Dtor->getLocation(), diag::note_non_literal_non_constexpr_dtor) 9473 << RD; 9474 } else { 9475 Diag(Dtor->getLocation(), Dtor->isUserProvided() 9476 ? diag::note_non_literal_user_provided_dtor 9477 : diag::note_non_literal_nontrivial_dtor) 9478 << RD; 9479 if (!Dtor->isUserProvided()) 9480 SpecialMemberIsTrivial(Dtor, CXXSpecialMemberKind::Destructor, 9481 TAH_IgnoreTrivialABI, 9482 /*Diagnose*/ true); 9483 } 9484 } 9485 9486 return true; 9487 } 9488 9489 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) { 9490 BoundTypeDiagnoser<> Diagnoser(DiagID); 9491 return RequireLiteralType(Loc, T, Diagnoser); 9492 } 9493 9494 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword, 9495 const CXXScopeSpec &SS, QualType T, 9496 TagDecl *OwnedTagDecl) { 9497 if (T.isNull()) 9498 return T; 9499 return Context.getElaboratedType( 9500 Keyword, SS.isValid() ? SS.getScopeRep() : nullptr, T, OwnedTagDecl); 9501 } 9502 9503 QualType Sema::BuildTypeofExprType(Expr *E, TypeOfKind Kind) { 9504 assert(!E->hasPlaceholderType() && "unexpected placeholder"); 9505 9506 if (!getLangOpts().CPlusPlus && E->refersToBitField()) 9507 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 9508 << (Kind == TypeOfKind::Unqualified ? 3 : 2); 9509 9510 if (!E->isTypeDependent()) { 9511 QualType T = E->getType(); 9512 if (const TagType *TT = T->getAs<TagType>()) 9513 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc()); 9514 } 9515 return Context.getTypeOfExprType(E, Kind); 9516 } 9517 9518 static void 9519 BuildTypeCoupledDecls(Expr *E, 9520 llvm::SmallVectorImpl<TypeCoupledDeclRefInfo> &Decls) { 9521 // Currently, 'counted_by' only allows direct DeclRefExpr to FieldDecl. 9522 auto *CountDecl = cast<DeclRefExpr>(E)->getDecl(); 9523 Decls.push_back(TypeCoupledDeclRefInfo(CountDecl, /*IsDref*/ false)); 9524 } 9525 9526 QualType Sema::BuildCountAttributedArrayOrPointerType(QualType WrappedTy, 9527 Expr *CountExpr, 9528 bool CountInBytes, 9529 bool OrNull) { 9530 assert(WrappedTy->isIncompleteArrayType() || WrappedTy->isPointerType()); 9531 9532 llvm::SmallVector<TypeCoupledDeclRefInfo, 1> Decls; 9533 BuildTypeCoupledDecls(CountExpr, Decls); 9534 /// When the resulting expression is invalid, we still create the AST using 9535 /// the original count expression for the sake of AST dump. 9536 return Context.getCountAttributedType(WrappedTy, CountExpr, CountInBytes, 9537 OrNull, Decls); 9538 } 9539 9540 /// getDecltypeForExpr - Given an expr, will return the decltype for 9541 /// that expression, according to the rules in C++11 9542 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18. 9543 QualType Sema::getDecltypeForExpr(Expr *E) { 9544 9545 Expr *IDExpr = E; 9546 if (auto *ImplCastExpr = dyn_cast<ImplicitCastExpr>(E)) 9547 IDExpr = ImplCastExpr->getSubExpr(); 9548 9549 if (auto *PackExpr = dyn_cast<PackIndexingExpr>(E)) { 9550 if (E->isInstantiationDependent()) 9551 IDExpr = PackExpr->getPackIdExpression(); 9552 else 9553 IDExpr = PackExpr->getSelectedExpr(); 9554 } 9555 9556 if (E->isTypeDependent()) 9557 return Context.DependentTy; 9558 9559 // C++11 [dcl.type.simple]p4: 9560 // The type denoted by decltype(e) is defined as follows: 9561 9562 // C++20: 9563 // - if E is an unparenthesized id-expression naming a non-type 9564 // template-parameter (13.2), decltype(E) is the type of the 9565 // template-parameter after performing any necessary type deduction 9566 // Note that this does not pick up the implicit 'const' for a template 9567 // parameter object. This rule makes no difference before C++20 so we apply 9568 // it unconditionally. 9569 if (const auto *SNTTPE = dyn_cast<SubstNonTypeTemplateParmExpr>(IDExpr)) 9570 return SNTTPE->getParameterType(Context); 9571 9572 // - if e is an unparenthesized id-expression or an unparenthesized class 9573 // member access (5.2.5), decltype(e) is the type of the entity named 9574 // by e. If there is no such entity, or if e names a set of overloaded 9575 // functions, the program is ill-formed; 9576 // 9577 // We apply the same rules for Objective-C ivar and property references. 9578 if (const auto *DRE = dyn_cast<DeclRefExpr>(IDExpr)) { 9579 const ValueDecl *VD = DRE->getDecl(); 9580 QualType T = VD->getType(); 9581 return isa<TemplateParamObjectDecl>(VD) ? T.getUnqualifiedType() : T; 9582 } 9583 if (const auto *ME = dyn_cast<MemberExpr>(IDExpr)) { 9584 if (const auto *VD = ME->getMemberDecl()) 9585 if (isa<FieldDecl>(VD) || isa<VarDecl>(VD)) 9586 return VD->getType(); 9587 } else if (const auto *IR = dyn_cast<ObjCIvarRefExpr>(IDExpr)) { 9588 return IR->getDecl()->getType(); 9589 } else if (const auto *PR = dyn_cast<ObjCPropertyRefExpr>(IDExpr)) { 9590 if (PR->isExplicitProperty()) 9591 return PR->getExplicitProperty()->getType(); 9592 } else if (const auto *PE = dyn_cast<PredefinedExpr>(IDExpr)) { 9593 return PE->getType(); 9594 } 9595 9596 // C++11 [expr.lambda.prim]p18: 9597 // Every occurrence of decltype((x)) where x is a possibly 9598 // parenthesized id-expression that names an entity of automatic 9599 // storage duration is treated as if x were transformed into an 9600 // access to a corresponding data member of the closure type that 9601 // would have been declared if x were an odr-use of the denoted 9602 // entity. 9603 if (getCurLambda() && isa<ParenExpr>(IDExpr)) { 9604 if (auto *DRE = dyn_cast<DeclRefExpr>(IDExpr->IgnoreParens())) { 9605 if (auto *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 9606 QualType T = getCapturedDeclRefType(Var, DRE->getLocation()); 9607 if (!T.isNull()) 9608 return Context.getLValueReferenceType(T); 9609 } 9610 } 9611 } 9612 9613 return Context.getReferenceQualifiedType(E); 9614 } 9615 9616 QualType Sema::BuildDecltypeType(Expr *E, bool AsUnevaluated) { 9617 assert(!E->hasPlaceholderType() && "unexpected placeholder"); 9618 9619 if (AsUnevaluated && CodeSynthesisContexts.empty() && 9620 !E->isInstantiationDependent() && E->HasSideEffects(Context, false)) { 9621 // The expression operand for decltype is in an unevaluated expression 9622 // context, so side effects could result in unintended consequences. 9623 // Exclude instantiation-dependent expressions, because 'decltype' is often 9624 // used to build SFINAE gadgets. 9625 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 9626 } 9627 return Context.getDecltypeType(E, getDecltypeForExpr(E)); 9628 } 9629 9630 QualType Sema::ActOnPackIndexingType(QualType Pattern, Expr *IndexExpr, 9631 SourceLocation Loc, 9632 SourceLocation EllipsisLoc) { 9633 if (!IndexExpr) 9634 return QualType(); 9635 9636 // Diagnose unexpanded packs but continue to improve recovery. 9637 if (!Pattern->containsUnexpandedParameterPack()) 9638 Diag(Loc, diag::err_expected_name_of_pack) << Pattern; 9639 9640 QualType Type = BuildPackIndexingType(Pattern, IndexExpr, Loc, EllipsisLoc); 9641 9642 if (!Type.isNull()) 9643 Diag(Loc, getLangOpts().CPlusPlus26 ? diag::warn_cxx23_pack_indexing 9644 : diag::ext_pack_indexing); 9645 return Type; 9646 } 9647 9648 QualType Sema::BuildPackIndexingType(QualType Pattern, Expr *IndexExpr, 9649 SourceLocation Loc, 9650 SourceLocation EllipsisLoc, 9651 bool FullySubstituted, 9652 ArrayRef<QualType> Expansions) { 9653 9654 std::optional<int64_t> Index; 9655 if (FullySubstituted && !IndexExpr->isValueDependent() && 9656 !IndexExpr->isTypeDependent()) { 9657 llvm::APSInt Value(Context.getIntWidth(Context.getSizeType())); 9658 ExprResult Res = CheckConvertedConstantExpression( 9659 IndexExpr, Context.getSizeType(), Value, CCEK_ArrayBound); 9660 if (!Res.isUsable()) 9661 return QualType(); 9662 Index = Value.getExtValue(); 9663 IndexExpr = Res.get(); 9664 } 9665 9666 if (FullySubstituted && Index) { 9667 if (*Index < 0 || *Index >= int64_t(Expansions.size())) { 9668 Diag(IndexExpr->getBeginLoc(), diag::err_pack_index_out_of_bound) 9669 << *Index << Pattern << Expansions.size(); 9670 return QualType(); 9671 } 9672 } 9673 9674 return Context.getPackIndexingType(Pattern, IndexExpr, FullySubstituted, 9675 Expansions, Index.value_or(-1)); 9676 } 9677 9678 static QualType GetEnumUnderlyingType(Sema &S, QualType BaseType, 9679 SourceLocation Loc) { 9680 assert(BaseType->isEnumeralType()); 9681 EnumDecl *ED = BaseType->castAs<EnumType>()->getDecl(); 9682 assert(ED && "EnumType has no EnumDecl"); 9683 9684 S.DiagnoseUseOfDecl(ED, Loc); 9685 9686 QualType Underlying = ED->getIntegerType(); 9687 assert(!Underlying.isNull()); 9688 9689 return Underlying; 9690 } 9691 9692 QualType Sema::BuiltinEnumUnderlyingType(QualType BaseType, 9693 SourceLocation Loc) { 9694 if (!BaseType->isEnumeralType()) { 9695 Diag(Loc, diag::err_only_enums_have_underlying_types); 9696 return QualType(); 9697 } 9698 9699 // The enum could be incomplete if we're parsing its definition or 9700 // recovering from an error. 9701 NamedDecl *FwdDecl = nullptr; 9702 if (BaseType->isIncompleteType(&FwdDecl)) { 9703 Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType; 9704 Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl; 9705 return QualType(); 9706 } 9707 9708 return GetEnumUnderlyingType(*this, BaseType, Loc); 9709 } 9710 9711 QualType Sema::BuiltinAddPointer(QualType BaseType, SourceLocation Loc) { 9712 QualType Pointer = BaseType.isReferenceable() || BaseType->isVoidType() 9713 ? BuildPointerType(BaseType.getNonReferenceType(), Loc, 9714 DeclarationName()) 9715 : BaseType; 9716 9717 return Pointer.isNull() ? QualType() : Pointer; 9718 } 9719 9720 QualType Sema::BuiltinRemovePointer(QualType BaseType, SourceLocation Loc) { 9721 // We don't want block pointers or ObjectiveC's id type. 9722 if (!BaseType->isAnyPointerType() || BaseType->isObjCIdType()) 9723 return BaseType; 9724 9725 return BaseType->getPointeeType(); 9726 } 9727 9728 QualType Sema::BuiltinDecay(QualType BaseType, SourceLocation Loc) { 9729 QualType Underlying = BaseType.getNonReferenceType(); 9730 if (Underlying->isArrayType()) 9731 return Context.getDecayedType(Underlying); 9732 9733 if (Underlying->isFunctionType()) 9734 return BuiltinAddPointer(BaseType, Loc); 9735 9736 SplitQualType Split = Underlying.getSplitUnqualifiedType(); 9737 // std::decay is supposed to produce 'std::remove_cv', but since 'restrict' is 9738 // in the same group of qualifiers as 'const' and 'volatile', we're extending 9739 // '__decay(T)' so that it removes all qualifiers. 9740 Split.Quals.removeCVRQualifiers(); 9741 return Context.getQualifiedType(Split); 9742 } 9743 9744 QualType Sema::BuiltinAddReference(QualType BaseType, UTTKind UKind, 9745 SourceLocation Loc) { 9746 assert(LangOpts.CPlusPlus); 9747 QualType Reference = 9748 BaseType.isReferenceable() 9749 ? BuildReferenceType(BaseType, 9750 UKind == UnaryTransformType::AddLvalueReference, 9751 Loc, DeclarationName()) 9752 : BaseType; 9753 return Reference.isNull() ? QualType() : Reference; 9754 } 9755 9756 QualType Sema::BuiltinRemoveExtent(QualType BaseType, UTTKind UKind, 9757 SourceLocation Loc) { 9758 if (UKind == UnaryTransformType::RemoveAllExtents) 9759 return Context.getBaseElementType(BaseType); 9760 9761 if (const auto *AT = Context.getAsArrayType(BaseType)) 9762 return AT->getElementType(); 9763 9764 return BaseType; 9765 } 9766 9767 QualType Sema::BuiltinRemoveReference(QualType BaseType, UTTKind UKind, 9768 SourceLocation Loc) { 9769 assert(LangOpts.CPlusPlus); 9770 QualType T = BaseType.getNonReferenceType(); 9771 if (UKind == UTTKind::RemoveCVRef && 9772 (T.isConstQualified() || T.isVolatileQualified())) { 9773 Qualifiers Quals; 9774 QualType Unqual = Context.getUnqualifiedArrayType(T, Quals); 9775 Quals.removeConst(); 9776 Quals.removeVolatile(); 9777 T = Context.getQualifiedType(Unqual, Quals); 9778 } 9779 return T; 9780 } 9781 9782 QualType Sema::BuiltinChangeCVRQualifiers(QualType BaseType, UTTKind UKind, 9783 SourceLocation Loc) { 9784 if ((BaseType->isReferenceType() && UKind != UTTKind::RemoveRestrict) || 9785 BaseType->isFunctionType()) 9786 return BaseType; 9787 9788 Qualifiers Quals; 9789 QualType Unqual = Context.getUnqualifiedArrayType(BaseType, Quals); 9790 9791 if (UKind == UTTKind::RemoveConst || UKind == UTTKind::RemoveCV) 9792 Quals.removeConst(); 9793 if (UKind == UTTKind::RemoveVolatile || UKind == UTTKind::RemoveCV) 9794 Quals.removeVolatile(); 9795 if (UKind == UTTKind::RemoveRestrict) 9796 Quals.removeRestrict(); 9797 9798 return Context.getQualifiedType(Unqual, Quals); 9799 } 9800 9801 static QualType ChangeIntegralSignedness(Sema &S, QualType BaseType, 9802 bool IsMakeSigned, 9803 SourceLocation Loc) { 9804 if (BaseType->isEnumeralType()) { 9805 QualType Underlying = GetEnumUnderlyingType(S, BaseType, Loc); 9806 if (auto *BitInt = dyn_cast<BitIntType>(Underlying)) { 9807 unsigned int Bits = BitInt->getNumBits(); 9808 if (Bits > 1) 9809 return S.Context.getBitIntType(!IsMakeSigned, Bits); 9810 9811 S.Diag(Loc, diag::err_make_signed_integral_only) 9812 << IsMakeSigned << /*_BitInt(1)*/ true << BaseType << 1 << Underlying; 9813 return QualType(); 9814 } 9815 if (Underlying->isBooleanType()) { 9816 S.Diag(Loc, diag::err_make_signed_integral_only) 9817 << IsMakeSigned << /*_BitInt(1)*/ false << BaseType << 1 9818 << Underlying; 9819 return QualType(); 9820 } 9821 } 9822 9823 bool Int128Unsupported = !S.Context.getTargetInfo().hasInt128Type(); 9824 std::array<CanQualType *, 6> AllSignedIntegers = { 9825 &S.Context.SignedCharTy, &S.Context.ShortTy, &S.Context.IntTy, 9826 &S.Context.LongTy, &S.Context.LongLongTy, &S.Context.Int128Ty}; 9827 ArrayRef<CanQualType *> AvailableSignedIntegers( 9828 AllSignedIntegers.data(), AllSignedIntegers.size() - Int128Unsupported); 9829 std::array<CanQualType *, 6> AllUnsignedIntegers = { 9830 &S.Context.UnsignedCharTy, &S.Context.UnsignedShortTy, 9831 &S.Context.UnsignedIntTy, &S.Context.UnsignedLongTy, 9832 &S.Context.UnsignedLongLongTy, &S.Context.UnsignedInt128Ty}; 9833 ArrayRef<CanQualType *> AvailableUnsignedIntegers(AllUnsignedIntegers.data(), 9834 AllUnsignedIntegers.size() - 9835 Int128Unsupported); 9836 ArrayRef<CanQualType *> *Consider = 9837 IsMakeSigned ? &AvailableSignedIntegers : &AvailableUnsignedIntegers; 9838 9839 uint64_t BaseSize = S.Context.getTypeSize(BaseType); 9840 auto *Result = 9841 llvm::find_if(*Consider, [&S, BaseSize](const CanQual<Type> *T) { 9842 return BaseSize == S.Context.getTypeSize(T->getTypePtr()); 9843 }); 9844 9845 assert(Result != Consider->end()); 9846 return QualType((*Result)->getTypePtr(), 0); 9847 } 9848 9849 QualType Sema::BuiltinChangeSignedness(QualType BaseType, UTTKind UKind, 9850 SourceLocation Loc) { 9851 bool IsMakeSigned = UKind == UnaryTransformType::MakeSigned; 9852 if ((!BaseType->isIntegerType() && !BaseType->isEnumeralType()) || 9853 BaseType->isBooleanType() || 9854 (BaseType->isBitIntType() && 9855 BaseType->getAs<BitIntType>()->getNumBits() < 2)) { 9856 Diag(Loc, diag::err_make_signed_integral_only) 9857 << IsMakeSigned << BaseType->isBitIntType() << BaseType << 0; 9858 return QualType(); 9859 } 9860 9861 bool IsNonIntIntegral = 9862 BaseType->isChar16Type() || BaseType->isChar32Type() || 9863 BaseType->isWideCharType() || BaseType->isEnumeralType(); 9864 9865 QualType Underlying = 9866 IsNonIntIntegral 9867 ? ChangeIntegralSignedness(*this, BaseType, IsMakeSigned, Loc) 9868 : IsMakeSigned ? Context.getCorrespondingSignedType(BaseType) 9869 : Context.getCorrespondingUnsignedType(BaseType); 9870 if (Underlying.isNull()) 9871 return Underlying; 9872 return Context.getQualifiedType(Underlying, BaseType.getQualifiers()); 9873 } 9874 9875 QualType Sema::BuildUnaryTransformType(QualType BaseType, UTTKind UKind, 9876 SourceLocation Loc) { 9877 if (BaseType->isDependentType()) 9878 return Context.getUnaryTransformType(BaseType, BaseType, UKind); 9879 QualType Result; 9880 switch (UKind) { 9881 case UnaryTransformType::EnumUnderlyingType: { 9882 Result = BuiltinEnumUnderlyingType(BaseType, Loc); 9883 break; 9884 } 9885 case UnaryTransformType::AddPointer: { 9886 Result = BuiltinAddPointer(BaseType, Loc); 9887 break; 9888 } 9889 case UnaryTransformType::RemovePointer: { 9890 Result = BuiltinRemovePointer(BaseType, Loc); 9891 break; 9892 } 9893 case UnaryTransformType::Decay: { 9894 Result = BuiltinDecay(BaseType, Loc); 9895 break; 9896 } 9897 case UnaryTransformType::AddLvalueReference: 9898 case UnaryTransformType::AddRvalueReference: { 9899 Result = BuiltinAddReference(BaseType, UKind, Loc); 9900 break; 9901 } 9902 case UnaryTransformType::RemoveAllExtents: 9903 case UnaryTransformType::RemoveExtent: { 9904 Result = BuiltinRemoveExtent(BaseType, UKind, Loc); 9905 break; 9906 } 9907 case UnaryTransformType::RemoveCVRef: 9908 case UnaryTransformType::RemoveReference: { 9909 Result = BuiltinRemoveReference(BaseType, UKind, Loc); 9910 break; 9911 } 9912 case UnaryTransformType::RemoveConst: 9913 case UnaryTransformType::RemoveCV: 9914 case UnaryTransformType::RemoveRestrict: 9915 case UnaryTransformType::RemoveVolatile: { 9916 Result = BuiltinChangeCVRQualifiers(BaseType, UKind, Loc); 9917 break; 9918 } 9919 case UnaryTransformType::MakeSigned: 9920 case UnaryTransformType::MakeUnsigned: { 9921 Result = BuiltinChangeSignedness(BaseType, UKind, Loc); 9922 break; 9923 } 9924 } 9925 9926 return !Result.isNull() 9927 ? Context.getUnaryTransformType(BaseType, Result, UKind) 9928 : Result; 9929 } 9930 9931 QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) { 9932 if (!isDependentOrGNUAutoType(T)) { 9933 // FIXME: It isn't entirely clear whether incomplete atomic types 9934 // are allowed or not; for simplicity, ban them for the moment. 9935 if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0)) 9936 return QualType(); 9937 9938 int DisallowedKind = -1; 9939 if (T->isArrayType()) 9940 DisallowedKind = 1; 9941 else if (T->isFunctionType()) 9942 DisallowedKind = 2; 9943 else if (T->isReferenceType()) 9944 DisallowedKind = 3; 9945 else if (T->isAtomicType()) 9946 DisallowedKind = 4; 9947 else if (T.hasQualifiers()) 9948 DisallowedKind = 5; 9949 else if (T->isSizelessType()) 9950 DisallowedKind = 6; 9951 else if (!T.isTriviallyCopyableType(Context) && getLangOpts().CPlusPlus) 9952 // Some other non-trivially-copyable type (probably a C++ class) 9953 DisallowedKind = 7; 9954 else if (T->isBitIntType()) 9955 DisallowedKind = 8; 9956 else if (getLangOpts().C23 && T->isUndeducedAutoType()) 9957 // _Atomic auto is prohibited in C23 9958 DisallowedKind = 9; 9959 9960 if (DisallowedKind != -1) { 9961 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T; 9962 return QualType(); 9963 } 9964 9965 // FIXME: Do we need any handling for ARC here? 9966 } 9967 9968 // Build the pointer type. 9969 return Context.getAtomicType(T); 9970 } 9971