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