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