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