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