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