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