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