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