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