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