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