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