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