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