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