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_MSABI: \ 125 case ParsedAttr::AT_SysVABI: \ 126 case ParsedAttr::AT_Pcs: \ 127 case ParsedAttr::AT_IntelOclBicc: \ 128 case ParsedAttr::AT_PreserveMost: \ 129 case ParsedAttr::AT_PreserveAll 130 131 // Function type attributes. 132 #define FUNCTION_TYPE_ATTRS_CASELIST \ 133 case ParsedAttr::AT_NSReturnsRetained: \ 134 case ParsedAttr::AT_NoReturn: \ 135 case ParsedAttr::AT_Regparm: \ 136 case ParsedAttr::AT_CmseNSCall: \ 137 case ParsedAttr::AT_AnyX86NoCallerSavedRegisters: \ 138 case ParsedAttr::AT_AnyX86NoCfCheck: \ 139 CALLING_CONV_ATTRS_CASELIST 140 141 // Microsoft-specific type qualifiers. 142 #define MS_TYPE_ATTRS_CASELIST \ 143 case ParsedAttr::AT_Ptr32: \ 144 case ParsedAttr::AT_Ptr64: \ 145 case ParsedAttr::AT_SPtr: \ 146 case ParsedAttr::AT_UPtr 147 148 // Nullability qualifiers. 149 #define NULLABILITY_TYPE_ATTRS_CASELIST \ 150 case ParsedAttr::AT_TypeNonNull: \ 151 case ParsedAttr::AT_TypeNullable: \ 152 case ParsedAttr::AT_TypeNullableResult: \ 153 case ParsedAttr::AT_TypeNullUnspecified 154 155 namespace { 156 /// An object which stores processing state for the entire 157 /// GetTypeForDeclarator process. 158 class TypeProcessingState { 159 Sema &sema; 160 161 /// The declarator being processed. 162 Declarator &declarator; 163 164 /// The index of the declarator chunk we're currently processing. 165 /// May be the total number of valid chunks, indicating the 166 /// DeclSpec. 167 unsigned chunkIndex; 168 169 /// The original set of attributes on the DeclSpec. 170 SmallVector<ParsedAttr *, 2> savedAttrs; 171 172 /// A list of attributes to diagnose the uselessness of when the 173 /// processing is complete. 174 SmallVector<ParsedAttr *, 2> ignoredTypeAttrs; 175 176 /// Attributes corresponding to AttributedTypeLocs that we have not yet 177 /// populated. 178 // FIXME: The two-phase mechanism by which we construct Types and fill 179 // their TypeLocs makes it hard to correctly assign these. We keep the 180 // attributes in creation order as an attempt to make them line up 181 // properly. 182 using TypeAttrPair = std::pair<const AttributedType*, const Attr*>; 183 SmallVector<TypeAttrPair, 8> AttrsForTypes; 184 bool AttrsForTypesSorted = true; 185 186 /// MacroQualifiedTypes mapping to macro expansion locations that will be 187 /// stored in a MacroQualifiedTypeLoc. 188 llvm::DenseMap<const MacroQualifiedType *, SourceLocation> LocsForMacros; 189 190 /// Flag to indicate we parsed a noderef attribute. This is used for 191 /// validating that noderef was used on a pointer or array. 192 bool parsedNoDeref; 193 194 public: 195 TypeProcessingState(Sema &sema, Declarator &declarator) 196 : sema(sema), declarator(declarator), 197 chunkIndex(declarator.getNumTypeObjects()), parsedNoDeref(false) {} 198 199 Sema &getSema() const { 200 return sema; 201 } 202 203 Declarator &getDeclarator() const { 204 return declarator; 205 } 206 207 bool isProcessingDeclSpec() const { 208 return chunkIndex == declarator.getNumTypeObjects(); 209 } 210 211 unsigned getCurrentChunkIndex() const { 212 return chunkIndex; 213 } 214 215 void setCurrentChunkIndex(unsigned idx) { 216 assert(idx <= declarator.getNumTypeObjects()); 217 chunkIndex = idx; 218 } 219 220 ParsedAttributesView &getCurrentAttributes() const { 221 if (isProcessingDeclSpec()) 222 return getMutableDeclSpec().getAttributes(); 223 return declarator.getTypeObject(chunkIndex).getAttrs(); 224 } 225 226 /// Save the current set of attributes on the DeclSpec. 227 void saveDeclSpecAttrs() { 228 // Don't try to save them multiple times. 229 if (!savedAttrs.empty()) 230 return; 231 232 DeclSpec &spec = getMutableDeclSpec(); 233 llvm::append_range(savedAttrs, 234 llvm::make_pointer_range(spec.getAttributes())); 235 } 236 237 /// Record that we had nowhere to put the given type attribute. 238 /// We will diagnose such attributes later. 239 void addIgnoredTypeAttr(ParsedAttr &attr) { 240 ignoredTypeAttrs.push_back(&attr); 241 } 242 243 /// Diagnose all the ignored type attributes, given that the 244 /// declarator worked out to the given type. 245 void diagnoseIgnoredTypeAttrs(QualType type) const { 246 for (auto *Attr : ignoredTypeAttrs) 247 diagnoseBadTypeAttribute(getSema(), *Attr, type); 248 } 249 250 /// Get an attributed type for the given attribute, and remember the Attr 251 /// object so that we can attach it to the AttributedTypeLoc. 252 QualType getAttributedType(Attr *A, QualType ModifiedType, 253 QualType EquivType) { 254 QualType T = 255 sema.Context.getAttributedType(A->getKind(), ModifiedType, EquivType); 256 AttrsForTypes.push_back({cast<AttributedType>(T.getTypePtr()), A}); 257 AttrsForTypesSorted = false; 258 return T; 259 } 260 261 /// Get a BTFTagAttributed type for the btf_type_tag attribute. 262 QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr, 263 QualType WrappedType) { 264 return sema.Context.getBTFTagAttributedType(BTFAttr, WrappedType); 265 } 266 267 /// Completely replace the \c auto in \p TypeWithAuto by 268 /// \p Replacement. Also replace \p TypeWithAuto in \c TypeAttrPair if 269 /// necessary. 270 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement) { 271 QualType T = sema.ReplaceAutoType(TypeWithAuto, Replacement); 272 if (auto *AttrTy = TypeWithAuto->getAs<AttributedType>()) { 273 // Attributed type still should be an attributed type after replacement. 274 auto *NewAttrTy = cast<AttributedType>(T.getTypePtr()); 275 for (TypeAttrPair &A : AttrsForTypes) { 276 if (A.first == AttrTy) 277 A.first = NewAttrTy; 278 } 279 AttrsForTypesSorted = false; 280 } 281 return T; 282 } 283 284 /// Extract and remove the Attr* for a given attributed type. 285 const Attr *takeAttrForAttributedType(const AttributedType *AT) { 286 if (!AttrsForTypesSorted) { 287 llvm::stable_sort(AttrsForTypes, llvm::less_first()); 288 AttrsForTypesSorted = true; 289 } 290 291 // FIXME: This is quadratic if we have lots of reuses of the same 292 // attributed type. 293 for (auto It = std::partition_point( 294 AttrsForTypes.begin(), AttrsForTypes.end(), 295 [=](const TypeAttrPair &A) { return A.first < AT; }); 296 It != AttrsForTypes.end() && It->first == AT; ++It) { 297 if (It->second) { 298 const Attr *Result = It->second; 299 It->second = nullptr; 300 return Result; 301 } 302 } 303 304 llvm_unreachable("no Attr* for AttributedType*"); 305 } 306 307 SourceLocation 308 getExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT) const { 309 auto FoundLoc = LocsForMacros.find(MQT); 310 assert(FoundLoc != LocsForMacros.end() && 311 "Unable to find macro expansion location for MacroQualifedType"); 312 return FoundLoc->second; 313 } 314 315 void setExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT, 316 SourceLocation Loc) { 317 LocsForMacros[MQT] = Loc; 318 } 319 320 void setParsedNoDeref(bool parsed) { parsedNoDeref = parsed; } 321 322 bool didParseNoDeref() const { return parsedNoDeref; } 323 324 ~TypeProcessingState() { 325 if (savedAttrs.empty()) 326 return; 327 328 getMutableDeclSpec().getAttributes().clearListOnly(); 329 for (ParsedAttr *AL : savedAttrs) 330 getMutableDeclSpec().getAttributes().addAtEnd(AL); 331 } 332 333 private: 334 DeclSpec &getMutableDeclSpec() const { 335 return const_cast<DeclSpec&>(declarator.getDeclSpec()); 336 } 337 }; 338 } // end anonymous namespace 339 340 static void moveAttrFromListToList(ParsedAttr &attr, 341 ParsedAttributesView &fromList, 342 ParsedAttributesView &toList) { 343 fromList.remove(&attr); 344 toList.addAtEnd(&attr); 345 } 346 347 /// The location of a type attribute. 348 enum TypeAttrLocation { 349 /// The attribute is in the decl-specifier-seq. 350 TAL_DeclSpec, 351 /// The attribute is part of a DeclaratorChunk. 352 TAL_DeclChunk, 353 /// The attribute is immediately after the declaration's name. 354 TAL_DeclName 355 }; 356 357 static void processTypeAttrs(TypeProcessingState &state, QualType &type, 358 TypeAttrLocation TAL, 359 const ParsedAttributesView &attrs); 360 361 static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr, 362 QualType &type); 363 364 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state, 365 ParsedAttr &attr, QualType &type); 366 367 static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr, 368 QualType &type); 369 370 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state, 371 ParsedAttr &attr, QualType &type); 372 373 static bool handleObjCPointerTypeAttr(TypeProcessingState &state, 374 ParsedAttr &attr, QualType &type) { 375 if (attr.getKind() == ParsedAttr::AT_ObjCGC) 376 return handleObjCGCTypeAttr(state, attr, type); 377 assert(attr.getKind() == ParsedAttr::AT_ObjCOwnership); 378 return handleObjCOwnershipTypeAttr(state, attr, type); 379 } 380 381 /// Given the index of a declarator chunk, check whether that chunk 382 /// directly specifies the return type of a function and, if so, find 383 /// an appropriate place for it. 384 /// 385 /// \param i - a notional index which the search will start 386 /// immediately inside 387 /// 388 /// \param onlyBlockPointers Whether we should only look into block 389 /// pointer types (vs. all pointer types). 390 static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator, 391 unsigned i, 392 bool onlyBlockPointers) { 393 assert(i <= declarator.getNumTypeObjects()); 394 395 DeclaratorChunk *result = nullptr; 396 397 // First, look inwards past parens for a function declarator. 398 for (; i != 0; --i) { 399 DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1); 400 switch (fnChunk.Kind) { 401 case DeclaratorChunk::Paren: 402 continue; 403 404 // If we find anything except a function, bail out. 405 case DeclaratorChunk::Pointer: 406 case DeclaratorChunk::BlockPointer: 407 case DeclaratorChunk::Array: 408 case DeclaratorChunk::Reference: 409 case DeclaratorChunk::MemberPointer: 410 case DeclaratorChunk::Pipe: 411 return result; 412 413 // If we do find a function declarator, scan inwards from that, 414 // looking for a (block-)pointer declarator. 415 case DeclaratorChunk::Function: 416 for (--i; i != 0; --i) { 417 DeclaratorChunk &ptrChunk = declarator.getTypeObject(i-1); 418 switch (ptrChunk.Kind) { 419 case DeclaratorChunk::Paren: 420 case DeclaratorChunk::Array: 421 case DeclaratorChunk::Function: 422 case DeclaratorChunk::Reference: 423 case DeclaratorChunk::Pipe: 424 continue; 425 426 case DeclaratorChunk::MemberPointer: 427 case DeclaratorChunk::Pointer: 428 if (onlyBlockPointers) 429 continue; 430 431 LLVM_FALLTHROUGH; 432 433 case DeclaratorChunk::BlockPointer: 434 result = &ptrChunk; 435 goto continue_outer; 436 } 437 llvm_unreachable("bad declarator chunk kind"); 438 } 439 440 // If we run out of declarators doing that, we're done. 441 return result; 442 } 443 llvm_unreachable("bad declarator chunk kind"); 444 445 // Okay, reconsider from our new point. 446 continue_outer: ; 447 } 448 449 // Ran out of chunks, bail out. 450 return result; 451 } 452 453 /// Given that an objc_gc attribute was written somewhere on a 454 /// declaration *other* than on the declarator itself (for which, use 455 /// distributeObjCPointerTypeAttrFromDeclarator), and given that it 456 /// didn't apply in whatever position it was written in, try to move 457 /// it to a more appropriate position. 458 static void distributeObjCPointerTypeAttr(TypeProcessingState &state, 459 ParsedAttr &attr, QualType type) { 460 Declarator &declarator = state.getDeclarator(); 461 462 // Move it to the outermost normal or block pointer declarator. 463 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { 464 DeclaratorChunk &chunk = declarator.getTypeObject(i-1); 465 switch (chunk.Kind) { 466 case DeclaratorChunk::Pointer: 467 case DeclaratorChunk::BlockPointer: { 468 // But don't move an ARC ownership attribute to the return type 469 // of a block. 470 DeclaratorChunk *destChunk = nullptr; 471 if (state.isProcessingDeclSpec() && 472 attr.getKind() == ParsedAttr::AT_ObjCOwnership) 473 destChunk = maybeMovePastReturnType(declarator, i - 1, 474 /*onlyBlockPointers=*/true); 475 if (!destChunk) destChunk = &chunk; 476 477 moveAttrFromListToList(attr, state.getCurrentAttributes(), 478 destChunk->getAttrs()); 479 return; 480 } 481 482 case DeclaratorChunk::Paren: 483 case DeclaratorChunk::Array: 484 continue; 485 486 // We may be starting at the return type of a block. 487 case DeclaratorChunk::Function: 488 if (state.isProcessingDeclSpec() && 489 attr.getKind() == ParsedAttr::AT_ObjCOwnership) { 490 if (DeclaratorChunk *dest = maybeMovePastReturnType( 491 declarator, i, 492 /*onlyBlockPointers=*/true)) { 493 moveAttrFromListToList(attr, state.getCurrentAttributes(), 494 dest->getAttrs()); 495 return; 496 } 497 } 498 goto error; 499 500 // Don't walk through these. 501 case DeclaratorChunk::Reference: 502 case DeclaratorChunk::MemberPointer: 503 case DeclaratorChunk::Pipe: 504 goto error; 505 } 506 } 507 error: 508 509 diagnoseBadTypeAttribute(state.getSema(), attr, type); 510 } 511 512 /// Distribute an objc_gc type attribute that was written on the 513 /// declarator. 514 static void distributeObjCPointerTypeAttrFromDeclarator( 515 TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType) { 516 Declarator &declarator = state.getDeclarator(); 517 518 // objc_gc goes on the innermost pointer to something that's not a 519 // pointer. 520 unsigned innermost = -1U; 521 bool considerDeclSpec = true; 522 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { 523 DeclaratorChunk &chunk = declarator.getTypeObject(i); 524 switch (chunk.Kind) { 525 case DeclaratorChunk::Pointer: 526 case DeclaratorChunk::BlockPointer: 527 innermost = i; 528 continue; 529 530 case DeclaratorChunk::Reference: 531 case DeclaratorChunk::MemberPointer: 532 case DeclaratorChunk::Paren: 533 case DeclaratorChunk::Array: 534 case DeclaratorChunk::Pipe: 535 continue; 536 537 case DeclaratorChunk::Function: 538 considerDeclSpec = false; 539 goto done; 540 } 541 } 542 done: 543 544 // That might actually be the decl spec if we weren't blocked by 545 // anything in the declarator. 546 if (considerDeclSpec) { 547 if (handleObjCPointerTypeAttr(state, attr, declSpecType)) { 548 // Splice the attribute into the decl spec. Prevents the 549 // attribute from being applied multiple times and gives 550 // the source-location-filler something to work with. 551 state.saveDeclSpecAttrs(); 552 declarator.getMutableDeclSpec().getAttributes().takeOneFrom( 553 declarator.getAttributes(), &attr); 554 return; 555 } 556 } 557 558 // Otherwise, if we found an appropriate chunk, splice the attribute 559 // into it. 560 if (innermost != -1U) { 561 moveAttrFromListToList(attr, declarator.getAttributes(), 562 declarator.getTypeObject(innermost).getAttrs()); 563 return; 564 } 565 566 // Otherwise, diagnose when we're done building the type. 567 declarator.getAttributes().remove(&attr); 568 state.addIgnoredTypeAttr(attr); 569 } 570 571 /// A function type attribute was written somewhere in a declaration 572 /// *other* than on the declarator itself or in the decl spec. Given 573 /// that it didn't apply in whatever position it was written in, try 574 /// to move it to a more appropriate position. 575 static void distributeFunctionTypeAttr(TypeProcessingState &state, 576 ParsedAttr &attr, QualType type) { 577 Declarator &declarator = state.getDeclarator(); 578 579 // Try to push the attribute from the return type of a function to 580 // the function itself. 581 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { 582 DeclaratorChunk &chunk = declarator.getTypeObject(i-1); 583 switch (chunk.Kind) { 584 case DeclaratorChunk::Function: 585 moveAttrFromListToList(attr, state.getCurrentAttributes(), 586 chunk.getAttrs()); 587 return; 588 589 case DeclaratorChunk::Paren: 590 case DeclaratorChunk::Pointer: 591 case DeclaratorChunk::BlockPointer: 592 case DeclaratorChunk::Array: 593 case DeclaratorChunk::Reference: 594 case DeclaratorChunk::MemberPointer: 595 case DeclaratorChunk::Pipe: 596 continue; 597 } 598 } 599 600 diagnoseBadTypeAttribute(state.getSema(), attr, type); 601 } 602 603 /// Try to distribute a function type attribute to the innermost 604 /// function chunk or type. Returns true if the attribute was 605 /// distributed, false if no location was found. 606 static bool distributeFunctionTypeAttrToInnermost( 607 TypeProcessingState &state, ParsedAttr &attr, 608 ParsedAttributesView &attrList, QualType &declSpecType) { 609 Declarator &declarator = state.getDeclarator(); 610 611 // Put it on the innermost function chunk, if there is one. 612 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { 613 DeclaratorChunk &chunk = declarator.getTypeObject(i); 614 if (chunk.Kind != DeclaratorChunk::Function) continue; 615 616 moveAttrFromListToList(attr, attrList, chunk.getAttrs()); 617 return true; 618 } 619 620 return handleFunctionTypeAttr(state, attr, declSpecType); 621 } 622 623 /// A function type attribute was written in the decl spec. Try to 624 /// apply it somewhere. 625 static void distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state, 626 ParsedAttr &attr, 627 QualType &declSpecType) { 628 state.saveDeclSpecAttrs(); 629 630 // C++11 attributes before the decl specifiers actually appertain to 631 // the declarators. Move them straight there. We don't support the 632 // 'put them wherever you like' semantics we allow for GNU attributes. 633 if (attr.isStandardAttributeSyntax()) { 634 moveAttrFromListToList(attr, state.getCurrentAttributes(), 635 state.getDeclarator().getAttributes()); 636 return; 637 } 638 639 // Try to distribute to the innermost. 640 if (distributeFunctionTypeAttrToInnermost( 641 state, attr, state.getCurrentAttributes(), declSpecType)) 642 return; 643 644 // If that failed, diagnose the bad attribute when the declarator is 645 // fully built. 646 state.addIgnoredTypeAttr(attr); 647 } 648 649 /// A function type attribute was written on the declarator. Try to 650 /// apply it somewhere. 651 static void distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state, 652 ParsedAttr &attr, 653 QualType &declSpecType) { 654 Declarator &declarator = state.getDeclarator(); 655 656 // Try to distribute to the innermost. 657 if (distributeFunctionTypeAttrToInnermost( 658 state, attr, declarator.getAttributes(), declSpecType)) 659 return; 660 661 // If that failed, diagnose the bad attribute when the declarator is 662 // fully built. 663 declarator.getAttributes().remove(&attr); 664 state.addIgnoredTypeAttr(attr); 665 } 666 667 /// Given that there are attributes written on the declarator 668 /// itself, try to distribute any type attributes to the appropriate 669 /// declarator chunk. 670 /// 671 /// These are attributes like the following: 672 /// int f ATTR; 673 /// int (f ATTR)(); 674 /// but not necessarily this: 675 /// int f() ATTR; 676 static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state, 677 QualType &declSpecType) { 678 // Collect all the type attributes from the declarator itself. 679 assert(!state.getDeclarator().getAttributes().empty() && 680 "declarator has no attrs!"); 681 // The called functions in this loop actually remove things from the current 682 // list, so iterating over the existing list isn't possible. Instead, make a 683 // non-owning copy and iterate over that. 684 ParsedAttributesView AttrsCopy{state.getDeclarator().getAttributes()}; 685 for (ParsedAttr &attr : AttrsCopy) { 686 // Do not distribute [[]] attributes. They have strict rules for what 687 // they appertain to. 688 if (attr.isStandardAttributeSyntax()) 689 continue; 690 691 switch (attr.getKind()) { 692 OBJC_POINTER_TYPE_ATTRS_CASELIST: 693 distributeObjCPointerTypeAttrFromDeclarator(state, attr, declSpecType); 694 break; 695 696 FUNCTION_TYPE_ATTRS_CASELIST: 697 distributeFunctionTypeAttrFromDeclarator(state, attr, declSpecType); 698 break; 699 700 MS_TYPE_ATTRS_CASELIST: 701 // Microsoft type attributes cannot go after the declarator-id. 702 continue; 703 704 NULLABILITY_TYPE_ATTRS_CASELIST: 705 // Nullability specifiers cannot go after the declarator-id. 706 707 // Objective-C __kindof does not get distributed. 708 case ParsedAttr::AT_ObjCKindOf: 709 continue; 710 711 default: 712 break; 713 } 714 } 715 } 716 717 /// Add a synthetic '()' to a block-literal declarator if it is 718 /// required, given the return type. 719 static void maybeSynthesizeBlockSignature(TypeProcessingState &state, 720 QualType declSpecType) { 721 Declarator &declarator = state.getDeclarator(); 722 723 // First, check whether the declarator would produce a function, 724 // i.e. whether the innermost semantic chunk is a function. 725 if (declarator.isFunctionDeclarator()) { 726 // If so, make that declarator a prototyped declarator. 727 declarator.getFunctionTypeInfo().hasPrototype = true; 728 return; 729 } 730 731 // If there are any type objects, the type as written won't name a 732 // function, regardless of the decl spec type. This is because a 733 // block signature declarator is always an abstract-declarator, and 734 // abstract-declarators can't just be parentheses chunks. Therefore 735 // we need to build a function chunk unless there are no type 736 // objects and the decl spec type is a function. 737 if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType()) 738 return; 739 740 // Note that there *are* cases with invalid declarators where 741 // declarators consist solely of parentheses. In general, these 742 // occur only in failed efforts to make function declarators, so 743 // faking up the function chunk is still the right thing to do. 744 745 // Otherwise, we need to fake up a function declarator. 746 SourceLocation loc = declarator.getBeginLoc(); 747 748 // ...and *prepend* it to the declarator. 749 SourceLocation NoLoc; 750 declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction( 751 /*HasProto=*/true, 752 /*IsAmbiguous=*/false, 753 /*LParenLoc=*/NoLoc, 754 /*ArgInfo=*/nullptr, 755 /*NumParams=*/0, 756 /*EllipsisLoc=*/NoLoc, 757 /*RParenLoc=*/NoLoc, 758 /*RefQualifierIsLvalueRef=*/true, 759 /*RefQualifierLoc=*/NoLoc, 760 /*MutableLoc=*/NoLoc, EST_None, 761 /*ESpecRange=*/SourceRange(), 762 /*Exceptions=*/nullptr, 763 /*ExceptionRanges=*/nullptr, 764 /*NumExceptions=*/0, 765 /*NoexceptExpr=*/nullptr, 766 /*ExceptionSpecTokens=*/nullptr, 767 /*DeclsInPrototype=*/None, loc, loc, declarator)); 768 769 // For consistency, make sure the state still has us as processing 770 // the decl spec. 771 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1); 772 state.setCurrentChunkIndex(declarator.getNumTypeObjects()); 773 } 774 775 static void diagnoseAndRemoveTypeQualifiers(Sema &S, const DeclSpec &DS, 776 unsigned &TypeQuals, 777 QualType TypeSoFar, 778 unsigned RemoveTQs, 779 unsigned DiagID) { 780 // If this occurs outside a template instantiation, warn the user about 781 // it; they probably didn't mean to specify a redundant qualifier. 782 typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc; 783 for (QualLoc Qual : {QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()), 784 QualLoc(DeclSpec::TQ_restrict, DS.getRestrictSpecLoc()), 785 QualLoc(DeclSpec::TQ_volatile, DS.getVolatileSpecLoc()), 786 QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) { 787 if (!(RemoveTQs & Qual.first)) 788 continue; 789 790 if (!S.inTemplateInstantiation()) { 791 if (TypeQuals & Qual.first) 792 S.Diag(Qual.second, DiagID) 793 << DeclSpec::getSpecifierName(Qual.first) << TypeSoFar 794 << FixItHint::CreateRemoval(Qual.second); 795 } 796 797 TypeQuals &= ~Qual.first; 798 } 799 } 800 801 /// Return true if this is omitted block return type. Also check type 802 /// attributes and type qualifiers when returning true. 803 static bool checkOmittedBlockReturnType(Sema &S, Declarator &declarator, 804 QualType Result) { 805 if (!isOmittedBlockReturnType(declarator)) 806 return false; 807 808 // Warn if we see type attributes for omitted return type on a block literal. 809 SmallVector<ParsedAttr *, 2> ToBeRemoved; 810 for (ParsedAttr &AL : declarator.getMutableDeclSpec().getAttributes()) { 811 if (AL.isInvalid() || !AL.isTypeAttr()) 812 continue; 813 S.Diag(AL.getLoc(), 814 diag::warn_block_literal_attributes_on_omitted_return_type) 815 << AL; 816 ToBeRemoved.push_back(&AL); 817 } 818 // Remove bad attributes from the list. 819 for (ParsedAttr *AL : ToBeRemoved) 820 declarator.getMutableDeclSpec().getAttributes().remove(AL); 821 822 // Warn if we see type qualifiers for omitted return type on a block literal. 823 const DeclSpec &DS = declarator.getDeclSpec(); 824 unsigned TypeQuals = DS.getTypeQualifiers(); 825 diagnoseAndRemoveTypeQualifiers(S, DS, TypeQuals, Result, (unsigned)-1, 826 diag::warn_block_literal_qualifiers_on_omitted_return_type); 827 declarator.getMutableDeclSpec().ClearTypeQualifiers(); 828 829 return true; 830 } 831 832 /// Apply Objective-C type arguments to the given type. 833 static QualType applyObjCTypeArgs(Sema &S, SourceLocation loc, QualType type, 834 ArrayRef<TypeSourceInfo *> typeArgs, 835 SourceRange typeArgsRange, 836 bool failOnError = false) { 837 // We can only apply type arguments to an Objective-C class type. 838 const auto *objcObjectType = type->getAs<ObjCObjectType>(); 839 if (!objcObjectType || !objcObjectType->getInterface()) { 840 S.Diag(loc, diag::err_objc_type_args_non_class) 841 << type 842 << typeArgsRange; 843 844 if (failOnError) 845 return QualType(); 846 return type; 847 } 848 849 // The class type must be parameterized. 850 ObjCInterfaceDecl *objcClass = objcObjectType->getInterface(); 851 ObjCTypeParamList *typeParams = objcClass->getTypeParamList(); 852 if (!typeParams) { 853 S.Diag(loc, diag::err_objc_type_args_non_parameterized_class) 854 << objcClass->getDeclName() 855 << FixItHint::CreateRemoval(typeArgsRange); 856 857 if (failOnError) 858 return QualType(); 859 860 return type; 861 } 862 863 // The type must not already be specialized. 864 if (objcObjectType->isSpecialized()) { 865 S.Diag(loc, diag::err_objc_type_args_specialized_class) 866 << type 867 << FixItHint::CreateRemoval(typeArgsRange); 868 869 if (failOnError) 870 return QualType(); 871 872 return type; 873 } 874 875 // Check the type arguments. 876 SmallVector<QualType, 4> finalTypeArgs; 877 unsigned numTypeParams = typeParams->size(); 878 bool anyPackExpansions = false; 879 for (unsigned i = 0, n = typeArgs.size(); i != n; ++i) { 880 TypeSourceInfo *typeArgInfo = typeArgs[i]; 881 QualType typeArg = typeArgInfo->getType(); 882 883 // Type arguments cannot have explicit qualifiers or nullability. 884 // We ignore indirect sources of these, e.g. behind typedefs or 885 // template arguments. 886 if (TypeLoc qual = typeArgInfo->getTypeLoc().findExplicitQualifierLoc()) { 887 bool diagnosed = false; 888 SourceRange rangeToRemove; 889 if (auto attr = qual.getAs<AttributedTypeLoc>()) { 890 rangeToRemove = attr.getLocalSourceRange(); 891 if (attr.getTypePtr()->getImmediateNullability()) { 892 typeArg = attr.getTypePtr()->getModifiedType(); 893 S.Diag(attr.getBeginLoc(), 894 diag::err_objc_type_arg_explicit_nullability) 895 << typeArg << FixItHint::CreateRemoval(rangeToRemove); 896 diagnosed = true; 897 } 898 } 899 900 if (!diagnosed) { 901 S.Diag(qual.getBeginLoc(), diag::err_objc_type_arg_qualified) 902 << typeArg << typeArg.getQualifiers().getAsString() 903 << FixItHint::CreateRemoval(rangeToRemove); 904 } 905 } 906 907 // Remove qualifiers even if they're non-local. 908 typeArg = typeArg.getUnqualifiedType(); 909 910 finalTypeArgs.push_back(typeArg); 911 912 if (typeArg->getAs<PackExpansionType>()) 913 anyPackExpansions = true; 914 915 // Find the corresponding type parameter, if there is one. 916 ObjCTypeParamDecl *typeParam = nullptr; 917 if (!anyPackExpansions) { 918 if (i < numTypeParams) { 919 typeParam = typeParams->begin()[i]; 920 } else { 921 // Too many arguments. 922 S.Diag(loc, diag::err_objc_type_args_wrong_arity) 923 << false 924 << objcClass->getDeclName() 925 << (unsigned)typeArgs.size() 926 << numTypeParams; 927 S.Diag(objcClass->getLocation(), diag::note_previous_decl) 928 << objcClass; 929 930 if (failOnError) 931 return QualType(); 932 933 return type; 934 } 935 } 936 937 // Objective-C object pointer types must be substitutable for the bounds. 938 if (const auto *typeArgObjC = typeArg->getAs<ObjCObjectPointerType>()) { 939 // If we don't have a type parameter to match against, assume 940 // everything is fine. There was a prior pack expansion that 941 // means we won't be able to match anything. 942 if (!typeParam) { 943 assert(anyPackExpansions && "Too many arguments?"); 944 continue; 945 } 946 947 // Retrieve the bound. 948 QualType bound = typeParam->getUnderlyingType(); 949 const auto *boundObjC = bound->getAs<ObjCObjectPointerType>(); 950 951 // Determine whether the type argument is substitutable for the bound. 952 if (typeArgObjC->isObjCIdType()) { 953 // When the type argument is 'id', the only acceptable type 954 // parameter bound is 'id'. 955 if (boundObjC->isObjCIdType()) 956 continue; 957 } else if (S.Context.canAssignObjCInterfaces(boundObjC, typeArgObjC)) { 958 // Otherwise, we follow the assignability rules. 959 continue; 960 } 961 962 // Diagnose the mismatch. 963 S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(), 964 diag::err_objc_type_arg_does_not_match_bound) 965 << typeArg << bound << typeParam->getDeclName(); 966 S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here) 967 << typeParam->getDeclName(); 968 969 if (failOnError) 970 return QualType(); 971 972 return type; 973 } 974 975 // Block pointer types are permitted for unqualified 'id' bounds. 976 if (typeArg->isBlockPointerType()) { 977 // If we don't have a type parameter to match against, assume 978 // everything is fine. There was a prior pack expansion that 979 // means we won't be able to match anything. 980 if (!typeParam) { 981 assert(anyPackExpansions && "Too many arguments?"); 982 continue; 983 } 984 985 // Retrieve the bound. 986 QualType bound = typeParam->getUnderlyingType(); 987 if (bound->isBlockCompatibleObjCPointerType(S.Context)) 988 continue; 989 990 // Diagnose the mismatch. 991 S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(), 992 diag::err_objc_type_arg_does_not_match_bound) 993 << typeArg << bound << typeParam->getDeclName(); 994 S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here) 995 << typeParam->getDeclName(); 996 997 if (failOnError) 998 return QualType(); 999 1000 return type; 1001 } 1002 1003 // Dependent types will be checked at instantiation time. 1004 if (typeArg->isDependentType()) { 1005 continue; 1006 } 1007 1008 // Diagnose non-id-compatible type arguments. 1009 S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(), 1010 diag::err_objc_type_arg_not_id_compatible) 1011 << typeArg << typeArgInfo->getTypeLoc().getSourceRange(); 1012 1013 if (failOnError) 1014 return QualType(); 1015 1016 return type; 1017 } 1018 1019 // Make sure we didn't have the wrong number of arguments. 1020 if (!anyPackExpansions && finalTypeArgs.size() != numTypeParams) { 1021 S.Diag(loc, diag::err_objc_type_args_wrong_arity) 1022 << (typeArgs.size() < typeParams->size()) 1023 << objcClass->getDeclName() 1024 << (unsigned)finalTypeArgs.size() 1025 << (unsigned)numTypeParams; 1026 S.Diag(objcClass->getLocation(), diag::note_previous_decl) 1027 << objcClass; 1028 1029 if (failOnError) 1030 return QualType(); 1031 1032 return type; 1033 } 1034 1035 // Success. Form the specialized type. 1036 return S.Context.getObjCObjectType(type, finalTypeArgs, { }, false); 1037 } 1038 1039 QualType Sema::BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl, 1040 SourceLocation ProtocolLAngleLoc, 1041 ArrayRef<ObjCProtocolDecl *> Protocols, 1042 ArrayRef<SourceLocation> ProtocolLocs, 1043 SourceLocation ProtocolRAngleLoc, 1044 bool FailOnError) { 1045 QualType Result = QualType(Decl->getTypeForDecl(), 0); 1046 if (!Protocols.empty()) { 1047 bool HasError; 1048 Result = Context.applyObjCProtocolQualifiers(Result, Protocols, 1049 HasError); 1050 if (HasError) { 1051 Diag(SourceLocation(), diag::err_invalid_protocol_qualifiers) 1052 << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc); 1053 if (FailOnError) Result = QualType(); 1054 } 1055 if (FailOnError && Result.isNull()) 1056 return QualType(); 1057 } 1058 1059 return Result; 1060 } 1061 1062 QualType Sema::BuildObjCObjectType(QualType BaseType, 1063 SourceLocation Loc, 1064 SourceLocation TypeArgsLAngleLoc, 1065 ArrayRef<TypeSourceInfo *> TypeArgs, 1066 SourceLocation TypeArgsRAngleLoc, 1067 SourceLocation ProtocolLAngleLoc, 1068 ArrayRef<ObjCProtocolDecl *> Protocols, 1069 ArrayRef<SourceLocation> ProtocolLocs, 1070 SourceLocation ProtocolRAngleLoc, 1071 bool FailOnError) { 1072 QualType Result = BaseType; 1073 if (!TypeArgs.empty()) { 1074 Result = applyObjCTypeArgs(*this, Loc, Result, TypeArgs, 1075 SourceRange(TypeArgsLAngleLoc, 1076 TypeArgsRAngleLoc), 1077 FailOnError); 1078 if (FailOnError && Result.isNull()) 1079 return QualType(); 1080 } 1081 1082 if (!Protocols.empty()) { 1083 bool HasError; 1084 Result = Context.applyObjCProtocolQualifiers(Result, Protocols, 1085 HasError); 1086 if (HasError) { 1087 Diag(Loc, diag::err_invalid_protocol_qualifiers) 1088 << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc); 1089 if (FailOnError) Result = QualType(); 1090 } 1091 if (FailOnError && Result.isNull()) 1092 return QualType(); 1093 } 1094 1095 return Result; 1096 } 1097 1098 TypeResult Sema::actOnObjCProtocolQualifierType( 1099 SourceLocation lAngleLoc, 1100 ArrayRef<Decl *> protocols, 1101 ArrayRef<SourceLocation> protocolLocs, 1102 SourceLocation rAngleLoc) { 1103 // Form id<protocol-list>. 1104 QualType Result = Context.getObjCObjectType( 1105 Context.ObjCBuiltinIdTy, { }, 1106 llvm::makeArrayRef( 1107 (ObjCProtocolDecl * const *)protocols.data(), 1108 protocols.size()), 1109 false); 1110 Result = Context.getObjCObjectPointerType(Result); 1111 1112 TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result); 1113 TypeLoc ResultTL = ResultTInfo->getTypeLoc(); 1114 1115 auto ObjCObjectPointerTL = ResultTL.castAs<ObjCObjectPointerTypeLoc>(); 1116 ObjCObjectPointerTL.setStarLoc(SourceLocation()); // implicit 1117 1118 auto ObjCObjectTL = ObjCObjectPointerTL.getPointeeLoc() 1119 .castAs<ObjCObjectTypeLoc>(); 1120 ObjCObjectTL.setHasBaseTypeAsWritten(false); 1121 ObjCObjectTL.getBaseLoc().initialize(Context, SourceLocation()); 1122 1123 // No type arguments. 1124 ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation()); 1125 ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation()); 1126 1127 // Fill in protocol qualifiers. 1128 ObjCObjectTL.setProtocolLAngleLoc(lAngleLoc); 1129 ObjCObjectTL.setProtocolRAngleLoc(rAngleLoc); 1130 for (unsigned i = 0, n = protocols.size(); i != n; ++i) 1131 ObjCObjectTL.setProtocolLoc(i, protocolLocs[i]); 1132 1133 // We're done. Return the completed type to the parser. 1134 return CreateParsedType(Result, ResultTInfo); 1135 } 1136 1137 TypeResult Sema::actOnObjCTypeArgsAndProtocolQualifiers( 1138 Scope *S, 1139 SourceLocation Loc, 1140 ParsedType BaseType, 1141 SourceLocation TypeArgsLAngleLoc, 1142 ArrayRef<ParsedType> TypeArgs, 1143 SourceLocation TypeArgsRAngleLoc, 1144 SourceLocation ProtocolLAngleLoc, 1145 ArrayRef<Decl *> Protocols, 1146 ArrayRef<SourceLocation> ProtocolLocs, 1147 SourceLocation ProtocolRAngleLoc) { 1148 TypeSourceInfo *BaseTypeInfo = nullptr; 1149 QualType T = GetTypeFromParser(BaseType, &BaseTypeInfo); 1150 if (T.isNull()) 1151 return true; 1152 1153 // Handle missing type-source info. 1154 if (!BaseTypeInfo) 1155 BaseTypeInfo = Context.getTrivialTypeSourceInfo(T, Loc); 1156 1157 // Extract type arguments. 1158 SmallVector<TypeSourceInfo *, 4> ActualTypeArgInfos; 1159 for (unsigned i = 0, n = TypeArgs.size(); i != n; ++i) { 1160 TypeSourceInfo *TypeArgInfo = nullptr; 1161 QualType TypeArg = GetTypeFromParser(TypeArgs[i], &TypeArgInfo); 1162 if (TypeArg.isNull()) { 1163 ActualTypeArgInfos.clear(); 1164 break; 1165 } 1166 1167 assert(TypeArgInfo && "No type source info?"); 1168 ActualTypeArgInfos.push_back(TypeArgInfo); 1169 } 1170 1171 // Build the object type. 1172 QualType Result = BuildObjCObjectType( 1173 T, BaseTypeInfo->getTypeLoc().getSourceRange().getBegin(), 1174 TypeArgsLAngleLoc, ActualTypeArgInfos, TypeArgsRAngleLoc, 1175 ProtocolLAngleLoc, 1176 llvm::makeArrayRef((ObjCProtocolDecl * const *)Protocols.data(), 1177 Protocols.size()), 1178 ProtocolLocs, ProtocolRAngleLoc, 1179 /*FailOnError=*/false); 1180 1181 if (Result == T) 1182 return BaseType; 1183 1184 // Create source information for this type. 1185 TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result); 1186 TypeLoc ResultTL = ResultTInfo->getTypeLoc(); 1187 1188 // For id<Proto1, Proto2> or Class<Proto1, Proto2>, we'll have an 1189 // object pointer type. Fill in source information for it. 1190 if (auto ObjCObjectPointerTL = ResultTL.getAs<ObjCObjectPointerTypeLoc>()) { 1191 // The '*' is implicit. 1192 ObjCObjectPointerTL.setStarLoc(SourceLocation()); 1193 ResultTL = ObjCObjectPointerTL.getPointeeLoc(); 1194 } 1195 1196 if (auto OTPTL = ResultTL.getAs<ObjCTypeParamTypeLoc>()) { 1197 // Protocol qualifier information. 1198 if (OTPTL.getNumProtocols() > 0) { 1199 assert(OTPTL.getNumProtocols() == Protocols.size()); 1200 OTPTL.setProtocolLAngleLoc(ProtocolLAngleLoc); 1201 OTPTL.setProtocolRAngleLoc(ProtocolRAngleLoc); 1202 for (unsigned i = 0, n = Protocols.size(); i != n; ++i) 1203 OTPTL.setProtocolLoc(i, ProtocolLocs[i]); 1204 } 1205 1206 // We're done. Return the completed type to the parser. 1207 return CreateParsedType(Result, ResultTInfo); 1208 } 1209 1210 auto ObjCObjectTL = ResultTL.castAs<ObjCObjectTypeLoc>(); 1211 1212 // Type argument information. 1213 if (ObjCObjectTL.getNumTypeArgs() > 0) { 1214 assert(ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size()); 1215 ObjCObjectTL.setTypeArgsLAngleLoc(TypeArgsLAngleLoc); 1216 ObjCObjectTL.setTypeArgsRAngleLoc(TypeArgsRAngleLoc); 1217 for (unsigned i = 0, n = ActualTypeArgInfos.size(); i != n; ++i) 1218 ObjCObjectTL.setTypeArgTInfo(i, ActualTypeArgInfos[i]); 1219 } else { 1220 ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation()); 1221 ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation()); 1222 } 1223 1224 // Protocol qualifier information. 1225 if (ObjCObjectTL.getNumProtocols() > 0) { 1226 assert(ObjCObjectTL.getNumProtocols() == Protocols.size()); 1227 ObjCObjectTL.setProtocolLAngleLoc(ProtocolLAngleLoc); 1228 ObjCObjectTL.setProtocolRAngleLoc(ProtocolRAngleLoc); 1229 for (unsigned i = 0, n = Protocols.size(); i != n; ++i) 1230 ObjCObjectTL.setProtocolLoc(i, ProtocolLocs[i]); 1231 } else { 1232 ObjCObjectTL.setProtocolLAngleLoc(SourceLocation()); 1233 ObjCObjectTL.setProtocolRAngleLoc(SourceLocation()); 1234 } 1235 1236 // Base type. 1237 ObjCObjectTL.setHasBaseTypeAsWritten(true); 1238 if (ObjCObjectTL.getType() == T) 1239 ObjCObjectTL.getBaseLoc().initializeFullCopy(BaseTypeInfo->getTypeLoc()); 1240 else 1241 ObjCObjectTL.getBaseLoc().initialize(Context, Loc); 1242 1243 // We're done. Return the completed type to the parser. 1244 return CreateParsedType(Result, ResultTInfo); 1245 } 1246 1247 static OpenCLAccessAttr::Spelling 1248 getImageAccess(const ParsedAttributesView &Attrs) { 1249 for (const ParsedAttr &AL : Attrs) 1250 if (AL.getKind() == ParsedAttr::AT_OpenCLAccess) 1251 return static_cast<OpenCLAccessAttr::Spelling>(AL.getSemanticSpelling()); 1252 return OpenCLAccessAttr::Keyword_read_only; 1253 } 1254 1255 /// Convert the specified declspec to the appropriate type 1256 /// object. 1257 /// \param state Specifies the declarator containing the declaration specifier 1258 /// to be converted, along with other associated processing state. 1259 /// \returns The type described by the declaration specifiers. This function 1260 /// never returns null. 1261 static QualType ConvertDeclSpecToType(TypeProcessingState &state) { 1262 // FIXME: Should move the logic from DeclSpec::Finish to here for validity 1263 // checking. 1264 1265 Sema &S = state.getSema(); 1266 Declarator &declarator = state.getDeclarator(); 1267 DeclSpec &DS = declarator.getMutableDeclSpec(); 1268 SourceLocation DeclLoc = declarator.getIdentifierLoc(); 1269 if (DeclLoc.isInvalid()) 1270 DeclLoc = DS.getBeginLoc(); 1271 1272 ASTContext &Context = S.Context; 1273 1274 QualType Result; 1275 switch (DS.getTypeSpecType()) { 1276 case DeclSpec::TST_void: 1277 Result = Context.VoidTy; 1278 break; 1279 case DeclSpec::TST_char: 1280 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified) 1281 Result = Context.CharTy; 1282 else if (DS.getTypeSpecSign() == TypeSpecifierSign::Signed) 1283 Result = Context.SignedCharTy; 1284 else { 1285 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned && 1286 "Unknown TSS value"); 1287 Result = Context.UnsignedCharTy; 1288 } 1289 break; 1290 case DeclSpec::TST_wchar: 1291 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified) 1292 Result = Context.WCharTy; 1293 else if (DS.getTypeSpecSign() == TypeSpecifierSign::Signed) { 1294 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec) 1295 << DS.getSpecifierName(DS.getTypeSpecType(), 1296 Context.getPrintingPolicy()); 1297 Result = Context.getSignedWCharType(); 1298 } else { 1299 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned && 1300 "Unknown TSS value"); 1301 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec) 1302 << DS.getSpecifierName(DS.getTypeSpecType(), 1303 Context.getPrintingPolicy()); 1304 Result = Context.getUnsignedWCharType(); 1305 } 1306 break; 1307 case DeclSpec::TST_char8: 1308 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && 1309 "Unknown TSS value"); 1310 Result = Context.Char8Ty; 1311 break; 1312 case DeclSpec::TST_char16: 1313 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && 1314 "Unknown TSS value"); 1315 Result = Context.Char16Ty; 1316 break; 1317 case DeclSpec::TST_char32: 1318 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && 1319 "Unknown TSS value"); 1320 Result = Context.Char32Ty; 1321 break; 1322 case DeclSpec::TST_unspecified: 1323 // If this is a missing declspec in a block literal return context, then it 1324 // is inferred from the return statements inside the block. 1325 // The declspec is always missing in a lambda expr context; it is either 1326 // specified with a trailing return type or inferred. 1327 if (S.getLangOpts().CPlusPlus14 && 1328 declarator.getContext() == DeclaratorContext::LambdaExpr) { 1329 // In C++1y, a lambda's implicit return type is 'auto'. 1330 Result = Context.getAutoDeductType(); 1331 break; 1332 } else if (declarator.getContext() == DeclaratorContext::LambdaExpr || 1333 checkOmittedBlockReturnType(S, declarator, 1334 Context.DependentTy)) { 1335 Result = Context.DependentTy; 1336 break; 1337 } 1338 1339 // Unspecified typespec defaults to int in C90. However, the C90 grammar 1340 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier, 1341 // type-qualifier, or storage-class-specifier. If not, emit an extwarn. 1342 // Note that the one exception to this is function definitions, which are 1343 // allowed to be completely missing a declspec. This is handled in the 1344 // parser already though by it pretending to have seen an 'int' in this 1345 // case. 1346 if (S.getLangOpts().ImplicitInt) { 1347 // In C89 mode, we only warn if there is a completely missing declspec 1348 // when one is not allowed. 1349 if (DS.isEmpty()) { 1350 S.Diag(DeclLoc, diag::ext_missing_declspec) 1351 << DS.getSourceRange() 1352 << FixItHint::CreateInsertion(DS.getBeginLoc(), "int"); 1353 } 1354 } else if (!DS.hasTypeSpecifier()) { 1355 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says: 1356 // "At least one type specifier shall be given in the declaration 1357 // specifiers in each declaration, and in the specifier-qualifier list in 1358 // each struct declaration and type name." 1359 if (S.getLangOpts().CPlusPlus && !DS.isTypeSpecPipe()) { 1360 S.Diag(DeclLoc, diag::err_missing_type_specifier) 1361 << DS.getSourceRange(); 1362 1363 // When this occurs in C++ code, often something is very broken with the 1364 // value being declared, poison it as invalid so we don't get chains of 1365 // errors. 1366 declarator.setInvalidType(true); 1367 } else if (S.getLangOpts().getOpenCLCompatibleVersion() >= 200 && 1368 DS.isTypeSpecPipe()) { 1369 S.Diag(DeclLoc, diag::err_missing_actual_pipe_type) 1370 << DS.getSourceRange(); 1371 declarator.setInvalidType(true); 1372 } else { 1373 S.Diag(DeclLoc, diag::ext_missing_type_specifier) 1374 << DS.getSourceRange(); 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 (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. 5579 if (FTI.NumParams == 0 && !FTI.isVariadic && FTI.getLParenLoc().isValid()) 5580 S.Diag(DeclType.Loc, diag::warn_strict_prototypes) 5581 << IsBlock 5582 << FixItHint::CreateInsertion(FTI.getRParenLoc(), "void"); 5583 IsBlock = false; 5584 break; 5585 } 5586 default: 5587 break; 5588 } 5589 } 5590 } 5591 5592 assert(!T.isNull() && "T must not be null after this point"); 5593 5594 if (LangOpts.CPlusPlus && T->isFunctionType()) { 5595 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>(); 5596 assert(FnTy && "Why oh why is there not a FunctionProtoType here?"); 5597 5598 // C++ 8.3.5p4: 5599 // A cv-qualifier-seq shall only be part of the function type 5600 // for a nonstatic member function, the function type to which a pointer 5601 // to member refers, or the top-level function type of a function typedef 5602 // declaration. 5603 // 5604 // Core issue 547 also allows cv-qualifiers on function types that are 5605 // top-level template type arguments. 5606 enum { NonMember, Member, DeductionGuide } Kind = NonMember; 5607 if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName) 5608 Kind = DeductionGuide; 5609 else if (!D.getCXXScopeSpec().isSet()) { 5610 if ((D.getContext() == DeclaratorContext::Member || 5611 D.getContext() == DeclaratorContext::LambdaExpr) && 5612 !D.getDeclSpec().isFriendSpecified()) 5613 Kind = Member; 5614 } else { 5615 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec()); 5616 if (!DC || DC->isRecord()) 5617 Kind = Member; 5618 } 5619 5620 // C++11 [dcl.fct]p6 (w/DR1417): 5621 // An attempt to specify a function type with a cv-qualifier-seq or a 5622 // ref-qualifier (including by typedef-name) is ill-formed unless it is: 5623 // - the function type for a non-static member function, 5624 // - the function type to which a pointer to member refers, 5625 // - the top-level function type of a function typedef declaration or 5626 // alias-declaration, 5627 // - the type-id in the default argument of a type-parameter, or 5628 // - the type-id of a template-argument for a type-parameter 5629 // 5630 // FIXME: Checking this here is insufficient. We accept-invalid on: 5631 // 5632 // template<typename T> struct S { void f(T); }; 5633 // S<int() const> s; 5634 // 5635 // ... for instance. 5636 if (IsQualifiedFunction && 5637 !(Kind == Member && 5638 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) && 5639 !IsTypedefName && D.getContext() != DeclaratorContext::TemplateArg && 5640 D.getContext() != DeclaratorContext::TemplateTypeArg) { 5641 SourceLocation Loc = D.getBeginLoc(); 5642 SourceRange RemovalRange; 5643 unsigned I; 5644 if (D.isFunctionDeclarator(I)) { 5645 SmallVector<SourceLocation, 4> RemovalLocs; 5646 const DeclaratorChunk &Chunk = D.getTypeObject(I); 5647 assert(Chunk.Kind == DeclaratorChunk::Function); 5648 5649 if (Chunk.Fun.hasRefQualifier()) 5650 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc()); 5651 5652 if (Chunk.Fun.hasMethodTypeQualifiers()) 5653 Chunk.Fun.MethodQualifiers->forEachQualifier( 5654 [&](DeclSpec::TQ TypeQual, StringRef QualName, 5655 SourceLocation SL) { RemovalLocs.push_back(SL); }); 5656 5657 if (!RemovalLocs.empty()) { 5658 llvm::sort(RemovalLocs, 5659 BeforeThanCompare<SourceLocation>(S.getSourceManager())); 5660 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back()); 5661 Loc = RemovalLocs.front(); 5662 } 5663 } 5664 5665 S.Diag(Loc, diag::err_invalid_qualified_function_type) 5666 << Kind << D.isFunctionDeclarator() << T 5667 << getFunctionQualifiersAsString(FnTy) 5668 << FixItHint::CreateRemoval(RemovalRange); 5669 5670 // Strip the cv-qualifiers and ref-qualifiers from the type. 5671 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo(); 5672 EPI.TypeQuals.removeCVRQualifiers(); 5673 EPI.RefQualifier = RQ_None; 5674 5675 T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(), 5676 EPI); 5677 // Rebuild any parens around the identifier in the function type. 5678 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 5679 if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren) 5680 break; 5681 T = S.BuildParenType(T); 5682 } 5683 } 5684 } 5685 5686 // Apply any undistributed attributes from the declarator. 5687 processTypeAttrs(state, T, TAL_DeclName, D.getAttributes()); 5688 5689 // Diagnose any ignored type attributes. 5690 state.diagnoseIgnoredTypeAttrs(T); 5691 5692 // C++0x [dcl.constexpr]p9: 5693 // A constexpr specifier used in an object declaration declares the object 5694 // as const. 5695 if (D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Constexpr && 5696 T->isObjectType()) 5697 T.addConst(); 5698 5699 // C++2a [dcl.fct]p4: 5700 // A parameter with volatile-qualified type is deprecated 5701 if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20 && 5702 (D.getContext() == DeclaratorContext::Prototype || 5703 D.getContext() == DeclaratorContext::LambdaExprParameter)) 5704 S.Diag(D.getIdentifierLoc(), diag::warn_deprecated_volatile_param) << T; 5705 5706 // If there was an ellipsis in the declarator, the declaration declares a 5707 // parameter pack whose type may be a pack expansion type. 5708 if (D.hasEllipsis()) { 5709 // C++0x [dcl.fct]p13: 5710 // A declarator-id or abstract-declarator containing an ellipsis shall 5711 // only be used in a parameter-declaration. Such a parameter-declaration 5712 // is a parameter pack (14.5.3). [...] 5713 switch (D.getContext()) { 5714 case DeclaratorContext::Prototype: 5715 case DeclaratorContext::LambdaExprParameter: 5716 case DeclaratorContext::RequiresExpr: 5717 // C++0x [dcl.fct]p13: 5718 // [...] When it is part of a parameter-declaration-clause, the 5719 // parameter pack is a function parameter pack (14.5.3). The type T 5720 // of the declarator-id of the function parameter pack shall contain 5721 // a template parameter pack; each template parameter pack in T is 5722 // expanded by the function parameter pack. 5723 // 5724 // We represent function parameter packs as function parameters whose 5725 // type is a pack expansion. 5726 if (!T->containsUnexpandedParameterPack() && 5727 (!LangOpts.CPlusPlus20 || !T->getContainedAutoType())) { 5728 S.Diag(D.getEllipsisLoc(), 5729 diag::err_function_parameter_pack_without_parameter_packs) 5730 << T << D.getSourceRange(); 5731 D.setEllipsisLoc(SourceLocation()); 5732 } else { 5733 T = Context.getPackExpansionType(T, None, /*ExpectPackInType=*/false); 5734 } 5735 break; 5736 case DeclaratorContext::TemplateParam: 5737 // C++0x [temp.param]p15: 5738 // If a template-parameter is a [...] is a parameter-declaration that 5739 // declares a parameter pack (8.3.5), then the template-parameter is a 5740 // template parameter pack (14.5.3). 5741 // 5742 // Note: core issue 778 clarifies that, if there are any unexpanded 5743 // parameter packs in the type of the non-type template parameter, then 5744 // it expands those parameter packs. 5745 if (T->containsUnexpandedParameterPack()) 5746 T = Context.getPackExpansionType(T, None); 5747 else 5748 S.Diag(D.getEllipsisLoc(), 5749 LangOpts.CPlusPlus11 5750 ? diag::warn_cxx98_compat_variadic_templates 5751 : diag::ext_variadic_templates); 5752 break; 5753 5754 case DeclaratorContext::File: 5755 case DeclaratorContext::KNRTypeList: 5756 case DeclaratorContext::ObjCParameter: // FIXME: special diagnostic here? 5757 case DeclaratorContext::ObjCResult: // FIXME: special diagnostic here? 5758 case DeclaratorContext::TypeName: 5759 case DeclaratorContext::FunctionalCast: 5760 case DeclaratorContext::CXXNew: 5761 case DeclaratorContext::AliasDecl: 5762 case DeclaratorContext::AliasTemplate: 5763 case DeclaratorContext::Member: 5764 case DeclaratorContext::Block: 5765 case DeclaratorContext::ForInit: 5766 case DeclaratorContext::SelectionInit: 5767 case DeclaratorContext::Condition: 5768 case DeclaratorContext::CXXCatch: 5769 case DeclaratorContext::ObjCCatch: 5770 case DeclaratorContext::BlockLiteral: 5771 case DeclaratorContext::LambdaExpr: 5772 case DeclaratorContext::ConversionId: 5773 case DeclaratorContext::TrailingReturn: 5774 case DeclaratorContext::TrailingReturnVar: 5775 case DeclaratorContext::TemplateArg: 5776 case DeclaratorContext::TemplateTypeArg: 5777 // FIXME: We may want to allow parameter packs in block-literal contexts 5778 // in the future. 5779 S.Diag(D.getEllipsisLoc(), 5780 diag::err_ellipsis_in_declarator_not_parameter); 5781 D.setEllipsisLoc(SourceLocation()); 5782 break; 5783 } 5784 } 5785 5786 assert(!T.isNull() && "T must not be null at the end of this function"); 5787 if (D.isInvalidType()) 5788 return Context.getTrivialTypeSourceInfo(T); 5789 5790 return GetTypeSourceInfoForDeclarator(state, T, TInfo); 5791 } 5792 5793 /// GetTypeForDeclarator - Convert the type for the specified 5794 /// declarator to Type instances. 5795 /// 5796 /// The result of this call will never be null, but the associated 5797 /// type may be a null type if there's an unrecoverable error. 5798 TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) { 5799 // Determine the type of the declarator. Not all forms of declarator 5800 // have a type. 5801 5802 TypeProcessingState state(*this, D); 5803 5804 TypeSourceInfo *ReturnTypeInfo = nullptr; 5805 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); 5806 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount) 5807 inferARCWriteback(state, T); 5808 5809 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo); 5810 } 5811 5812 static void transferARCOwnershipToDeclSpec(Sema &S, 5813 QualType &declSpecTy, 5814 Qualifiers::ObjCLifetime ownership) { 5815 if (declSpecTy->isObjCRetainableType() && 5816 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) { 5817 Qualifiers qs; 5818 qs.addObjCLifetime(ownership); 5819 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs); 5820 } 5821 } 5822 5823 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, 5824 Qualifiers::ObjCLifetime ownership, 5825 unsigned chunkIndex) { 5826 Sema &S = state.getSema(); 5827 Declarator &D = state.getDeclarator(); 5828 5829 // Look for an explicit lifetime attribute. 5830 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex); 5831 if (chunk.getAttrs().hasAttribute(ParsedAttr::AT_ObjCOwnership)) 5832 return; 5833 5834 const char *attrStr = nullptr; 5835 switch (ownership) { 5836 case Qualifiers::OCL_None: llvm_unreachable("no ownership!"); 5837 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break; 5838 case Qualifiers::OCL_Strong: attrStr = "strong"; break; 5839 case Qualifiers::OCL_Weak: attrStr = "weak"; break; 5840 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break; 5841 } 5842 5843 IdentifierLoc *Arg = new (S.Context) IdentifierLoc; 5844 Arg->Ident = &S.Context.Idents.get(attrStr); 5845 Arg->Loc = SourceLocation(); 5846 5847 ArgsUnion Args(Arg); 5848 5849 // If there wasn't one, add one (with an invalid source location 5850 // so that we don't make an AttributedType for it). 5851 ParsedAttr *attr = D.getAttributePool().create( 5852 &S.Context.Idents.get("objc_ownership"), SourceLocation(), 5853 /*scope*/ nullptr, SourceLocation(), 5854 /*args*/ &Args, 1, ParsedAttr::AS_GNU); 5855 chunk.getAttrs().addAtEnd(attr); 5856 // TODO: mark whether we did this inference? 5857 } 5858 5859 /// Used for transferring ownership in casts resulting in l-values. 5860 static void transferARCOwnership(TypeProcessingState &state, 5861 QualType &declSpecTy, 5862 Qualifiers::ObjCLifetime ownership) { 5863 Sema &S = state.getSema(); 5864 Declarator &D = state.getDeclarator(); 5865 5866 int inner = -1; 5867 bool hasIndirection = false; 5868 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 5869 DeclaratorChunk &chunk = D.getTypeObject(i); 5870 switch (chunk.Kind) { 5871 case DeclaratorChunk::Paren: 5872 // Ignore parens. 5873 break; 5874 5875 case DeclaratorChunk::Array: 5876 case DeclaratorChunk::Reference: 5877 case DeclaratorChunk::Pointer: 5878 if (inner != -1) 5879 hasIndirection = true; 5880 inner = i; 5881 break; 5882 5883 case DeclaratorChunk::BlockPointer: 5884 if (inner != -1) 5885 transferARCOwnershipToDeclaratorChunk(state, ownership, i); 5886 return; 5887 5888 case DeclaratorChunk::Function: 5889 case DeclaratorChunk::MemberPointer: 5890 case DeclaratorChunk::Pipe: 5891 return; 5892 } 5893 } 5894 5895 if (inner == -1) 5896 return; 5897 5898 DeclaratorChunk &chunk = D.getTypeObject(inner); 5899 if (chunk.Kind == DeclaratorChunk::Pointer) { 5900 if (declSpecTy->isObjCRetainableType()) 5901 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); 5902 if (declSpecTy->isObjCObjectType() && hasIndirection) 5903 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner); 5904 } else { 5905 assert(chunk.Kind == DeclaratorChunk::Array || 5906 chunk.Kind == DeclaratorChunk::Reference); 5907 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); 5908 } 5909 } 5910 5911 TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) { 5912 TypeProcessingState state(*this, D); 5913 5914 TypeSourceInfo *ReturnTypeInfo = nullptr; 5915 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); 5916 5917 if (getLangOpts().ObjC) { 5918 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy); 5919 if (ownership != Qualifiers::OCL_None) 5920 transferARCOwnership(state, declSpecTy, ownership); 5921 } 5922 5923 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo); 5924 } 5925 5926 static void fillAttributedTypeLoc(AttributedTypeLoc TL, 5927 TypeProcessingState &State) { 5928 TL.setAttr(State.takeAttrForAttributedType(TL.getTypePtr())); 5929 } 5930 5931 namespace { 5932 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> { 5933 Sema &SemaRef; 5934 ASTContext &Context; 5935 TypeProcessingState &State; 5936 const DeclSpec &DS; 5937 5938 public: 5939 TypeSpecLocFiller(Sema &S, ASTContext &Context, TypeProcessingState &State, 5940 const DeclSpec &DS) 5941 : SemaRef(S), Context(Context), State(State), DS(DS) {} 5942 5943 void VisitAttributedTypeLoc(AttributedTypeLoc TL) { 5944 Visit(TL.getModifiedLoc()); 5945 fillAttributedTypeLoc(TL, State); 5946 } 5947 void VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) { 5948 Visit(TL.getWrappedLoc()); 5949 } 5950 void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) { 5951 Visit(TL.getInnerLoc()); 5952 TL.setExpansionLoc( 5953 State.getExpansionLocForMacroQualifiedType(TL.getTypePtr())); 5954 } 5955 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 5956 Visit(TL.getUnqualifiedLoc()); 5957 } 5958 // Allow to fill pointee's type locations, e.g., 5959 // int __attr * __attr * __attr *p; 5960 void VisitPointerTypeLoc(PointerTypeLoc TL) { Visit(TL.getNextTypeLoc()); } 5961 void VisitTypedefTypeLoc(TypedefTypeLoc TL) { 5962 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 5963 } 5964 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { 5965 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 5966 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires 5967 // addition field. What we have is good enough for display of location 5968 // of 'fixit' on interface name. 5969 TL.setNameEndLoc(DS.getEndLoc()); 5970 } 5971 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { 5972 TypeSourceInfo *RepTInfo = nullptr; 5973 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo); 5974 TL.copy(RepTInfo->getTypeLoc()); 5975 } 5976 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 5977 TypeSourceInfo *RepTInfo = nullptr; 5978 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo); 5979 TL.copy(RepTInfo->getTypeLoc()); 5980 } 5981 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) { 5982 TypeSourceInfo *TInfo = nullptr; 5983 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 5984 5985 // If we got no declarator info from previous Sema routines, 5986 // just fill with the typespec loc. 5987 if (!TInfo) { 5988 TL.initialize(Context, DS.getTypeSpecTypeNameLoc()); 5989 return; 5990 } 5991 5992 TypeLoc OldTL = TInfo->getTypeLoc(); 5993 if (TInfo->getType()->getAs<ElaboratedType>()) { 5994 ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>(); 5995 TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc() 5996 .castAs<TemplateSpecializationTypeLoc>(); 5997 TL.copy(NamedTL); 5998 } else { 5999 TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>()); 6000 assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc()); 6001 } 6002 6003 } 6004 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { 6005 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr); 6006 TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); 6007 TL.setParensRange(DS.getTypeofParensRange()); 6008 } 6009 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { 6010 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType); 6011 TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); 6012 TL.setParensRange(DS.getTypeofParensRange()); 6013 assert(DS.getRepAsType()); 6014 TypeSourceInfo *TInfo = nullptr; 6015 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 6016 TL.setUnderlyingTInfo(TInfo); 6017 } 6018 void VisitDecltypeTypeLoc(DecltypeTypeLoc TL) { 6019 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype); 6020 TL.setDecltypeLoc(DS.getTypeSpecTypeLoc()); 6021 TL.setRParenLoc(DS.getTypeofParensRange().getEnd()); 6022 } 6023 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) { 6024 // FIXME: This holds only because we only have one unary transform. 6025 assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType); 6026 TL.setKWLoc(DS.getTypeSpecTypeLoc()); 6027 TL.setParensRange(DS.getTypeofParensRange()); 6028 assert(DS.getRepAsType()); 6029 TypeSourceInfo *TInfo = nullptr; 6030 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 6031 TL.setUnderlyingTInfo(TInfo); 6032 } 6033 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { 6034 // By default, use the source location of the type specifier. 6035 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc()); 6036 if (TL.needsExtraLocalData()) { 6037 // Set info for the written builtin specifiers. 6038 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs(); 6039 // Try to have a meaningful source location. 6040 if (TL.getWrittenSignSpec() != TypeSpecifierSign::Unspecified) 6041 TL.expandBuiltinRange(DS.getTypeSpecSignLoc()); 6042 if (TL.getWrittenWidthSpec() != TypeSpecifierWidth::Unspecified) 6043 TL.expandBuiltinRange(DS.getTypeSpecWidthRange()); 6044 } 6045 } 6046 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { 6047 ElaboratedTypeKeyword Keyword 6048 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType()); 6049 if (DS.getTypeSpecType() == TST_typename) { 6050 TypeSourceInfo *TInfo = nullptr; 6051 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 6052 if (TInfo) { 6053 TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>()); 6054 return; 6055 } 6056 } 6057 TL.setElaboratedKeywordLoc(Keyword != ETK_None 6058 ? DS.getTypeSpecTypeLoc() 6059 : SourceLocation()); 6060 const CXXScopeSpec& SS = DS.getTypeSpecScope(); 6061 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 6062 Visit(TL.getNextTypeLoc().getUnqualifiedLoc()); 6063 } 6064 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { 6065 assert(DS.getTypeSpecType() == TST_typename); 6066 TypeSourceInfo *TInfo = nullptr; 6067 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 6068 assert(TInfo); 6069 TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>()); 6070 } 6071 void VisitDependentTemplateSpecializationTypeLoc( 6072 DependentTemplateSpecializationTypeLoc TL) { 6073 assert(DS.getTypeSpecType() == TST_typename); 6074 TypeSourceInfo *TInfo = nullptr; 6075 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 6076 assert(TInfo); 6077 TL.copy( 6078 TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>()); 6079 } 6080 void VisitAutoTypeLoc(AutoTypeLoc TL) { 6081 assert(DS.getTypeSpecType() == TST_auto || 6082 DS.getTypeSpecType() == TST_decltype_auto || 6083 DS.getTypeSpecType() == TST_auto_type || 6084 DS.getTypeSpecType() == TST_unspecified); 6085 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 6086 if (DS.getTypeSpecType() == TST_decltype_auto) 6087 TL.setRParenLoc(DS.getTypeofParensRange().getEnd()); 6088 if (!DS.isConstrainedAuto()) 6089 return; 6090 TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId(); 6091 if (!TemplateId) 6092 return; 6093 if (DS.getTypeSpecScope().isNotEmpty()) 6094 TL.setNestedNameSpecifierLoc( 6095 DS.getTypeSpecScope().getWithLocInContext(Context)); 6096 else 6097 TL.setNestedNameSpecifierLoc(NestedNameSpecifierLoc()); 6098 TL.setTemplateKWLoc(TemplateId->TemplateKWLoc); 6099 TL.setConceptNameLoc(TemplateId->TemplateNameLoc); 6100 TL.setFoundDecl(nullptr); 6101 TL.setLAngleLoc(TemplateId->LAngleLoc); 6102 TL.setRAngleLoc(TemplateId->RAngleLoc); 6103 if (TemplateId->NumArgs == 0) 6104 return; 6105 TemplateArgumentListInfo TemplateArgsInfo; 6106 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 6107 TemplateId->NumArgs); 6108 SemaRef.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo); 6109 for (unsigned I = 0; I < TemplateId->NumArgs; ++I) 6110 TL.setArgLocInfo(I, TemplateArgsInfo.arguments()[I].getLocInfo()); 6111 } 6112 void VisitTagTypeLoc(TagTypeLoc TL) { 6113 TL.setNameLoc(DS.getTypeSpecTypeNameLoc()); 6114 } 6115 void VisitAtomicTypeLoc(AtomicTypeLoc TL) { 6116 // An AtomicTypeLoc can come from either an _Atomic(...) type specifier 6117 // or an _Atomic qualifier. 6118 if (DS.getTypeSpecType() == DeclSpec::TST_atomic) { 6119 TL.setKWLoc(DS.getTypeSpecTypeLoc()); 6120 TL.setParensRange(DS.getTypeofParensRange()); 6121 6122 TypeSourceInfo *TInfo = nullptr; 6123 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 6124 assert(TInfo); 6125 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc()); 6126 } else { 6127 TL.setKWLoc(DS.getAtomicSpecLoc()); 6128 // No parens, to indicate this was spelled as an _Atomic qualifier. 6129 TL.setParensRange(SourceRange()); 6130 Visit(TL.getValueLoc()); 6131 } 6132 } 6133 6134 void VisitPipeTypeLoc(PipeTypeLoc TL) { 6135 TL.setKWLoc(DS.getTypeSpecTypeLoc()); 6136 6137 TypeSourceInfo *TInfo = nullptr; 6138 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 6139 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc()); 6140 } 6141 6142 void VisitExtIntTypeLoc(BitIntTypeLoc TL) { 6143 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 6144 } 6145 6146 void VisitDependentExtIntTypeLoc(DependentBitIntTypeLoc TL) { 6147 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 6148 } 6149 6150 void VisitTypeLoc(TypeLoc TL) { 6151 // FIXME: add other typespec types and change this to an assert. 6152 TL.initialize(Context, DS.getTypeSpecTypeLoc()); 6153 } 6154 }; 6155 6156 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> { 6157 ASTContext &Context; 6158 TypeProcessingState &State; 6159 const DeclaratorChunk &Chunk; 6160 6161 public: 6162 DeclaratorLocFiller(ASTContext &Context, TypeProcessingState &State, 6163 const DeclaratorChunk &Chunk) 6164 : Context(Context), State(State), Chunk(Chunk) {} 6165 6166 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 6167 llvm_unreachable("qualified type locs not expected here!"); 6168 } 6169 void VisitDecayedTypeLoc(DecayedTypeLoc TL) { 6170 llvm_unreachable("decayed type locs not expected here!"); 6171 } 6172 6173 void VisitAttributedTypeLoc(AttributedTypeLoc TL) { 6174 fillAttributedTypeLoc(TL, State); 6175 } 6176 void VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) { 6177 // nothing 6178 } 6179 void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) { 6180 // nothing 6181 } 6182 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { 6183 assert(Chunk.Kind == DeclaratorChunk::BlockPointer); 6184 TL.setCaretLoc(Chunk.Loc); 6185 } 6186 void VisitPointerTypeLoc(PointerTypeLoc TL) { 6187 assert(Chunk.Kind == DeclaratorChunk::Pointer); 6188 TL.setStarLoc(Chunk.Loc); 6189 } 6190 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 6191 assert(Chunk.Kind == DeclaratorChunk::Pointer); 6192 TL.setStarLoc(Chunk.Loc); 6193 } 6194 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { 6195 assert(Chunk.Kind == DeclaratorChunk::MemberPointer); 6196 const CXXScopeSpec& SS = Chunk.Mem.Scope(); 6197 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context); 6198 6199 const Type* ClsTy = TL.getClass(); 6200 QualType ClsQT = QualType(ClsTy, 0); 6201 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0); 6202 // Now copy source location info into the type loc component. 6203 TypeLoc ClsTL = ClsTInfo->getTypeLoc(); 6204 switch (NNSLoc.getNestedNameSpecifier()->getKind()) { 6205 case NestedNameSpecifier::Identifier: 6206 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc"); 6207 { 6208 DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>(); 6209 DNTLoc.setElaboratedKeywordLoc(SourceLocation()); 6210 DNTLoc.setQualifierLoc(NNSLoc.getPrefix()); 6211 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc()); 6212 } 6213 break; 6214 6215 case NestedNameSpecifier::TypeSpec: 6216 case NestedNameSpecifier::TypeSpecWithTemplate: 6217 if (isa<ElaboratedType>(ClsTy)) { 6218 ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>(); 6219 ETLoc.setElaboratedKeywordLoc(SourceLocation()); 6220 ETLoc.setQualifierLoc(NNSLoc.getPrefix()); 6221 TypeLoc NamedTL = ETLoc.getNamedTypeLoc(); 6222 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc()); 6223 } else { 6224 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc()); 6225 } 6226 break; 6227 6228 case NestedNameSpecifier::Namespace: 6229 case NestedNameSpecifier::NamespaceAlias: 6230 case NestedNameSpecifier::Global: 6231 case NestedNameSpecifier::Super: 6232 llvm_unreachable("Nested-name-specifier must name a type"); 6233 } 6234 6235 // Finally fill in MemberPointerLocInfo fields. 6236 TL.setStarLoc(Chunk.Mem.StarLoc); 6237 TL.setClassTInfo(ClsTInfo); 6238 } 6239 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { 6240 assert(Chunk.Kind == DeclaratorChunk::Reference); 6241 // 'Amp' is misleading: this might have been originally 6242 /// spelled with AmpAmp. 6243 TL.setAmpLoc(Chunk.Loc); 6244 } 6245 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { 6246 assert(Chunk.Kind == DeclaratorChunk::Reference); 6247 assert(!Chunk.Ref.LValueRef); 6248 TL.setAmpAmpLoc(Chunk.Loc); 6249 } 6250 void VisitArrayTypeLoc(ArrayTypeLoc TL) { 6251 assert(Chunk.Kind == DeclaratorChunk::Array); 6252 TL.setLBracketLoc(Chunk.Loc); 6253 TL.setRBracketLoc(Chunk.EndLoc); 6254 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts)); 6255 } 6256 void VisitFunctionTypeLoc(FunctionTypeLoc TL) { 6257 assert(Chunk.Kind == DeclaratorChunk::Function); 6258 TL.setLocalRangeBegin(Chunk.Loc); 6259 TL.setLocalRangeEnd(Chunk.EndLoc); 6260 6261 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun; 6262 TL.setLParenLoc(FTI.getLParenLoc()); 6263 TL.setRParenLoc(FTI.getRParenLoc()); 6264 for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) { 6265 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 6266 TL.setParam(tpi++, Param); 6267 } 6268 TL.setExceptionSpecRange(FTI.getExceptionSpecRange()); 6269 } 6270 void VisitParenTypeLoc(ParenTypeLoc TL) { 6271 assert(Chunk.Kind == DeclaratorChunk::Paren); 6272 TL.setLParenLoc(Chunk.Loc); 6273 TL.setRParenLoc(Chunk.EndLoc); 6274 } 6275 void VisitPipeTypeLoc(PipeTypeLoc TL) { 6276 assert(Chunk.Kind == DeclaratorChunk::Pipe); 6277 TL.setKWLoc(Chunk.Loc); 6278 } 6279 void VisitBitIntTypeLoc(BitIntTypeLoc TL) { 6280 TL.setNameLoc(Chunk.Loc); 6281 } 6282 void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) { 6283 TL.setExpansionLoc(Chunk.Loc); 6284 } 6285 void VisitVectorTypeLoc(VectorTypeLoc TL) { TL.setNameLoc(Chunk.Loc); } 6286 void VisitDependentVectorTypeLoc(DependentVectorTypeLoc TL) { 6287 TL.setNameLoc(Chunk.Loc); 6288 } 6289 void VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) { 6290 TL.setNameLoc(Chunk.Loc); 6291 } 6292 void 6293 VisitDependentSizedExtVectorTypeLoc(DependentSizedExtVectorTypeLoc TL) { 6294 TL.setNameLoc(Chunk.Loc); 6295 } 6296 6297 void VisitTypeLoc(TypeLoc TL) { 6298 llvm_unreachable("unsupported TypeLoc kind in declarator!"); 6299 } 6300 }; 6301 } // end anonymous namespace 6302 6303 static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) { 6304 SourceLocation Loc; 6305 switch (Chunk.Kind) { 6306 case DeclaratorChunk::Function: 6307 case DeclaratorChunk::Array: 6308 case DeclaratorChunk::Paren: 6309 case DeclaratorChunk::Pipe: 6310 llvm_unreachable("cannot be _Atomic qualified"); 6311 6312 case DeclaratorChunk::Pointer: 6313 Loc = Chunk.Ptr.AtomicQualLoc; 6314 break; 6315 6316 case DeclaratorChunk::BlockPointer: 6317 case DeclaratorChunk::Reference: 6318 case DeclaratorChunk::MemberPointer: 6319 // FIXME: Provide a source location for the _Atomic keyword. 6320 break; 6321 } 6322 6323 ATL.setKWLoc(Loc); 6324 ATL.setParensRange(SourceRange()); 6325 } 6326 6327 static void 6328 fillDependentAddressSpaceTypeLoc(DependentAddressSpaceTypeLoc DASTL, 6329 const ParsedAttributesView &Attrs) { 6330 for (const ParsedAttr &AL : Attrs) { 6331 if (AL.getKind() == ParsedAttr::AT_AddressSpace) { 6332 DASTL.setAttrNameLoc(AL.getLoc()); 6333 DASTL.setAttrExprOperand(AL.getArgAsExpr(0)); 6334 DASTL.setAttrOperandParensRange(SourceRange()); 6335 return; 6336 } 6337 } 6338 6339 llvm_unreachable( 6340 "no address_space attribute found at the expected location!"); 6341 } 6342 6343 static void fillMatrixTypeLoc(MatrixTypeLoc MTL, 6344 const ParsedAttributesView &Attrs) { 6345 for (const ParsedAttr &AL : Attrs) { 6346 if (AL.getKind() == ParsedAttr::AT_MatrixType) { 6347 MTL.setAttrNameLoc(AL.getLoc()); 6348 MTL.setAttrRowOperand(AL.getArgAsExpr(0)); 6349 MTL.setAttrColumnOperand(AL.getArgAsExpr(1)); 6350 MTL.setAttrOperandParensRange(SourceRange()); 6351 return; 6352 } 6353 } 6354 6355 llvm_unreachable("no matrix_type attribute found at the expected location!"); 6356 } 6357 6358 /// Create and instantiate a TypeSourceInfo with type source information. 6359 /// 6360 /// \param T QualType referring to the type as written in source code. 6361 /// 6362 /// \param ReturnTypeInfo For declarators whose return type does not show 6363 /// up in the normal place in the declaration specifiers (such as a C++ 6364 /// conversion function), this pointer will refer to a type source information 6365 /// for that return type. 6366 static TypeSourceInfo * 6367 GetTypeSourceInfoForDeclarator(TypeProcessingState &State, 6368 QualType T, TypeSourceInfo *ReturnTypeInfo) { 6369 Sema &S = State.getSema(); 6370 Declarator &D = State.getDeclarator(); 6371 6372 TypeSourceInfo *TInfo = S.Context.CreateTypeSourceInfo(T); 6373 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc(); 6374 6375 // Handle parameter packs whose type is a pack expansion. 6376 if (isa<PackExpansionType>(T)) { 6377 CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc()); 6378 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); 6379 } 6380 6381 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 6382 // An AtomicTypeLoc might be produced by an atomic qualifier in this 6383 // declarator chunk. 6384 if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) { 6385 fillAtomicQualLoc(ATL, D.getTypeObject(i)); 6386 CurrTL = ATL.getValueLoc().getUnqualifiedLoc(); 6387 } 6388 6389 while (MacroQualifiedTypeLoc TL = CurrTL.getAs<MacroQualifiedTypeLoc>()) { 6390 TL.setExpansionLoc( 6391 State.getExpansionLocForMacroQualifiedType(TL.getTypePtr())); 6392 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); 6393 } 6394 6395 while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) { 6396 fillAttributedTypeLoc(TL, State); 6397 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); 6398 } 6399 6400 while (DependentAddressSpaceTypeLoc TL = 6401 CurrTL.getAs<DependentAddressSpaceTypeLoc>()) { 6402 fillDependentAddressSpaceTypeLoc(TL, D.getTypeObject(i).getAttrs()); 6403 CurrTL = TL.getPointeeTypeLoc().getUnqualifiedLoc(); 6404 } 6405 6406 if (MatrixTypeLoc TL = CurrTL.getAs<MatrixTypeLoc>()) 6407 fillMatrixTypeLoc(TL, D.getTypeObject(i).getAttrs()); 6408 6409 // FIXME: Ordering here? 6410 while (AdjustedTypeLoc TL = CurrTL.getAs<AdjustedTypeLoc>()) 6411 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); 6412 6413 DeclaratorLocFiller(S.Context, State, D.getTypeObject(i)).Visit(CurrTL); 6414 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); 6415 } 6416 6417 // If we have different source information for the return type, use 6418 // that. This really only applies to C++ conversion functions. 6419 if (ReturnTypeInfo) { 6420 TypeLoc TL = ReturnTypeInfo->getTypeLoc(); 6421 assert(TL.getFullDataSize() == CurrTL.getFullDataSize()); 6422 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize()); 6423 } else { 6424 TypeSpecLocFiller(S, S.Context, State, D.getDeclSpec()).Visit(CurrTL); 6425 } 6426 6427 return TInfo; 6428 } 6429 6430 /// Create a LocInfoType to hold the given QualType and TypeSourceInfo. 6431 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) { 6432 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser 6433 // and Sema during declaration parsing. Try deallocating/caching them when 6434 // it's appropriate, instead of allocating them and keeping them around. 6435 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType), 6436 TypeAlignment); 6437 new (LocT) LocInfoType(T, TInfo); 6438 assert(LocT->getTypeClass() != T->getTypeClass() && 6439 "LocInfoType's TypeClass conflicts with an existing Type class"); 6440 return ParsedType::make(QualType(LocT, 0)); 6441 } 6442 6443 void LocInfoType::getAsStringInternal(std::string &Str, 6444 const PrintingPolicy &Policy) const { 6445 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*" 6446 " was used directly instead of getting the QualType through" 6447 " GetTypeFromParser"); 6448 } 6449 6450 TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) { 6451 // C99 6.7.6: Type names have no identifier. This is already validated by 6452 // the parser. 6453 assert(D.getIdentifier() == nullptr && 6454 "Type name should have no identifier!"); 6455 6456 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 6457 QualType T = TInfo->getType(); 6458 if (D.isInvalidType()) 6459 return true; 6460 6461 // Make sure there are no unused decl attributes on the declarator. 6462 // We don't want to do this for ObjC parameters because we're going 6463 // to apply them to the actual parameter declaration. 6464 // Likewise, we don't want to do this for alias declarations, because 6465 // we are actually going to build a declaration from this eventually. 6466 if (D.getContext() != DeclaratorContext::ObjCParameter && 6467 D.getContext() != DeclaratorContext::AliasDecl && 6468 D.getContext() != DeclaratorContext::AliasTemplate) 6469 checkUnusedDeclAttributes(D); 6470 6471 if (getLangOpts().CPlusPlus) { 6472 // Check that there are no default arguments (C++ only). 6473 CheckExtraCXXDefaultArguments(D); 6474 } 6475 6476 return CreateParsedType(T, TInfo); 6477 } 6478 6479 ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) { 6480 QualType T = Context.getObjCInstanceType(); 6481 TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 6482 return CreateParsedType(T, TInfo); 6483 } 6484 6485 //===----------------------------------------------------------------------===// 6486 // Type Attribute Processing 6487 //===----------------------------------------------------------------------===// 6488 6489 /// Build an AddressSpace index from a constant expression and diagnose any 6490 /// errors related to invalid address_spaces. Returns true on successfully 6491 /// building an AddressSpace index. 6492 static bool BuildAddressSpaceIndex(Sema &S, LangAS &ASIdx, 6493 const Expr *AddrSpace, 6494 SourceLocation AttrLoc) { 6495 if (!AddrSpace->isValueDependent()) { 6496 Optional<llvm::APSInt> OptAddrSpace = 6497 AddrSpace->getIntegerConstantExpr(S.Context); 6498 if (!OptAddrSpace) { 6499 S.Diag(AttrLoc, diag::err_attribute_argument_type) 6500 << "'address_space'" << AANT_ArgumentIntegerConstant 6501 << AddrSpace->getSourceRange(); 6502 return false; 6503 } 6504 llvm::APSInt &addrSpace = *OptAddrSpace; 6505 6506 // Bounds checking. 6507 if (addrSpace.isSigned()) { 6508 if (addrSpace.isNegative()) { 6509 S.Diag(AttrLoc, diag::err_attribute_address_space_negative) 6510 << AddrSpace->getSourceRange(); 6511 return false; 6512 } 6513 addrSpace.setIsSigned(false); 6514 } 6515 6516 llvm::APSInt max(addrSpace.getBitWidth()); 6517 max = 6518 Qualifiers::MaxAddressSpace - (unsigned)LangAS::FirstTargetAddressSpace; 6519 6520 if (addrSpace > max) { 6521 S.Diag(AttrLoc, diag::err_attribute_address_space_too_high) 6522 << (unsigned)max.getZExtValue() << AddrSpace->getSourceRange(); 6523 return false; 6524 } 6525 6526 ASIdx = 6527 getLangASFromTargetAS(static_cast<unsigned>(addrSpace.getZExtValue())); 6528 return true; 6529 } 6530 6531 // Default value for DependentAddressSpaceTypes 6532 ASIdx = LangAS::Default; 6533 return true; 6534 } 6535 6536 /// BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an expression 6537 /// is uninstantiated. If instantiated it will apply the appropriate address 6538 /// space to the type. This function allows dependent template variables to be 6539 /// used in conjunction with the address_space attribute 6540 QualType Sema::BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace, 6541 SourceLocation AttrLoc) { 6542 if (!AddrSpace->isValueDependent()) { 6543 if (DiagnoseMultipleAddrSpaceAttributes(*this, T.getAddressSpace(), ASIdx, 6544 AttrLoc)) 6545 return QualType(); 6546 6547 return Context.getAddrSpaceQualType(T, ASIdx); 6548 } 6549 6550 // A check with similar intentions as checking if a type already has an 6551 // address space except for on a dependent types, basically if the 6552 // current type is already a DependentAddressSpaceType then its already 6553 // lined up to have another address space on it and we can't have 6554 // multiple address spaces on the one pointer indirection 6555 if (T->getAs<DependentAddressSpaceType>()) { 6556 Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers); 6557 return QualType(); 6558 } 6559 6560 return Context.getDependentAddressSpaceType(T, AddrSpace, AttrLoc); 6561 } 6562 6563 QualType Sema::BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace, 6564 SourceLocation AttrLoc) { 6565 LangAS ASIdx; 6566 if (!BuildAddressSpaceIndex(*this, ASIdx, AddrSpace, AttrLoc)) 6567 return QualType(); 6568 return BuildAddressSpaceAttr(T, ASIdx, AddrSpace, AttrLoc); 6569 } 6570 6571 static void HandleBTFTypeTagAttribute(QualType &Type, const ParsedAttr &Attr, 6572 TypeProcessingState &State) { 6573 Sema &S = State.getSema(); 6574 6575 // Check the number of attribute arguments. 6576 if (Attr.getNumArgs() != 1) { 6577 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 6578 << Attr << 1; 6579 Attr.setInvalid(); 6580 return; 6581 } 6582 6583 // Ensure the argument is a string. 6584 auto *StrLiteral = dyn_cast<StringLiteral>(Attr.getArgAsExpr(0)); 6585 if (!StrLiteral) { 6586 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) 6587 << Attr << AANT_ArgumentString; 6588 Attr.setInvalid(); 6589 return; 6590 } 6591 6592 ASTContext &Ctx = S.Context; 6593 StringRef BTFTypeTag = StrLiteral->getString(); 6594 Type = State.getBTFTagAttributedType( 6595 ::new (Ctx) BTFTypeTagAttr(Ctx, Attr, BTFTypeTag), Type); 6596 } 6597 6598 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the 6599 /// specified type. The attribute contains 1 argument, the id of the address 6600 /// space for the type. 6601 static void HandleAddressSpaceTypeAttribute(QualType &Type, 6602 const ParsedAttr &Attr, 6603 TypeProcessingState &State) { 6604 Sema &S = State.getSema(); 6605 6606 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be 6607 // qualified by an address-space qualifier." 6608 if (Type->isFunctionType()) { 6609 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type); 6610 Attr.setInvalid(); 6611 return; 6612 } 6613 6614 LangAS ASIdx; 6615 if (Attr.getKind() == ParsedAttr::AT_AddressSpace) { 6616 6617 // Check the attribute arguments. 6618 if (Attr.getNumArgs() != 1) { 6619 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr 6620 << 1; 6621 Attr.setInvalid(); 6622 return; 6623 } 6624 6625 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); 6626 LangAS ASIdx; 6627 if (!BuildAddressSpaceIndex(S, ASIdx, ASArgExpr, Attr.getLoc())) { 6628 Attr.setInvalid(); 6629 return; 6630 } 6631 6632 ASTContext &Ctx = S.Context; 6633 auto *ASAttr = 6634 ::new (Ctx) AddressSpaceAttr(Ctx, Attr, static_cast<unsigned>(ASIdx)); 6635 6636 // If the expression is not value dependent (not templated), then we can 6637 // apply the address space qualifiers just to the equivalent type. 6638 // Otherwise, we make an AttributedType with the modified and equivalent 6639 // type the same, and wrap it in a DependentAddressSpaceType. When this 6640 // dependent type is resolved, the qualifier is added to the equivalent type 6641 // later. 6642 QualType T; 6643 if (!ASArgExpr->isValueDependent()) { 6644 QualType EquivType = 6645 S.BuildAddressSpaceAttr(Type, ASIdx, ASArgExpr, Attr.getLoc()); 6646 if (EquivType.isNull()) { 6647 Attr.setInvalid(); 6648 return; 6649 } 6650 T = State.getAttributedType(ASAttr, Type, EquivType); 6651 } else { 6652 T = State.getAttributedType(ASAttr, Type, Type); 6653 T = S.BuildAddressSpaceAttr(T, ASIdx, ASArgExpr, Attr.getLoc()); 6654 } 6655 6656 if (!T.isNull()) 6657 Type = T; 6658 else 6659 Attr.setInvalid(); 6660 } else { 6661 // The keyword-based type attributes imply which address space to use. 6662 ASIdx = S.getLangOpts().SYCLIsDevice ? Attr.asSYCLLangAS() 6663 : Attr.asOpenCLLangAS(); 6664 6665 if (ASIdx == LangAS::Default) 6666 llvm_unreachable("Invalid address space"); 6667 6668 if (DiagnoseMultipleAddrSpaceAttributes(S, Type.getAddressSpace(), ASIdx, 6669 Attr.getLoc())) { 6670 Attr.setInvalid(); 6671 return; 6672 } 6673 6674 Type = S.Context.getAddrSpaceQualType(Type, ASIdx); 6675 } 6676 } 6677 6678 /// handleObjCOwnershipTypeAttr - Process an objc_ownership 6679 /// attribute on the specified type. 6680 /// 6681 /// Returns 'true' if the attribute was handled. 6682 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state, 6683 ParsedAttr &attr, QualType &type) { 6684 bool NonObjCPointer = false; 6685 6686 if (!type->isDependentType() && !type->isUndeducedType()) { 6687 if (const PointerType *ptr = type->getAs<PointerType>()) { 6688 QualType pointee = ptr->getPointeeType(); 6689 if (pointee->isObjCRetainableType() || pointee->isPointerType()) 6690 return false; 6691 // It is important not to lose the source info that there was an attribute 6692 // applied to non-objc pointer. We will create an attributed type but 6693 // its type will be the same as the original type. 6694 NonObjCPointer = true; 6695 } else if (!type->isObjCRetainableType()) { 6696 return false; 6697 } 6698 6699 // Don't accept an ownership attribute in the declspec if it would 6700 // just be the return type of a block pointer. 6701 if (state.isProcessingDeclSpec()) { 6702 Declarator &D = state.getDeclarator(); 6703 if (maybeMovePastReturnType(D, D.getNumTypeObjects(), 6704 /*onlyBlockPointers=*/true)) 6705 return false; 6706 } 6707 } 6708 6709 Sema &S = state.getSema(); 6710 SourceLocation AttrLoc = attr.getLoc(); 6711 if (AttrLoc.isMacroID()) 6712 AttrLoc = 6713 S.getSourceManager().getImmediateExpansionRange(AttrLoc).getBegin(); 6714 6715 if (!attr.isArgIdent(0)) { 6716 S.Diag(AttrLoc, diag::err_attribute_argument_type) << attr 6717 << AANT_ArgumentString; 6718 attr.setInvalid(); 6719 return true; 6720 } 6721 6722 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident; 6723 Qualifiers::ObjCLifetime lifetime; 6724 if (II->isStr("none")) 6725 lifetime = Qualifiers::OCL_ExplicitNone; 6726 else if (II->isStr("strong")) 6727 lifetime = Qualifiers::OCL_Strong; 6728 else if (II->isStr("weak")) 6729 lifetime = Qualifiers::OCL_Weak; 6730 else if (II->isStr("autoreleasing")) 6731 lifetime = Qualifiers::OCL_Autoreleasing; 6732 else { 6733 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported) << attr << II; 6734 attr.setInvalid(); 6735 return true; 6736 } 6737 6738 // Just ignore lifetime attributes other than __weak and __unsafe_unretained 6739 // outside of ARC mode. 6740 if (!S.getLangOpts().ObjCAutoRefCount && 6741 lifetime != Qualifiers::OCL_Weak && 6742 lifetime != Qualifiers::OCL_ExplicitNone) { 6743 return true; 6744 } 6745 6746 SplitQualType underlyingType = type.split(); 6747 6748 // Check for redundant/conflicting ownership qualifiers. 6749 if (Qualifiers::ObjCLifetime previousLifetime 6750 = type.getQualifiers().getObjCLifetime()) { 6751 // If it's written directly, that's an error. 6752 if (S.Context.hasDirectOwnershipQualifier(type)) { 6753 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant) 6754 << type; 6755 return true; 6756 } 6757 6758 // Otherwise, if the qualifiers actually conflict, pull sugar off 6759 // and remove the ObjCLifetime qualifiers. 6760 if (previousLifetime != lifetime) { 6761 // It's possible to have multiple local ObjCLifetime qualifiers. We 6762 // can't stop after we reach a type that is directly qualified. 6763 const Type *prevTy = nullptr; 6764 while (!prevTy || prevTy != underlyingType.Ty) { 6765 prevTy = underlyingType.Ty; 6766 underlyingType = underlyingType.getSingleStepDesugaredType(); 6767 } 6768 underlyingType.Quals.removeObjCLifetime(); 6769 } 6770 } 6771 6772 underlyingType.Quals.addObjCLifetime(lifetime); 6773 6774 if (NonObjCPointer) { 6775 StringRef name = attr.getAttrName()->getName(); 6776 switch (lifetime) { 6777 case Qualifiers::OCL_None: 6778 case Qualifiers::OCL_ExplicitNone: 6779 break; 6780 case Qualifiers::OCL_Strong: name = "__strong"; break; 6781 case Qualifiers::OCL_Weak: name = "__weak"; break; 6782 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break; 6783 } 6784 S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name 6785 << TDS_ObjCObjOrBlock << type; 6786 } 6787 6788 // Don't actually add the __unsafe_unretained qualifier in non-ARC files, 6789 // because having both 'T' and '__unsafe_unretained T' exist in the type 6790 // system causes unfortunate widespread consistency problems. (For example, 6791 // they're not considered compatible types, and we mangle them identicially 6792 // as template arguments.) These problems are all individually fixable, 6793 // but it's easier to just not add the qualifier and instead sniff it out 6794 // in specific places using isObjCInertUnsafeUnretainedType(). 6795 // 6796 // Doing this does means we miss some trivial consistency checks that 6797 // would've triggered in ARC, but that's better than trying to solve all 6798 // the coexistence problems with __unsafe_unretained. 6799 if (!S.getLangOpts().ObjCAutoRefCount && 6800 lifetime == Qualifiers::OCL_ExplicitNone) { 6801 type = state.getAttributedType( 6802 createSimpleAttr<ObjCInertUnsafeUnretainedAttr>(S.Context, attr), 6803 type, type); 6804 return true; 6805 } 6806 6807 QualType origType = type; 6808 if (!NonObjCPointer) 6809 type = S.Context.getQualifiedType(underlyingType); 6810 6811 // If we have a valid source location for the attribute, use an 6812 // AttributedType instead. 6813 if (AttrLoc.isValid()) { 6814 type = state.getAttributedType(::new (S.Context) 6815 ObjCOwnershipAttr(S.Context, attr, II), 6816 origType, type); 6817 } 6818 6819 auto diagnoseOrDelay = [](Sema &S, SourceLocation loc, 6820 unsigned diagnostic, QualType type) { 6821 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) { 6822 S.DelayedDiagnostics.add( 6823 sema::DelayedDiagnostic::makeForbiddenType( 6824 S.getSourceManager().getExpansionLoc(loc), 6825 diagnostic, type, /*ignored*/ 0)); 6826 } else { 6827 S.Diag(loc, diagnostic); 6828 } 6829 }; 6830 6831 // Sometimes, __weak isn't allowed. 6832 if (lifetime == Qualifiers::OCL_Weak && 6833 !S.getLangOpts().ObjCWeak && !NonObjCPointer) { 6834 6835 // Use a specialized diagnostic if the runtime just doesn't support them. 6836 unsigned diagnostic = 6837 (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled 6838 : diag::err_arc_weak_no_runtime); 6839 6840 // In any case, delay the diagnostic until we know what we're parsing. 6841 diagnoseOrDelay(S, AttrLoc, diagnostic, type); 6842 6843 attr.setInvalid(); 6844 return true; 6845 } 6846 6847 // Forbid __weak for class objects marked as 6848 // objc_arc_weak_reference_unavailable 6849 if (lifetime == Qualifiers::OCL_Weak) { 6850 if (const ObjCObjectPointerType *ObjT = 6851 type->getAs<ObjCObjectPointerType>()) { 6852 if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) { 6853 if (Class->isArcWeakrefUnavailable()) { 6854 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class); 6855 S.Diag(ObjT->getInterfaceDecl()->getLocation(), 6856 diag::note_class_declared); 6857 } 6858 } 6859 } 6860 } 6861 6862 return true; 6863 } 6864 6865 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type 6866 /// attribute on the specified type. Returns true to indicate that 6867 /// the attribute was handled, false to indicate that the type does 6868 /// not permit the attribute. 6869 static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr, 6870 QualType &type) { 6871 Sema &S = state.getSema(); 6872 6873 // Delay if this isn't some kind of pointer. 6874 if (!type->isPointerType() && 6875 !type->isObjCObjectPointerType() && 6876 !type->isBlockPointerType()) 6877 return false; 6878 6879 if (type.getObjCGCAttr() != Qualifiers::GCNone) { 6880 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc); 6881 attr.setInvalid(); 6882 return true; 6883 } 6884 6885 // Check the attribute arguments. 6886 if (!attr.isArgIdent(0)) { 6887 S.Diag(attr.getLoc(), diag::err_attribute_argument_type) 6888 << attr << AANT_ArgumentString; 6889 attr.setInvalid(); 6890 return true; 6891 } 6892 Qualifiers::GC GCAttr; 6893 if (attr.getNumArgs() > 1) { 6894 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << attr 6895 << 1; 6896 attr.setInvalid(); 6897 return true; 6898 } 6899 6900 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident; 6901 if (II->isStr("weak")) 6902 GCAttr = Qualifiers::Weak; 6903 else if (II->isStr("strong")) 6904 GCAttr = Qualifiers::Strong; 6905 else { 6906 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported) 6907 << attr << II; 6908 attr.setInvalid(); 6909 return true; 6910 } 6911 6912 QualType origType = type; 6913 type = S.Context.getObjCGCQualType(origType, GCAttr); 6914 6915 // Make an attributed type to preserve the source information. 6916 if (attr.getLoc().isValid()) 6917 type = state.getAttributedType( 6918 ::new (S.Context) ObjCGCAttr(S.Context, attr, II), origType, type); 6919 6920 return true; 6921 } 6922 6923 namespace { 6924 /// A helper class to unwrap a type down to a function for the 6925 /// purposes of applying attributes there. 6926 /// 6927 /// Use: 6928 /// FunctionTypeUnwrapper unwrapped(SemaRef, T); 6929 /// if (unwrapped.isFunctionType()) { 6930 /// const FunctionType *fn = unwrapped.get(); 6931 /// // change fn somehow 6932 /// T = unwrapped.wrap(fn); 6933 /// } 6934 struct FunctionTypeUnwrapper { 6935 enum WrapKind { 6936 Desugar, 6937 Attributed, 6938 Parens, 6939 Array, 6940 Pointer, 6941 BlockPointer, 6942 Reference, 6943 MemberPointer, 6944 MacroQualified, 6945 }; 6946 6947 QualType Original; 6948 const FunctionType *Fn; 6949 SmallVector<unsigned char /*WrapKind*/, 8> Stack; 6950 6951 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) { 6952 while (true) { 6953 const Type *Ty = T.getTypePtr(); 6954 if (isa<FunctionType>(Ty)) { 6955 Fn = cast<FunctionType>(Ty); 6956 return; 6957 } else if (isa<ParenType>(Ty)) { 6958 T = cast<ParenType>(Ty)->getInnerType(); 6959 Stack.push_back(Parens); 6960 } else if (isa<ConstantArrayType>(Ty) || isa<VariableArrayType>(Ty) || 6961 isa<IncompleteArrayType>(Ty)) { 6962 T = cast<ArrayType>(Ty)->getElementType(); 6963 Stack.push_back(Array); 6964 } else if (isa<PointerType>(Ty)) { 6965 T = cast<PointerType>(Ty)->getPointeeType(); 6966 Stack.push_back(Pointer); 6967 } else if (isa<BlockPointerType>(Ty)) { 6968 T = cast<BlockPointerType>(Ty)->getPointeeType(); 6969 Stack.push_back(BlockPointer); 6970 } else if (isa<MemberPointerType>(Ty)) { 6971 T = cast<MemberPointerType>(Ty)->getPointeeType(); 6972 Stack.push_back(MemberPointer); 6973 } else if (isa<ReferenceType>(Ty)) { 6974 T = cast<ReferenceType>(Ty)->getPointeeType(); 6975 Stack.push_back(Reference); 6976 } else if (isa<AttributedType>(Ty)) { 6977 T = cast<AttributedType>(Ty)->getEquivalentType(); 6978 Stack.push_back(Attributed); 6979 } else if (isa<MacroQualifiedType>(Ty)) { 6980 T = cast<MacroQualifiedType>(Ty)->getUnderlyingType(); 6981 Stack.push_back(MacroQualified); 6982 } else { 6983 const Type *DTy = Ty->getUnqualifiedDesugaredType(); 6984 if (Ty == DTy) { 6985 Fn = nullptr; 6986 return; 6987 } 6988 6989 T = QualType(DTy, 0); 6990 Stack.push_back(Desugar); 6991 } 6992 } 6993 } 6994 6995 bool isFunctionType() const { return (Fn != nullptr); } 6996 const FunctionType *get() const { return Fn; } 6997 6998 QualType wrap(Sema &S, const FunctionType *New) { 6999 // If T wasn't modified from the unwrapped type, do nothing. 7000 if (New == get()) return Original; 7001 7002 Fn = New; 7003 return wrap(S.Context, Original, 0); 7004 } 7005 7006 private: 7007 QualType wrap(ASTContext &C, QualType Old, unsigned I) { 7008 if (I == Stack.size()) 7009 return C.getQualifiedType(Fn, Old.getQualifiers()); 7010 7011 // Build up the inner type, applying the qualifiers from the old 7012 // type to the new type. 7013 SplitQualType SplitOld = Old.split(); 7014 7015 // As a special case, tail-recurse if there are no qualifiers. 7016 if (SplitOld.Quals.empty()) 7017 return wrap(C, SplitOld.Ty, I); 7018 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals); 7019 } 7020 7021 QualType wrap(ASTContext &C, const Type *Old, unsigned I) { 7022 if (I == Stack.size()) return QualType(Fn, 0); 7023 7024 switch (static_cast<WrapKind>(Stack[I++])) { 7025 case Desugar: 7026 // This is the point at which we potentially lose source 7027 // information. 7028 return wrap(C, Old->getUnqualifiedDesugaredType(), I); 7029 7030 case Attributed: 7031 return wrap(C, cast<AttributedType>(Old)->getEquivalentType(), I); 7032 7033 case Parens: { 7034 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I); 7035 return C.getParenType(New); 7036 } 7037 7038 case MacroQualified: 7039 return wrap(C, cast<MacroQualifiedType>(Old)->getUnderlyingType(), I); 7040 7041 case Array: { 7042 if (const auto *CAT = dyn_cast<ConstantArrayType>(Old)) { 7043 QualType New = wrap(C, CAT->getElementType(), I); 7044 return C.getConstantArrayType(New, CAT->getSize(), CAT->getSizeExpr(), 7045 CAT->getSizeModifier(), 7046 CAT->getIndexTypeCVRQualifiers()); 7047 } 7048 7049 if (const auto *VAT = dyn_cast<VariableArrayType>(Old)) { 7050 QualType New = wrap(C, VAT->getElementType(), I); 7051 return C.getVariableArrayType( 7052 New, VAT->getSizeExpr(), VAT->getSizeModifier(), 7053 VAT->getIndexTypeCVRQualifiers(), VAT->getBracketsRange()); 7054 } 7055 7056 const auto *IAT = cast<IncompleteArrayType>(Old); 7057 QualType New = wrap(C, IAT->getElementType(), I); 7058 return C.getIncompleteArrayType(New, IAT->getSizeModifier(), 7059 IAT->getIndexTypeCVRQualifiers()); 7060 } 7061 7062 case Pointer: { 7063 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I); 7064 return C.getPointerType(New); 7065 } 7066 7067 case BlockPointer: { 7068 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I); 7069 return C.getBlockPointerType(New); 7070 } 7071 7072 case MemberPointer: { 7073 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old); 7074 QualType New = wrap(C, OldMPT->getPointeeType(), I); 7075 return C.getMemberPointerType(New, OldMPT->getClass()); 7076 } 7077 7078 case Reference: { 7079 const ReferenceType *OldRef = cast<ReferenceType>(Old); 7080 QualType New = wrap(C, OldRef->getPointeeType(), I); 7081 if (isa<LValueReferenceType>(OldRef)) 7082 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue()); 7083 else 7084 return C.getRValueReferenceType(New); 7085 } 7086 } 7087 7088 llvm_unreachable("unknown wrapping kind"); 7089 } 7090 }; 7091 } // end anonymous namespace 7092 7093 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State, 7094 ParsedAttr &PAttr, QualType &Type) { 7095 Sema &S = State.getSema(); 7096 7097 Attr *A; 7098 switch (PAttr.getKind()) { 7099 default: llvm_unreachable("Unknown attribute kind"); 7100 case ParsedAttr::AT_Ptr32: 7101 A = createSimpleAttr<Ptr32Attr>(S.Context, PAttr); 7102 break; 7103 case ParsedAttr::AT_Ptr64: 7104 A = createSimpleAttr<Ptr64Attr>(S.Context, PAttr); 7105 break; 7106 case ParsedAttr::AT_SPtr: 7107 A = createSimpleAttr<SPtrAttr>(S.Context, PAttr); 7108 break; 7109 case ParsedAttr::AT_UPtr: 7110 A = createSimpleAttr<UPtrAttr>(S.Context, PAttr); 7111 break; 7112 } 7113 7114 std::bitset<attr::LastAttr> Attrs; 7115 attr::Kind NewAttrKind = A->getKind(); 7116 QualType Desugared = Type; 7117 const AttributedType *AT = dyn_cast<AttributedType>(Type); 7118 while (AT) { 7119 Attrs[AT->getAttrKind()] = true; 7120 Desugared = AT->getModifiedType(); 7121 AT = dyn_cast<AttributedType>(Desugared); 7122 } 7123 7124 // You cannot specify duplicate type attributes, so if the attribute has 7125 // already been applied, flag it. 7126 if (Attrs[NewAttrKind]) { 7127 S.Diag(PAttr.getLoc(), diag::warn_duplicate_attribute_exact) << PAttr; 7128 return true; 7129 } 7130 Attrs[NewAttrKind] = true; 7131 7132 // You cannot have both __sptr and __uptr on the same type, nor can you 7133 // have __ptr32 and __ptr64. 7134 if (Attrs[attr::Ptr32] && Attrs[attr::Ptr64]) { 7135 S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible) 7136 << "'__ptr32'" 7137 << "'__ptr64'"; 7138 return true; 7139 } else if (Attrs[attr::SPtr] && Attrs[attr::UPtr]) { 7140 S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible) 7141 << "'__sptr'" 7142 << "'__uptr'"; 7143 return true; 7144 } 7145 7146 // Pointer type qualifiers can only operate on pointer types, but not 7147 // pointer-to-member types. 7148 // 7149 // FIXME: Should we really be disallowing this attribute if there is any 7150 // type sugar between it and the pointer (other than attributes)? Eg, this 7151 // disallows the attribute on a parenthesized pointer. 7152 // And if so, should we really allow *any* type attribute? 7153 if (!isa<PointerType>(Desugared)) { 7154 if (Type->isMemberPointerType()) 7155 S.Diag(PAttr.getLoc(), diag::err_attribute_no_member_pointers) << PAttr; 7156 else 7157 S.Diag(PAttr.getLoc(), diag::err_attribute_pointers_only) << PAttr << 0; 7158 return true; 7159 } 7160 7161 // Add address space to type based on its attributes. 7162 LangAS ASIdx = LangAS::Default; 7163 uint64_t PtrWidth = S.Context.getTargetInfo().getPointerWidth(0); 7164 if (PtrWidth == 32) { 7165 if (Attrs[attr::Ptr64]) 7166 ASIdx = LangAS::ptr64; 7167 else if (Attrs[attr::UPtr]) 7168 ASIdx = LangAS::ptr32_uptr; 7169 } else if (PtrWidth == 64 && Attrs[attr::Ptr32]) { 7170 if (Attrs[attr::UPtr]) 7171 ASIdx = LangAS::ptr32_uptr; 7172 else 7173 ASIdx = LangAS::ptr32_sptr; 7174 } 7175 7176 QualType Pointee = Type->getPointeeType(); 7177 if (ASIdx != LangAS::Default) 7178 Pointee = S.Context.getAddrSpaceQualType( 7179 S.Context.removeAddrSpaceQualType(Pointee), ASIdx); 7180 Type = State.getAttributedType(A, Type, S.Context.getPointerType(Pointee)); 7181 return false; 7182 } 7183 7184 /// Map a nullability attribute kind to a nullability kind. 7185 static NullabilityKind mapNullabilityAttrKind(ParsedAttr::Kind kind) { 7186 switch (kind) { 7187 case ParsedAttr::AT_TypeNonNull: 7188 return NullabilityKind::NonNull; 7189 7190 case ParsedAttr::AT_TypeNullable: 7191 return NullabilityKind::Nullable; 7192 7193 case ParsedAttr::AT_TypeNullableResult: 7194 return NullabilityKind::NullableResult; 7195 7196 case ParsedAttr::AT_TypeNullUnspecified: 7197 return NullabilityKind::Unspecified; 7198 7199 default: 7200 llvm_unreachable("not a nullability attribute kind"); 7201 } 7202 } 7203 7204 /// Applies a nullability type specifier to the given type, if possible. 7205 /// 7206 /// \param state The type processing state. 7207 /// 7208 /// \param type The type to which the nullability specifier will be 7209 /// added. On success, this type will be updated appropriately. 7210 /// 7211 /// \param attr The attribute as written on the type. 7212 /// 7213 /// \param allowOnArrayType Whether to accept nullability specifiers on an 7214 /// array type (e.g., because it will decay to a pointer). 7215 /// 7216 /// \returns true if a problem has been diagnosed, false on success. 7217 static bool checkNullabilityTypeSpecifier(TypeProcessingState &state, 7218 QualType &type, 7219 ParsedAttr &attr, 7220 bool allowOnArrayType) { 7221 Sema &S = state.getSema(); 7222 7223 NullabilityKind nullability = mapNullabilityAttrKind(attr.getKind()); 7224 SourceLocation nullabilityLoc = attr.getLoc(); 7225 bool isContextSensitive = attr.isContextSensitiveKeywordAttribute(); 7226 7227 recordNullabilitySeen(S, nullabilityLoc); 7228 7229 // Check for existing nullability attributes on the type. 7230 QualType desugared = type; 7231 while (auto attributed = dyn_cast<AttributedType>(desugared.getTypePtr())) { 7232 // Check whether there is already a null 7233 if (auto existingNullability = attributed->getImmediateNullability()) { 7234 // Duplicated nullability. 7235 if (nullability == *existingNullability) { 7236 S.Diag(nullabilityLoc, diag::warn_nullability_duplicate) 7237 << DiagNullabilityKind(nullability, isContextSensitive) 7238 << FixItHint::CreateRemoval(nullabilityLoc); 7239 7240 break; 7241 } 7242 7243 // Conflicting nullability. 7244 S.Diag(nullabilityLoc, diag::err_nullability_conflicting) 7245 << DiagNullabilityKind(nullability, isContextSensitive) 7246 << DiagNullabilityKind(*existingNullability, false); 7247 return true; 7248 } 7249 7250 desugared = attributed->getModifiedType(); 7251 } 7252 7253 // If there is already a different nullability specifier, complain. 7254 // This (unlike the code above) looks through typedefs that might 7255 // have nullability specifiers on them, which means we cannot 7256 // provide a useful Fix-It. 7257 if (auto existingNullability = desugared->getNullability(S.Context)) { 7258 if (nullability != *existingNullability) { 7259 S.Diag(nullabilityLoc, diag::err_nullability_conflicting) 7260 << DiagNullabilityKind(nullability, isContextSensitive) 7261 << DiagNullabilityKind(*existingNullability, false); 7262 7263 // Try to find the typedef with the existing nullability specifier. 7264 if (auto typedefType = desugared->getAs<TypedefType>()) { 7265 TypedefNameDecl *typedefDecl = typedefType->getDecl(); 7266 QualType underlyingType = typedefDecl->getUnderlyingType(); 7267 if (auto typedefNullability 7268 = AttributedType::stripOuterNullability(underlyingType)) { 7269 if (*typedefNullability == *existingNullability) { 7270 S.Diag(typedefDecl->getLocation(), diag::note_nullability_here) 7271 << DiagNullabilityKind(*existingNullability, false); 7272 } 7273 } 7274 } 7275 7276 return true; 7277 } 7278 } 7279 7280 // If this definitely isn't a pointer type, reject the specifier. 7281 if (!desugared->canHaveNullability() && 7282 !(allowOnArrayType && desugared->isArrayType())) { 7283 S.Diag(nullabilityLoc, diag::err_nullability_nonpointer) 7284 << DiagNullabilityKind(nullability, isContextSensitive) << type; 7285 return true; 7286 } 7287 7288 // For the context-sensitive keywords/Objective-C property 7289 // attributes, require that the type be a single-level pointer. 7290 if (isContextSensitive) { 7291 // Make sure that the pointee isn't itself a pointer type. 7292 const Type *pointeeType = nullptr; 7293 if (desugared->isArrayType()) 7294 pointeeType = desugared->getArrayElementTypeNoTypeQual(); 7295 else if (desugared->isAnyPointerType()) 7296 pointeeType = desugared->getPointeeType().getTypePtr(); 7297 7298 if (pointeeType && (pointeeType->isAnyPointerType() || 7299 pointeeType->isObjCObjectPointerType() || 7300 pointeeType->isMemberPointerType())) { 7301 S.Diag(nullabilityLoc, diag::err_nullability_cs_multilevel) 7302 << DiagNullabilityKind(nullability, true) 7303 << type; 7304 S.Diag(nullabilityLoc, diag::note_nullability_type_specifier) 7305 << DiagNullabilityKind(nullability, false) 7306 << type 7307 << FixItHint::CreateReplacement(nullabilityLoc, 7308 getNullabilitySpelling(nullability)); 7309 return true; 7310 } 7311 } 7312 7313 // Form the attributed type. 7314 type = state.getAttributedType( 7315 createNullabilityAttr(S.Context, attr, nullability), type, type); 7316 return false; 7317 } 7318 7319 /// Check the application of the Objective-C '__kindof' qualifier to 7320 /// the given type. 7321 static bool checkObjCKindOfType(TypeProcessingState &state, QualType &type, 7322 ParsedAttr &attr) { 7323 Sema &S = state.getSema(); 7324 7325 if (isa<ObjCTypeParamType>(type)) { 7326 // Build the attributed type to record where __kindof occurred. 7327 type = state.getAttributedType( 7328 createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, type); 7329 return false; 7330 } 7331 7332 // Find out if it's an Objective-C object or object pointer type; 7333 const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>(); 7334 const ObjCObjectType *objType = ptrType ? ptrType->getObjectType() 7335 : type->getAs<ObjCObjectType>(); 7336 7337 // If not, we can't apply __kindof. 7338 if (!objType) { 7339 // FIXME: Handle dependent types that aren't yet object types. 7340 S.Diag(attr.getLoc(), diag::err_objc_kindof_nonobject) 7341 << type; 7342 return true; 7343 } 7344 7345 // Rebuild the "equivalent" type, which pushes __kindof down into 7346 // the object type. 7347 // There is no need to apply kindof on an unqualified id type. 7348 QualType equivType = S.Context.getObjCObjectType( 7349 objType->getBaseType(), objType->getTypeArgsAsWritten(), 7350 objType->getProtocols(), 7351 /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true); 7352 7353 // If we started with an object pointer type, rebuild it. 7354 if (ptrType) { 7355 equivType = S.Context.getObjCObjectPointerType(equivType); 7356 if (auto nullability = type->getNullability(S.Context)) { 7357 // We create a nullability attribute from the __kindof attribute. 7358 // Make sure that will make sense. 7359 assert(attr.getAttributeSpellingListIndex() == 0 && 7360 "multiple spellings for __kindof?"); 7361 Attr *A = createNullabilityAttr(S.Context, attr, *nullability); 7362 A->setImplicit(true); 7363 equivType = state.getAttributedType(A, equivType, equivType); 7364 } 7365 } 7366 7367 // Build the attributed type to record where __kindof occurred. 7368 type = state.getAttributedType( 7369 createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, equivType); 7370 return false; 7371 } 7372 7373 /// Distribute a nullability type attribute that cannot be applied to 7374 /// the type specifier to a pointer, block pointer, or member pointer 7375 /// declarator, complaining if necessary. 7376 /// 7377 /// \returns true if the nullability annotation was distributed, false 7378 /// otherwise. 7379 static bool distributeNullabilityTypeAttr(TypeProcessingState &state, 7380 QualType type, ParsedAttr &attr) { 7381 Declarator &declarator = state.getDeclarator(); 7382 7383 /// Attempt to move the attribute to the specified chunk. 7384 auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool { 7385 // If there is already a nullability attribute there, don't add 7386 // one. 7387 if (hasNullabilityAttr(chunk.getAttrs())) 7388 return false; 7389 7390 // Complain about the nullability qualifier being in the wrong 7391 // place. 7392 enum { 7393 PK_Pointer, 7394 PK_BlockPointer, 7395 PK_MemberPointer, 7396 PK_FunctionPointer, 7397 PK_MemberFunctionPointer, 7398 } pointerKind 7399 = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer 7400 : PK_Pointer) 7401 : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer 7402 : inFunction? PK_MemberFunctionPointer : PK_MemberPointer; 7403 7404 auto diag = state.getSema().Diag(attr.getLoc(), 7405 diag::warn_nullability_declspec) 7406 << DiagNullabilityKind(mapNullabilityAttrKind(attr.getKind()), 7407 attr.isContextSensitiveKeywordAttribute()) 7408 << type 7409 << static_cast<unsigned>(pointerKind); 7410 7411 // FIXME: MemberPointer chunks don't carry the location of the *. 7412 if (chunk.Kind != DeclaratorChunk::MemberPointer) { 7413 diag << FixItHint::CreateRemoval(attr.getLoc()) 7414 << FixItHint::CreateInsertion( 7415 state.getSema().getPreprocessor().getLocForEndOfToken( 7416 chunk.Loc), 7417 " " + attr.getAttrName()->getName().str() + " "); 7418 } 7419 7420 moveAttrFromListToList(attr, state.getCurrentAttributes(), 7421 chunk.getAttrs()); 7422 return true; 7423 }; 7424 7425 // Move it to the outermost pointer, member pointer, or block 7426 // pointer declarator. 7427 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { 7428 DeclaratorChunk &chunk = declarator.getTypeObject(i-1); 7429 switch (chunk.Kind) { 7430 case DeclaratorChunk::Pointer: 7431 case DeclaratorChunk::BlockPointer: 7432 case DeclaratorChunk::MemberPointer: 7433 return moveToChunk(chunk, false); 7434 7435 case DeclaratorChunk::Paren: 7436 case DeclaratorChunk::Array: 7437 continue; 7438 7439 case DeclaratorChunk::Function: 7440 // Try to move past the return type to a function/block/member 7441 // function pointer. 7442 if (DeclaratorChunk *dest = maybeMovePastReturnType( 7443 declarator, i, 7444 /*onlyBlockPointers=*/false)) { 7445 return moveToChunk(*dest, true); 7446 } 7447 7448 return false; 7449 7450 // Don't walk through these. 7451 case DeclaratorChunk::Reference: 7452 case DeclaratorChunk::Pipe: 7453 return false; 7454 } 7455 } 7456 7457 return false; 7458 } 7459 7460 static Attr *getCCTypeAttr(ASTContext &Ctx, ParsedAttr &Attr) { 7461 assert(!Attr.isInvalid()); 7462 switch (Attr.getKind()) { 7463 default: 7464 llvm_unreachable("not a calling convention attribute"); 7465 case ParsedAttr::AT_CDecl: 7466 return createSimpleAttr<CDeclAttr>(Ctx, Attr); 7467 case ParsedAttr::AT_FastCall: 7468 return createSimpleAttr<FastCallAttr>(Ctx, Attr); 7469 case ParsedAttr::AT_StdCall: 7470 return createSimpleAttr<StdCallAttr>(Ctx, Attr); 7471 case ParsedAttr::AT_ThisCall: 7472 return createSimpleAttr<ThisCallAttr>(Ctx, Attr); 7473 case ParsedAttr::AT_RegCall: 7474 return createSimpleAttr<RegCallAttr>(Ctx, Attr); 7475 case ParsedAttr::AT_Pascal: 7476 return createSimpleAttr<PascalAttr>(Ctx, Attr); 7477 case ParsedAttr::AT_SwiftCall: 7478 return createSimpleAttr<SwiftCallAttr>(Ctx, Attr); 7479 case ParsedAttr::AT_SwiftAsyncCall: 7480 return createSimpleAttr<SwiftAsyncCallAttr>(Ctx, Attr); 7481 case ParsedAttr::AT_VectorCall: 7482 return createSimpleAttr<VectorCallAttr>(Ctx, Attr); 7483 case ParsedAttr::AT_AArch64VectorPcs: 7484 return createSimpleAttr<AArch64VectorPcsAttr>(Ctx, Attr); 7485 case ParsedAttr::AT_Pcs: { 7486 // The attribute may have had a fixit applied where we treated an 7487 // identifier as a string literal. The contents of the string are valid, 7488 // but the form may not be. 7489 StringRef Str; 7490 if (Attr.isArgExpr(0)) 7491 Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString(); 7492 else 7493 Str = Attr.getArgAsIdent(0)->Ident->getName(); 7494 PcsAttr::PCSType Type; 7495 if (!PcsAttr::ConvertStrToPCSType(Str, Type)) 7496 llvm_unreachable("already validated the attribute"); 7497 return ::new (Ctx) PcsAttr(Ctx, Attr, Type); 7498 } 7499 case ParsedAttr::AT_IntelOclBicc: 7500 return createSimpleAttr<IntelOclBiccAttr>(Ctx, Attr); 7501 case ParsedAttr::AT_MSABI: 7502 return createSimpleAttr<MSABIAttr>(Ctx, Attr); 7503 case ParsedAttr::AT_SysVABI: 7504 return createSimpleAttr<SysVABIAttr>(Ctx, Attr); 7505 case ParsedAttr::AT_PreserveMost: 7506 return createSimpleAttr<PreserveMostAttr>(Ctx, Attr); 7507 case ParsedAttr::AT_PreserveAll: 7508 return createSimpleAttr<PreserveAllAttr>(Ctx, Attr); 7509 } 7510 llvm_unreachable("unexpected attribute kind!"); 7511 } 7512 7513 /// Process an individual function attribute. Returns true to 7514 /// indicate that the attribute was handled, false if it wasn't. 7515 static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr, 7516 QualType &type) { 7517 Sema &S = state.getSema(); 7518 7519 FunctionTypeUnwrapper unwrapped(S, type); 7520 7521 if (attr.getKind() == ParsedAttr::AT_NoReturn) { 7522 if (S.CheckAttrNoArgs(attr)) 7523 return true; 7524 7525 // Delay if this is not a function type. 7526 if (!unwrapped.isFunctionType()) 7527 return false; 7528 7529 // Otherwise we can process right away. 7530 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true); 7531 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 7532 return true; 7533 } 7534 7535 if (attr.getKind() == ParsedAttr::AT_CmseNSCall) { 7536 // Delay if this is not a function type. 7537 if (!unwrapped.isFunctionType()) 7538 return false; 7539 7540 // Ignore if we don't have CMSE enabled. 7541 if (!S.getLangOpts().Cmse) { 7542 S.Diag(attr.getLoc(), diag::warn_attribute_ignored) << attr; 7543 attr.setInvalid(); 7544 return true; 7545 } 7546 7547 // Otherwise we can process right away. 7548 FunctionType::ExtInfo EI = 7549 unwrapped.get()->getExtInfo().withCmseNSCall(true); 7550 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 7551 return true; 7552 } 7553 7554 // ns_returns_retained is not always a type attribute, but if we got 7555 // here, we're treating it as one right now. 7556 if (attr.getKind() == ParsedAttr::AT_NSReturnsRetained) { 7557 if (attr.getNumArgs()) return true; 7558 7559 // Delay if this is not a function type. 7560 if (!unwrapped.isFunctionType()) 7561 return false; 7562 7563 // Check whether the return type is reasonable. 7564 if (S.checkNSReturnsRetainedReturnType(attr.getLoc(), 7565 unwrapped.get()->getReturnType())) 7566 return true; 7567 7568 // Only actually change the underlying type in ARC builds. 7569 QualType origType = type; 7570 if (state.getSema().getLangOpts().ObjCAutoRefCount) { 7571 FunctionType::ExtInfo EI 7572 = unwrapped.get()->getExtInfo().withProducesResult(true); 7573 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 7574 } 7575 type = state.getAttributedType( 7576 createSimpleAttr<NSReturnsRetainedAttr>(S.Context, attr), 7577 origType, type); 7578 return true; 7579 } 7580 7581 if (attr.getKind() == ParsedAttr::AT_AnyX86NoCallerSavedRegisters) { 7582 if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr)) 7583 return true; 7584 7585 // Delay if this is not a function type. 7586 if (!unwrapped.isFunctionType()) 7587 return false; 7588 7589 FunctionType::ExtInfo EI = 7590 unwrapped.get()->getExtInfo().withNoCallerSavedRegs(true); 7591 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 7592 return true; 7593 } 7594 7595 if (attr.getKind() == ParsedAttr::AT_AnyX86NoCfCheck) { 7596 if (!S.getLangOpts().CFProtectionBranch) { 7597 S.Diag(attr.getLoc(), diag::warn_nocf_check_attribute_ignored); 7598 attr.setInvalid(); 7599 return true; 7600 } 7601 7602 if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr)) 7603 return true; 7604 7605 // If this is not a function type, warning will be asserted by subject 7606 // check. 7607 if (!unwrapped.isFunctionType()) 7608 return true; 7609 7610 FunctionType::ExtInfo EI = 7611 unwrapped.get()->getExtInfo().withNoCfCheck(true); 7612 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 7613 return true; 7614 } 7615 7616 if (attr.getKind() == ParsedAttr::AT_Regparm) { 7617 unsigned value; 7618 if (S.CheckRegparmAttr(attr, value)) 7619 return true; 7620 7621 // Delay if this is not a function type. 7622 if (!unwrapped.isFunctionType()) 7623 return false; 7624 7625 // Diagnose regparm with fastcall. 7626 const FunctionType *fn = unwrapped.get(); 7627 CallingConv CC = fn->getCallConv(); 7628 if (CC == CC_X86FastCall) { 7629 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 7630 << FunctionType::getNameForCallConv(CC) 7631 << "regparm"; 7632 attr.setInvalid(); 7633 return true; 7634 } 7635 7636 FunctionType::ExtInfo EI = 7637 unwrapped.get()->getExtInfo().withRegParm(value); 7638 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 7639 return true; 7640 } 7641 7642 if (attr.getKind() == ParsedAttr::AT_NoThrow) { 7643 // Delay if this is not a function type. 7644 if (!unwrapped.isFunctionType()) 7645 return false; 7646 7647 if (S.CheckAttrNoArgs(attr)) { 7648 attr.setInvalid(); 7649 return true; 7650 } 7651 7652 // Otherwise we can process right away. 7653 auto *Proto = unwrapped.get()->castAs<FunctionProtoType>(); 7654 7655 // MSVC ignores nothrow if it is in conflict with an explicit exception 7656 // specification. 7657 if (Proto->hasExceptionSpec()) { 7658 switch (Proto->getExceptionSpecType()) { 7659 case EST_None: 7660 llvm_unreachable("This doesn't have an exception spec!"); 7661 7662 case EST_DynamicNone: 7663 case EST_BasicNoexcept: 7664 case EST_NoexceptTrue: 7665 case EST_NoThrow: 7666 // Exception spec doesn't conflict with nothrow, so don't warn. 7667 LLVM_FALLTHROUGH; 7668 case EST_Unparsed: 7669 case EST_Uninstantiated: 7670 case EST_DependentNoexcept: 7671 case EST_Unevaluated: 7672 // We don't have enough information to properly determine if there is a 7673 // conflict, so suppress the warning. 7674 break; 7675 case EST_Dynamic: 7676 case EST_MSAny: 7677 case EST_NoexceptFalse: 7678 S.Diag(attr.getLoc(), diag::warn_nothrow_attribute_ignored); 7679 break; 7680 } 7681 return true; 7682 } 7683 7684 type = unwrapped.wrap( 7685 S, S.Context 7686 .getFunctionTypeWithExceptionSpec( 7687 QualType{Proto, 0}, 7688 FunctionProtoType::ExceptionSpecInfo{EST_NoThrow}) 7689 ->getAs<FunctionType>()); 7690 return true; 7691 } 7692 7693 // Delay if the type didn't work out to a function. 7694 if (!unwrapped.isFunctionType()) return false; 7695 7696 // Otherwise, a calling convention. 7697 CallingConv CC; 7698 if (S.CheckCallingConvAttr(attr, CC)) 7699 return true; 7700 7701 const FunctionType *fn = unwrapped.get(); 7702 CallingConv CCOld = fn->getCallConv(); 7703 Attr *CCAttr = getCCTypeAttr(S.Context, attr); 7704 7705 if (CCOld != CC) { 7706 // Error out on when there's already an attribute on the type 7707 // and the CCs don't match. 7708 if (S.getCallingConvAttributedType(type)) { 7709 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 7710 << FunctionType::getNameForCallConv(CC) 7711 << FunctionType::getNameForCallConv(CCOld); 7712 attr.setInvalid(); 7713 return true; 7714 } 7715 } 7716 7717 // Diagnose use of variadic functions with calling conventions that 7718 // don't support them (e.g. because they're callee-cleanup). 7719 // We delay warning about this on unprototyped function declarations 7720 // until after redeclaration checking, just in case we pick up a 7721 // prototype that way. And apparently we also "delay" warning about 7722 // unprototyped function types in general, despite not necessarily having 7723 // much ability to diagnose it later. 7724 if (!supportsVariadicCall(CC)) { 7725 const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn); 7726 if (FnP && FnP->isVariadic()) { 7727 // stdcall and fastcall are ignored with a warning for GCC and MS 7728 // compatibility. 7729 if (CC == CC_X86StdCall || CC == CC_X86FastCall) 7730 return S.Diag(attr.getLoc(), diag::warn_cconv_unsupported) 7731 << FunctionType::getNameForCallConv(CC) 7732 << (int)Sema::CallingConventionIgnoredReason::VariadicFunction; 7733 7734 attr.setInvalid(); 7735 return S.Diag(attr.getLoc(), diag::err_cconv_varargs) 7736 << FunctionType::getNameForCallConv(CC); 7737 } 7738 } 7739 7740 // Also diagnose fastcall with regparm. 7741 if (CC == CC_X86FastCall && fn->getHasRegParm()) { 7742 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 7743 << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall); 7744 attr.setInvalid(); 7745 return true; 7746 } 7747 7748 // Modify the CC from the wrapped function type, wrap it all back, and then 7749 // wrap the whole thing in an AttributedType as written. The modified type 7750 // might have a different CC if we ignored the attribute. 7751 QualType Equivalent; 7752 if (CCOld == CC) { 7753 Equivalent = type; 7754 } else { 7755 auto EI = unwrapped.get()->getExtInfo().withCallingConv(CC); 7756 Equivalent = 7757 unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 7758 } 7759 type = state.getAttributedType(CCAttr, type, Equivalent); 7760 return true; 7761 } 7762 7763 bool Sema::hasExplicitCallingConv(QualType T) { 7764 const AttributedType *AT; 7765 7766 // Stop if we'd be stripping off a typedef sugar node to reach the 7767 // AttributedType. 7768 while ((AT = T->getAs<AttributedType>()) && 7769 AT->getAs<TypedefType>() == T->getAs<TypedefType>()) { 7770 if (AT->isCallingConv()) 7771 return true; 7772 T = AT->getModifiedType(); 7773 } 7774 return false; 7775 } 7776 7777 void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor, 7778 SourceLocation Loc) { 7779 FunctionTypeUnwrapper Unwrapped(*this, T); 7780 const FunctionType *FT = Unwrapped.get(); 7781 bool IsVariadic = (isa<FunctionProtoType>(FT) && 7782 cast<FunctionProtoType>(FT)->isVariadic()); 7783 CallingConv CurCC = FT->getCallConv(); 7784 CallingConv ToCC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic); 7785 7786 if (CurCC == ToCC) 7787 return; 7788 7789 // MS compiler ignores explicit calling convention attributes on structors. We 7790 // should do the same. 7791 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) { 7792 // Issue a warning on ignored calling convention -- except of __stdcall. 7793 // Again, this is what MS compiler does. 7794 if (CurCC != CC_X86StdCall) 7795 Diag(Loc, diag::warn_cconv_unsupported) 7796 << FunctionType::getNameForCallConv(CurCC) 7797 << (int)Sema::CallingConventionIgnoredReason::ConstructorDestructor; 7798 // Default adjustment. 7799 } else { 7800 // Only adjust types with the default convention. For example, on Windows 7801 // we should adjust a __cdecl type to __thiscall for instance methods, and a 7802 // __thiscall type to __cdecl for static methods. 7803 CallingConv DefaultCC = 7804 Context.getDefaultCallingConvention(IsVariadic, IsStatic); 7805 7806 if (CurCC != DefaultCC || DefaultCC == ToCC) 7807 return; 7808 7809 if (hasExplicitCallingConv(T)) 7810 return; 7811 } 7812 7813 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC)); 7814 QualType Wrapped = Unwrapped.wrap(*this, FT); 7815 T = Context.getAdjustedType(T, Wrapped); 7816 } 7817 7818 /// HandleVectorSizeAttribute - this attribute is only applicable to integral 7819 /// and float scalars, although arrays, pointers, and function return values are 7820 /// allowed in conjunction with this construct. Aggregates with this attribute 7821 /// are invalid, even if they are of the same size as a corresponding scalar. 7822 /// The raw attribute should contain precisely 1 argument, the vector size for 7823 /// the variable, measured in bytes. If curType and rawAttr are well formed, 7824 /// this routine will return a new vector type. 7825 static void HandleVectorSizeAttr(QualType &CurType, const ParsedAttr &Attr, 7826 Sema &S) { 7827 // Check the attribute arguments. 7828 if (Attr.getNumArgs() != 1) { 7829 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr 7830 << 1; 7831 Attr.setInvalid(); 7832 return; 7833 } 7834 7835 Expr *SizeExpr = Attr.getArgAsExpr(0); 7836 QualType T = S.BuildVectorType(CurType, SizeExpr, Attr.getLoc()); 7837 if (!T.isNull()) 7838 CurType = T; 7839 else 7840 Attr.setInvalid(); 7841 } 7842 7843 /// Process the OpenCL-like ext_vector_type attribute when it occurs on 7844 /// a type. 7845 static void HandleExtVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr, 7846 Sema &S) { 7847 // check the attribute arguments. 7848 if (Attr.getNumArgs() != 1) { 7849 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr 7850 << 1; 7851 return; 7852 } 7853 7854 Expr *SizeExpr = Attr.getArgAsExpr(0); 7855 QualType T = S.BuildExtVectorType(CurType, SizeExpr, Attr.getLoc()); 7856 if (!T.isNull()) 7857 CurType = T; 7858 } 7859 7860 static bool isPermittedNeonBaseType(QualType &Ty, 7861 VectorType::VectorKind VecKind, Sema &S) { 7862 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 7863 if (!BTy) 7864 return false; 7865 7866 llvm::Triple Triple = S.Context.getTargetInfo().getTriple(); 7867 7868 // Signed poly is mathematically wrong, but has been baked into some ABIs by 7869 // now. 7870 bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 || 7871 Triple.getArch() == llvm::Triple::aarch64_32 || 7872 Triple.getArch() == llvm::Triple::aarch64_be; 7873 if (VecKind == VectorType::NeonPolyVector) { 7874 if (IsPolyUnsigned) { 7875 // AArch64 polynomial vectors are unsigned. 7876 return BTy->getKind() == BuiltinType::UChar || 7877 BTy->getKind() == BuiltinType::UShort || 7878 BTy->getKind() == BuiltinType::ULong || 7879 BTy->getKind() == BuiltinType::ULongLong; 7880 } else { 7881 // AArch32 polynomial vectors are signed. 7882 return BTy->getKind() == BuiltinType::SChar || 7883 BTy->getKind() == BuiltinType::Short || 7884 BTy->getKind() == BuiltinType::LongLong; 7885 } 7886 } 7887 7888 // Non-polynomial vector types: the usual suspects are allowed, as well as 7889 // float64_t on AArch64. 7890 if ((Triple.isArch64Bit() || Triple.getArch() == llvm::Triple::aarch64_32) && 7891 BTy->getKind() == BuiltinType::Double) 7892 return true; 7893 7894 return BTy->getKind() == BuiltinType::SChar || 7895 BTy->getKind() == BuiltinType::UChar || 7896 BTy->getKind() == BuiltinType::Short || 7897 BTy->getKind() == BuiltinType::UShort || 7898 BTy->getKind() == BuiltinType::Int || 7899 BTy->getKind() == BuiltinType::UInt || 7900 BTy->getKind() == BuiltinType::Long || 7901 BTy->getKind() == BuiltinType::ULong || 7902 BTy->getKind() == BuiltinType::LongLong || 7903 BTy->getKind() == BuiltinType::ULongLong || 7904 BTy->getKind() == BuiltinType::Float || 7905 BTy->getKind() == BuiltinType::Half || 7906 BTy->getKind() == BuiltinType::BFloat16; 7907 } 7908 7909 static bool verifyValidIntegerConstantExpr(Sema &S, const ParsedAttr &Attr, 7910 llvm::APSInt &Result) { 7911 const auto *AttrExpr = Attr.getArgAsExpr(0); 7912 if (!AttrExpr->isTypeDependent()) { 7913 if (Optional<llvm::APSInt> Res = 7914 AttrExpr->getIntegerConstantExpr(S.Context)) { 7915 Result = *Res; 7916 return true; 7917 } 7918 } 7919 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) 7920 << Attr << AANT_ArgumentIntegerConstant << AttrExpr->getSourceRange(); 7921 Attr.setInvalid(); 7922 return false; 7923 } 7924 7925 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and 7926 /// "neon_polyvector_type" attributes are used to create vector types that 7927 /// are mangled according to ARM's ABI. Otherwise, these types are identical 7928 /// to those created with the "vector_size" attribute. Unlike "vector_size" 7929 /// the argument to these Neon attributes is the number of vector elements, 7930 /// not the vector size in bytes. The vector width and element type must 7931 /// match one of the standard Neon vector types. 7932 static void HandleNeonVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr, 7933 Sema &S, VectorType::VectorKind VecKind) { 7934 // Target must have NEON (or MVE, whose vectors are similar enough 7935 // not to need a separate attribute) 7936 if (!S.Context.getTargetInfo().hasFeature("neon") && 7937 !S.Context.getTargetInfo().hasFeature("mve")) { 7938 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) 7939 << Attr << "'neon' or 'mve'"; 7940 Attr.setInvalid(); 7941 return; 7942 } 7943 // Check the attribute arguments. 7944 if (Attr.getNumArgs() != 1) { 7945 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr 7946 << 1; 7947 Attr.setInvalid(); 7948 return; 7949 } 7950 // The number of elements must be an ICE. 7951 llvm::APSInt numEltsInt(32); 7952 if (!verifyValidIntegerConstantExpr(S, Attr, numEltsInt)) 7953 return; 7954 7955 // Only certain element types are supported for Neon vectors. 7956 if (!isPermittedNeonBaseType(CurType, VecKind, S)) { 7957 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType; 7958 Attr.setInvalid(); 7959 return; 7960 } 7961 7962 // The total size of the vector must be 64 or 128 bits. 7963 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType)); 7964 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue()); 7965 unsigned vecSize = typeSize * numElts; 7966 if (vecSize != 64 && vecSize != 128) { 7967 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType; 7968 Attr.setInvalid(); 7969 return; 7970 } 7971 7972 CurType = S.Context.getVectorType(CurType, numElts, VecKind); 7973 } 7974 7975 /// HandleArmSveVectorBitsTypeAttr - The "arm_sve_vector_bits" attribute is 7976 /// used to create fixed-length versions of sizeless SVE types defined by 7977 /// the ACLE, such as svint32_t and svbool_t. 7978 static void HandleArmSveVectorBitsTypeAttr(QualType &CurType, ParsedAttr &Attr, 7979 Sema &S) { 7980 // Target must have SVE. 7981 if (!S.Context.getTargetInfo().hasFeature("sve")) { 7982 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr << "'sve'"; 7983 Attr.setInvalid(); 7984 return; 7985 } 7986 7987 // Attribute is unsupported if '-msve-vector-bits=<bits>' isn't specified, or 7988 // if <bits>+ syntax is used. 7989 if (!S.getLangOpts().VScaleMin || 7990 S.getLangOpts().VScaleMin != S.getLangOpts().VScaleMax) { 7991 S.Diag(Attr.getLoc(), diag::err_attribute_arm_feature_sve_bits_unsupported) 7992 << Attr; 7993 Attr.setInvalid(); 7994 return; 7995 } 7996 7997 // Check the attribute arguments. 7998 if (Attr.getNumArgs() != 1) { 7999 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 8000 << Attr << 1; 8001 Attr.setInvalid(); 8002 return; 8003 } 8004 8005 // The vector size must be an integer constant expression. 8006 llvm::APSInt SveVectorSizeInBits(32); 8007 if (!verifyValidIntegerConstantExpr(S, Attr, SveVectorSizeInBits)) 8008 return; 8009 8010 unsigned VecSize = static_cast<unsigned>(SveVectorSizeInBits.getZExtValue()); 8011 8012 // The attribute vector size must match -msve-vector-bits. 8013 if (VecSize != S.getLangOpts().VScaleMin * 128) { 8014 S.Diag(Attr.getLoc(), diag::err_attribute_bad_sve_vector_size) 8015 << VecSize << S.getLangOpts().VScaleMin * 128; 8016 Attr.setInvalid(); 8017 return; 8018 } 8019 8020 // Attribute can only be attached to a single SVE vector or predicate type. 8021 if (!CurType->isVLSTBuiltinType()) { 8022 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_sve_type) 8023 << Attr << CurType; 8024 Attr.setInvalid(); 8025 return; 8026 } 8027 8028 const auto *BT = CurType->castAs<BuiltinType>(); 8029 8030 QualType EltType = CurType->getSveEltType(S.Context); 8031 unsigned TypeSize = S.Context.getTypeSize(EltType); 8032 VectorType::VectorKind VecKind = VectorType::SveFixedLengthDataVector; 8033 if (BT->getKind() == BuiltinType::SveBool) { 8034 // Predicates are represented as i8. 8035 VecSize /= S.Context.getCharWidth() * S.Context.getCharWidth(); 8036 VecKind = VectorType::SveFixedLengthPredicateVector; 8037 } else 8038 VecSize /= TypeSize; 8039 CurType = S.Context.getVectorType(EltType, VecSize, VecKind); 8040 } 8041 8042 static void HandleArmMveStrictPolymorphismAttr(TypeProcessingState &State, 8043 QualType &CurType, 8044 ParsedAttr &Attr) { 8045 const VectorType *VT = dyn_cast<VectorType>(CurType); 8046 if (!VT || VT->getVectorKind() != VectorType::NeonVector) { 8047 State.getSema().Diag(Attr.getLoc(), 8048 diag::err_attribute_arm_mve_polymorphism); 8049 Attr.setInvalid(); 8050 return; 8051 } 8052 8053 CurType = 8054 State.getAttributedType(createSimpleAttr<ArmMveStrictPolymorphismAttr>( 8055 State.getSema().Context, Attr), 8056 CurType, CurType); 8057 } 8058 8059 /// Handle OpenCL Access Qualifier Attribute. 8060 static void HandleOpenCLAccessAttr(QualType &CurType, const ParsedAttr &Attr, 8061 Sema &S) { 8062 // OpenCL v2.0 s6.6 - Access qualifier can be used only for image and pipe type. 8063 if (!(CurType->isImageType() || CurType->isPipeType())) { 8064 S.Diag(Attr.getLoc(), diag::err_opencl_invalid_access_qualifier); 8065 Attr.setInvalid(); 8066 return; 8067 } 8068 8069 if (const TypedefType* TypedefTy = CurType->getAs<TypedefType>()) { 8070 QualType BaseTy = TypedefTy->desugar(); 8071 8072 std::string PrevAccessQual; 8073 if (BaseTy->isPipeType()) { 8074 if (TypedefTy->getDecl()->hasAttr<OpenCLAccessAttr>()) { 8075 OpenCLAccessAttr *Attr = 8076 TypedefTy->getDecl()->getAttr<OpenCLAccessAttr>(); 8077 PrevAccessQual = Attr->getSpelling(); 8078 } else { 8079 PrevAccessQual = "read_only"; 8080 } 8081 } else if (const BuiltinType* ImgType = BaseTy->getAs<BuiltinType>()) { 8082 8083 switch (ImgType->getKind()) { 8084 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 8085 case BuiltinType::Id: \ 8086 PrevAccessQual = #Access; \ 8087 break; 8088 #include "clang/Basic/OpenCLImageTypes.def" 8089 default: 8090 llvm_unreachable("Unable to find corresponding image type."); 8091 } 8092 } else { 8093 llvm_unreachable("unexpected type"); 8094 } 8095 StringRef AttrName = Attr.getAttrName()->getName(); 8096 if (PrevAccessQual == AttrName.ltrim("_")) { 8097 // Duplicated qualifiers 8098 S.Diag(Attr.getLoc(), diag::warn_duplicate_declspec) 8099 << AttrName << Attr.getRange(); 8100 } else { 8101 // Contradicting qualifiers 8102 S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers); 8103 } 8104 8105 S.Diag(TypedefTy->getDecl()->getBeginLoc(), 8106 diag::note_opencl_typedef_access_qualifier) << PrevAccessQual; 8107 } else if (CurType->isPipeType()) { 8108 if (Attr.getSemanticSpelling() == OpenCLAccessAttr::Keyword_write_only) { 8109 QualType ElemType = CurType->castAs<PipeType>()->getElementType(); 8110 CurType = S.Context.getWritePipeType(ElemType); 8111 } 8112 } 8113 } 8114 8115 /// HandleMatrixTypeAttr - "matrix_type" attribute, like ext_vector_type 8116 static void HandleMatrixTypeAttr(QualType &CurType, const ParsedAttr &Attr, 8117 Sema &S) { 8118 if (!S.getLangOpts().MatrixTypes) { 8119 S.Diag(Attr.getLoc(), diag::err_builtin_matrix_disabled); 8120 return; 8121 } 8122 8123 if (Attr.getNumArgs() != 2) { 8124 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 8125 << Attr << 2; 8126 return; 8127 } 8128 8129 Expr *RowsExpr = Attr.getArgAsExpr(0); 8130 Expr *ColsExpr = Attr.getArgAsExpr(1); 8131 QualType T = S.BuildMatrixType(CurType, RowsExpr, ColsExpr, Attr.getLoc()); 8132 if (!T.isNull()) 8133 CurType = T; 8134 } 8135 8136 static void HandleLifetimeBoundAttr(TypeProcessingState &State, 8137 QualType &CurType, 8138 ParsedAttr &Attr) { 8139 if (State.getDeclarator().isDeclarationOfFunction()) { 8140 CurType = State.getAttributedType( 8141 createSimpleAttr<LifetimeBoundAttr>(State.getSema().Context, Attr), 8142 CurType, CurType); 8143 } 8144 } 8145 8146 static bool isAddressSpaceKind(const ParsedAttr &attr) { 8147 auto attrKind = attr.getKind(); 8148 8149 return attrKind == ParsedAttr::AT_AddressSpace || 8150 attrKind == ParsedAttr::AT_OpenCLPrivateAddressSpace || 8151 attrKind == ParsedAttr::AT_OpenCLGlobalAddressSpace || 8152 attrKind == ParsedAttr::AT_OpenCLGlobalDeviceAddressSpace || 8153 attrKind == ParsedAttr::AT_OpenCLGlobalHostAddressSpace || 8154 attrKind == ParsedAttr::AT_OpenCLLocalAddressSpace || 8155 attrKind == ParsedAttr::AT_OpenCLConstantAddressSpace || 8156 attrKind == ParsedAttr::AT_OpenCLGenericAddressSpace; 8157 } 8158 8159 static void processTypeAttrs(TypeProcessingState &state, QualType &type, 8160 TypeAttrLocation TAL, 8161 const ParsedAttributesView &attrs) { 8162 8163 state.setParsedNoDeref(false); 8164 if (attrs.empty()) 8165 return; 8166 8167 // Scan through and apply attributes to this type where it makes sense. Some 8168 // attributes (such as __address_space__, __vector_size__, etc) apply to the 8169 // type, but others can be present in the type specifiers even though they 8170 // apply to the decl. Here we apply type attributes and ignore the rest. 8171 8172 // This loop modifies the list pretty frequently, but we still need to make 8173 // sure we visit every element once. Copy the attributes list, and iterate 8174 // over that. 8175 ParsedAttributesView AttrsCopy{attrs}; 8176 for (ParsedAttr &attr : AttrsCopy) { 8177 8178 // Skip attributes that were marked to be invalid. 8179 if (attr.isInvalid()) 8180 continue; 8181 8182 if (attr.isStandardAttributeSyntax()) { 8183 // [[gnu::...]] attributes are treated as declaration attributes, so may 8184 // not appertain to a DeclaratorChunk. If we handle them as type 8185 // attributes, accept them in that position and diagnose the GCC 8186 // incompatibility. 8187 if (attr.isGNUScope()) { 8188 bool IsTypeAttr = attr.isTypeAttr(); 8189 if (TAL == TAL_DeclChunk) { 8190 state.getSema().Diag(attr.getLoc(), 8191 IsTypeAttr 8192 ? diag::warn_gcc_ignores_type_attr 8193 : diag::warn_cxx11_gnu_attribute_on_type) 8194 << attr; 8195 if (!IsTypeAttr) 8196 continue; 8197 } 8198 } else if (TAL != TAL_DeclChunk && !isAddressSpaceKind(attr)) { 8199 // Otherwise, only consider type processing for a C++11 attribute if 8200 // it's actually been applied to a type. 8201 // We also allow C++11 address_space and 8202 // OpenCL language address space attributes to pass through. 8203 continue; 8204 } 8205 } 8206 8207 // If this is an attribute we can handle, do so now, 8208 // otherwise, add it to the FnAttrs list for rechaining. 8209 switch (attr.getKind()) { 8210 default: 8211 // A [[]] attribute on a declarator chunk must appertain to a type. 8212 if (attr.isStandardAttributeSyntax() && TAL == TAL_DeclChunk) { 8213 state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr) 8214 << attr; 8215 attr.setUsedAsTypeAttr(); 8216 } 8217 break; 8218 8219 case ParsedAttr::UnknownAttribute: 8220 if (attr.isStandardAttributeSyntax() && TAL == TAL_DeclChunk) 8221 state.getSema().Diag(attr.getLoc(), 8222 diag::warn_unknown_attribute_ignored) 8223 << attr << attr.getRange(); 8224 break; 8225 8226 case ParsedAttr::IgnoredAttribute: 8227 break; 8228 8229 case ParsedAttr::AT_BTFTypeTag: 8230 HandleBTFTypeTagAttribute(type, attr, state); 8231 attr.setUsedAsTypeAttr(); 8232 break; 8233 8234 case ParsedAttr::AT_MayAlias: 8235 // FIXME: This attribute needs to actually be handled, but if we ignore 8236 // it it breaks large amounts of Linux software. 8237 attr.setUsedAsTypeAttr(); 8238 break; 8239 case ParsedAttr::AT_OpenCLPrivateAddressSpace: 8240 case ParsedAttr::AT_OpenCLGlobalAddressSpace: 8241 case ParsedAttr::AT_OpenCLGlobalDeviceAddressSpace: 8242 case ParsedAttr::AT_OpenCLGlobalHostAddressSpace: 8243 case ParsedAttr::AT_OpenCLLocalAddressSpace: 8244 case ParsedAttr::AT_OpenCLConstantAddressSpace: 8245 case ParsedAttr::AT_OpenCLGenericAddressSpace: 8246 case ParsedAttr::AT_AddressSpace: 8247 HandleAddressSpaceTypeAttribute(type, attr, state); 8248 attr.setUsedAsTypeAttr(); 8249 break; 8250 OBJC_POINTER_TYPE_ATTRS_CASELIST: 8251 if (!handleObjCPointerTypeAttr(state, attr, type)) 8252 distributeObjCPointerTypeAttr(state, attr, type); 8253 attr.setUsedAsTypeAttr(); 8254 break; 8255 case ParsedAttr::AT_VectorSize: 8256 HandleVectorSizeAttr(type, attr, state.getSema()); 8257 attr.setUsedAsTypeAttr(); 8258 break; 8259 case ParsedAttr::AT_ExtVectorType: 8260 HandleExtVectorTypeAttr(type, attr, state.getSema()); 8261 attr.setUsedAsTypeAttr(); 8262 break; 8263 case ParsedAttr::AT_NeonVectorType: 8264 HandleNeonVectorTypeAttr(type, attr, state.getSema(), 8265 VectorType::NeonVector); 8266 attr.setUsedAsTypeAttr(); 8267 break; 8268 case ParsedAttr::AT_NeonPolyVectorType: 8269 HandleNeonVectorTypeAttr(type, attr, state.getSema(), 8270 VectorType::NeonPolyVector); 8271 attr.setUsedAsTypeAttr(); 8272 break; 8273 case ParsedAttr::AT_ArmSveVectorBits: 8274 HandleArmSveVectorBitsTypeAttr(type, attr, state.getSema()); 8275 attr.setUsedAsTypeAttr(); 8276 break; 8277 case ParsedAttr::AT_ArmMveStrictPolymorphism: { 8278 HandleArmMveStrictPolymorphismAttr(state, type, attr); 8279 attr.setUsedAsTypeAttr(); 8280 break; 8281 } 8282 case ParsedAttr::AT_OpenCLAccess: 8283 HandleOpenCLAccessAttr(type, attr, state.getSema()); 8284 attr.setUsedAsTypeAttr(); 8285 break; 8286 case ParsedAttr::AT_LifetimeBound: 8287 if (TAL == TAL_DeclChunk) 8288 HandleLifetimeBoundAttr(state, type, attr); 8289 break; 8290 8291 case ParsedAttr::AT_NoDeref: { 8292 ASTContext &Ctx = state.getSema().Context; 8293 type = state.getAttributedType(createSimpleAttr<NoDerefAttr>(Ctx, attr), 8294 type, type); 8295 attr.setUsedAsTypeAttr(); 8296 state.setParsedNoDeref(true); 8297 break; 8298 } 8299 8300 case ParsedAttr::AT_MatrixType: 8301 HandleMatrixTypeAttr(type, attr, state.getSema()); 8302 attr.setUsedAsTypeAttr(); 8303 break; 8304 8305 MS_TYPE_ATTRS_CASELIST: 8306 if (!handleMSPointerTypeQualifierAttr(state, attr, type)) 8307 attr.setUsedAsTypeAttr(); 8308 break; 8309 8310 8311 NULLABILITY_TYPE_ATTRS_CASELIST: 8312 // Either add nullability here or try to distribute it. We 8313 // don't want to distribute the nullability specifier past any 8314 // dependent type, because that complicates the user model. 8315 if (type->canHaveNullability() || type->isDependentType() || 8316 type->isArrayType() || 8317 !distributeNullabilityTypeAttr(state, type, attr)) { 8318 unsigned endIndex; 8319 if (TAL == TAL_DeclChunk) 8320 endIndex = state.getCurrentChunkIndex(); 8321 else 8322 endIndex = state.getDeclarator().getNumTypeObjects(); 8323 bool allowOnArrayType = 8324 state.getDeclarator().isPrototypeContext() && 8325 !hasOuterPointerLikeChunk(state.getDeclarator(), endIndex); 8326 if (checkNullabilityTypeSpecifier( 8327 state, 8328 type, 8329 attr, 8330 allowOnArrayType)) { 8331 attr.setInvalid(); 8332 } 8333 8334 attr.setUsedAsTypeAttr(); 8335 } 8336 break; 8337 8338 case ParsedAttr::AT_ObjCKindOf: 8339 // '__kindof' must be part of the decl-specifiers. 8340 switch (TAL) { 8341 case TAL_DeclSpec: 8342 break; 8343 8344 case TAL_DeclChunk: 8345 case TAL_DeclName: 8346 state.getSema().Diag(attr.getLoc(), 8347 diag::err_objc_kindof_wrong_position) 8348 << FixItHint::CreateRemoval(attr.getLoc()) 8349 << FixItHint::CreateInsertion( 8350 state.getDeclarator().getDeclSpec().getBeginLoc(), 8351 "__kindof "); 8352 break; 8353 } 8354 8355 // Apply it regardless. 8356 if (checkObjCKindOfType(state, type, attr)) 8357 attr.setInvalid(); 8358 break; 8359 8360 case ParsedAttr::AT_NoThrow: 8361 // Exception Specifications aren't generally supported in C mode throughout 8362 // clang, so revert to attribute-based handling for C. 8363 if (!state.getSema().getLangOpts().CPlusPlus) 8364 break; 8365 LLVM_FALLTHROUGH; 8366 FUNCTION_TYPE_ATTRS_CASELIST: 8367 attr.setUsedAsTypeAttr(); 8368 8369 // Never process function type attributes as part of the 8370 // declaration-specifiers. 8371 if (TAL == TAL_DeclSpec) 8372 distributeFunctionTypeAttrFromDeclSpec(state, attr, type); 8373 8374 // Otherwise, handle the possible delays. 8375 else if (!handleFunctionTypeAttr(state, attr, type)) 8376 distributeFunctionTypeAttr(state, attr, type); 8377 break; 8378 case ParsedAttr::AT_AcquireHandle: { 8379 if (!type->isFunctionType()) 8380 return; 8381 8382 if (attr.getNumArgs() != 1) { 8383 state.getSema().Diag(attr.getLoc(), 8384 diag::err_attribute_wrong_number_arguments) 8385 << attr << 1; 8386 attr.setInvalid(); 8387 return; 8388 } 8389 8390 StringRef HandleType; 8391 if (!state.getSema().checkStringLiteralArgumentAttr(attr, 0, HandleType)) 8392 return; 8393 type = state.getAttributedType( 8394 AcquireHandleAttr::Create(state.getSema().Context, HandleType, attr), 8395 type, type); 8396 attr.setUsedAsTypeAttr(); 8397 break; 8398 } 8399 } 8400 8401 // Handle attributes that are defined in a macro. We do not want this to be 8402 // applied to ObjC builtin attributes. 8403 if (isa<AttributedType>(type) && attr.hasMacroIdentifier() && 8404 !type.getQualifiers().hasObjCLifetime() && 8405 !type.getQualifiers().hasObjCGCAttr() && 8406 attr.getKind() != ParsedAttr::AT_ObjCGC && 8407 attr.getKind() != ParsedAttr::AT_ObjCOwnership) { 8408 const IdentifierInfo *MacroII = attr.getMacroIdentifier(); 8409 type = state.getSema().Context.getMacroQualifiedType(type, MacroII); 8410 state.setExpansionLocForMacroQualifiedType( 8411 cast<MacroQualifiedType>(type.getTypePtr()), 8412 attr.getMacroExpansionLoc()); 8413 } 8414 } 8415 } 8416 8417 void Sema::completeExprArrayBound(Expr *E) { 8418 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 8419 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 8420 if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) { 8421 auto *Def = Var->getDefinition(); 8422 if (!Def) { 8423 SourceLocation PointOfInstantiation = E->getExprLoc(); 8424 runWithSufficientStackSpace(PointOfInstantiation, [&] { 8425 InstantiateVariableDefinition(PointOfInstantiation, Var); 8426 }); 8427 Def = Var->getDefinition(); 8428 8429 // If we don't already have a point of instantiation, and we managed 8430 // to instantiate a definition, this is the point of instantiation. 8431 // Otherwise, we don't request an end-of-TU instantiation, so this is 8432 // not a point of instantiation. 8433 // FIXME: Is this really the right behavior? 8434 if (Var->getPointOfInstantiation().isInvalid() && Def) { 8435 assert(Var->getTemplateSpecializationKind() == 8436 TSK_ImplicitInstantiation && 8437 "explicit instantiation with no point of instantiation"); 8438 Var->setTemplateSpecializationKind( 8439 Var->getTemplateSpecializationKind(), PointOfInstantiation); 8440 } 8441 } 8442 8443 // Update the type to the definition's type both here and within the 8444 // expression. 8445 if (Def) { 8446 DRE->setDecl(Def); 8447 QualType T = Def->getType(); 8448 DRE->setType(T); 8449 // FIXME: Update the type on all intervening expressions. 8450 E->setType(T); 8451 } 8452 8453 // We still go on to try to complete the type independently, as it 8454 // may also require instantiations or diagnostics if it remains 8455 // incomplete. 8456 } 8457 } 8458 } 8459 } 8460 8461 QualType Sema::getCompletedType(Expr *E) { 8462 // Incomplete array types may be completed by the initializer attached to 8463 // their definitions. For static data members of class templates and for 8464 // variable templates, we need to instantiate the definition to get this 8465 // initializer and complete the type. 8466 if (E->getType()->isIncompleteArrayType()) 8467 completeExprArrayBound(E); 8468 8469 // FIXME: Are there other cases which require instantiating something other 8470 // than the type to complete the type of an expression? 8471 8472 return E->getType(); 8473 } 8474 8475 /// Ensure that the type of the given expression is complete. 8476 /// 8477 /// This routine checks whether the expression \p E has a complete type. If the 8478 /// expression refers to an instantiable construct, that instantiation is 8479 /// performed as needed to complete its type. Furthermore 8480 /// Sema::RequireCompleteType is called for the expression's type (or in the 8481 /// case of a reference type, the referred-to type). 8482 /// 8483 /// \param E The expression whose type is required to be complete. 8484 /// \param Kind Selects which completeness rules should be applied. 8485 /// \param Diagnoser The object that will emit a diagnostic if the type is 8486 /// incomplete. 8487 /// 8488 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false 8489 /// otherwise. 8490 bool Sema::RequireCompleteExprType(Expr *E, CompleteTypeKind Kind, 8491 TypeDiagnoser &Diagnoser) { 8492 return RequireCompleteType(E->getExprLoc(), getCompletedType(E), Kind, 8493 Diagnoser); 8494 } 8495 8496 bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) { 8497 BoundTypeDiagnoser<> Diagnoser(DiagID); 8498 return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser); 8499 } 8500 8501 /// Ensure that the type T is a complete type. 8502 /// 8503 /// This routine checks whether the type @p T is complete in any 8504 /// context where a complete type is required. If @p T is a complete 8505 /// type, returns false. If @p T is a class template specialization, 8506 /// this routine then attempts to perform class template 8507 /// instantiation. If instantiation fails, or if @p T is incomplete 8508 /// and cannot be completed, issues the diagnostic @p diag (giving it 8509 /// the type @p T) and returns true. 8510 /// 8511 /// @param Loc The location in the source that the incomplete type 8512 /// diagnostic should refer to. 8513 /// 8514 /// @param T The type that this routine is examining for completeness. 8515 /// 8516 /// @param Kind Selects which completeness rules should be applied. 8517 /// 8518 /// @returns @c true if @p T is incomplete and a diagnostic was emitted, 8519 /// @c false otherwise. 8520 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, 8521 CompleteTypeKind Kind, 8522 TypeDiagnoser &Diagnoser) { 8523 if (RequireCompleteTypeImpl(Loc, T, Kind, &Diagnoser)) 8524 return true; 8525 if (const TagType *Tag = T->getAs<TagType>()) { 8526 if (!Tag->getDecl()->isCompleteDefinitionRequired()) { 8527 Tag->getDecl()->setCompleteDefinitionRequired(); 8528 Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl()); 8529 } 8530 } 8531 return false; 8532 } 8533 8534 bool Sema::hasStructuralCompatLayout(Decl *D, Decl *Suggested) { 8535 llvm::DenseSet<std::pair<Decl *, Decl *>> NonEquivalentDecls; 8536 if (!Suggested) 8537 return false; 8538 8539 // FIXME: Add a specific mode for C11 6.2.7/1 in StructuralEquivalenceContext 8540 // and isolate from other C++ specific checks. 8541 StructuralEquivalenceContext Ctx( 8542 D->getASTContext(), Suggested->getASTContext(), NonEquivalentDecls, 8543 StructuralEquivalenceKind::Default, 8544 false /*StrictTypeSpelling*/, true /*Complain*/, 8545 true /*ErrorOnTagTypeMismatch*/); 8546 return Ctx.IsEquivalent(D, Suggested); 8547 } 8548 8549 /// Determine whether there is any declaration of \p D that was ever a 8550 /// definition (perhaps before module merging) and is currently visible. 8551 /// \param D The definition of the entity. 8552 /// \param Suggested Filled in with the declaration that should be made visible 8553 /// in order to provide a definition of this entity. 8554 /// \param OnlyNeedComplete If \c true, we only need the type to be complete, 8555 /// not defined. This only matters for enums with a fixed underlying 8556 /// type, since in all other cases, a type is complete if and only if it 8557 /// is defined. 8558 bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, 8559 bool OnlyNeedComplete) { 8560 // Easy case: if we don't have modules, all declarations are visible. 8561 if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility) 8562 return true; 8563 8564 // If this definition was instantiated from a template, map back to the 8565 // pattern from which it was instantiated. 8566 if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined()) { 8567 // We're in the middle of defining it; this definition should be treated 8568 // as visible. 8569 return true; 8570 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 8571 if (auto *Pattern = RD->getTemplateInstantiationPattern()) 8572 RD = Pattern; 8573 D = RD->getDefinition(); 8574 } else if (auto *ED = dyn_cast<EnumDecl>(D)) { 8575 if (auto *Pattern = ED->getTemplateInstantiationPattern()) 8576 ED = Pattern; 8577 if (OnlyNeedComplete && (ED->isFixed() || getLangOpts().MSVCCompat)) { 8578 // If the enum has a fixed underlying type, it may have been forward 8579 // declared. In -fms-compatibility, `enum Foo;` will also forward declare 8580 // the enum and assign it the underlying type of `int`. Since we're only 8581 // looking for a complete type (not a definition), any visible declaration 8582 // of it will do. 8583 *Suggested = nullptr; 8584 for (auto *Redecl : ED->redecls()) { 8585 if (isVisible(Redecl)) 8586 return true; 8587 if (Redecl->isThisDeclarationADefinition() || 8588 (Redecl->isCanonicalDecl() && !*Suggested)) 8589 *Suggested = Redecl; 8590 } 8591 return false; 8592 } 8593 D = ED->getDefinition(); 8594 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) { 8595 if (auto *Pattern = FD->getTemplateInstantiationPattern()) 8596 FD = Pattern; 8597 D = FD->getDefinition(); 8598 } else if (auto *VD = dyn_cast<VarDecl>(D)) { 8599 if (auto *Pattern = VD->getTemplateInstantiationPattern()) 8600 VD = Pattern; 8601 D = VD->getDefinition(); 8602 } 8603 assert(D && "missing definition for pattern of instantiated definition"); 8604 8605 *Suggested = D; 8606 8607 auto DefinitionIsVisible = [&] { 8608 // The (primary) definition might be in a visible module. 8609 if (isVisible(D)) 8610 return true; 8611 8612 // A visible module might have a merged definition instead. 8613 if (D->isModulePrivate() ? hasMergedDefinitionInCurrentModule(D) 8614 : hasVisibleMergedDefinition(D)) { 8615 if (CodeSynthesisContexts.empty() && 8616 !getLangOpts().ModulesLocalVisibility) { 8617 // Cache the fact that this definition is implicitly visible because 8618 // there is a visible merged definition. 8619 D->setVisibleDespiteOwningModule(); 8620 } 8621 return true; 8622 } 8623 8624 return false; 8625 }; 8626 8627 if (DefinitionIsVisible()) 8628 return true; 8629 8630 // The external source may have additional definitions of this entity that are 8631 // visible, so complete the redeclaration chain now and ask again. 8632 if (auto *Source = Context.getExternalSource()) { 8633 Source->CompleteRedeclChain(D); 8634 return DefinitionIsVisible(); 8635 } 8636 8637 return false; 8638 } 8639 8640 /// Locks in the inheritance model for the given class and all of its bases. 8641 static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) { 8642 RD = RD->getMostRecentNonInjectedDecl(); 8643 if (!RD->hasAttr<MSInheritanceAttr>()) { 8644 MSInheritanceModel IM; 8645 bool BestCase = false; 8646 switch (S.MSPointerToMemberRepresentationMethod) { 8647 case LangOptions::PPTMK_BestCase: 8648 BestCase = true; 8649 IM = RD->calculateInheritanceModel(); 8650 break; 8651 case LangOptions::PPTMK_FullGeneralitySingleInheritance: 8652 IM = MSInheritanceModel::Single; 8653 break; 8654 case LangOptions::PPTMK_FullGeneralityMultipleInheritance: 8655 IM = MSInheritanceModel::Multiple; 8656 break; 8657 case LangOptions::PPTMK_FullGeneralityVirtualInheritance: 8658 IM = MSInheritanceModel::Unspecified; 8659 break; 8660 } 8661 8662 SourceRange Loc = S.ImplicitMSInheritanceAttrLoc.isValid() 8663 ? S.ImplicitMSInheritanceAttrLoc 8664 : RD->getSourceRange(); 8665 RD->addAttr(MSInheritanceAttr::CreateImplicit( 8666 S.getASTContext(), BestCase, Loc, AttributeCommonInfo::AS_Microsoft, 8667 MSInheritanceAttr::Spelling(IM))); 8668 S.Consumer.AssignInheritanceModel(RD); 8669 } 8670 } 8671 8672 /// The implementation of RequireCompleteType 8673 bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T, 8674 CompleteTypeKind Kind, 8675 TypeDiagnoser *Diagnoser) { 8676 // FIXME: Add this assertion to make sure we always get instantiation points. 8677 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType"); 8678 // FIXME: Add this assertion to help us flush out problems with 8679 // checking for dependent types and type-dependent expressions. 8680 // 8681 // assert(!T->isDependentType() && 8682 // "Can't ask whether a dependent type is complete"); 8683 8684 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) { 8685 if (!MPTy->getClass()->isDependentType()) { 8686 if (getLangOpts().CompleteMemberPointers && 8687 !MPTy->getClass()->getAsCXXRecordDecl()->isBeingDefined() && 8688 RequireCompleteType(Loc, QualType(MPTy->getClass(), 0), Kind, 8689 diag::err_memptr_incomplete)) 8690 return true; 8691 8692 // We lock in the inheritance model once somebody has asked us to ensure 8693 // that a pointer-to-member type is complete. 8694 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 8695 (void)isCompleteType(Loc, QualType(MPTy->getClass(), 0)); 8696 assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl()); 8697 } 8698 } 8699 } 8700 8701 NamedDecl *Def = nullptr; 8702 bool AcceptSizeless = (Kind == CompleteTypeKind::AcceptSizeless); 8703 bool Incomplete = (T->isIncompleteType(&Def) || 8704 (!AcceptSizeless && T->isSizelessBuiltinType())); 8705 8706 // Check that any necessary explicit specializations are visible. For an 8707 // enum, we just need the declaration, so don't check this. 8708 if (Def && !isa<EnumDecl>(Def)) 8709 checkSpecializationVisibility(Loc, Def); 8710 8711 // If we have a complete type, we're done. 8712 if (!Incomplete) { 8713 // If we know about the definition but it is not visible, complain. 8714 NamedDecl *SuggestedDef = nullptr; 8715 if (Def && 8716 !hasVisibleDefinition(Def, &SuggestedDef, /*OnlyNeedComplete*/true)) { 8717 // If the user is going to see an error here, recover by making the 8718 // definition visible. 8719 bool TreatAsComplete = Diagnoser && !isSFINAEContext(); 8720 if (Diagnoser && SuggestedDef) 8721 diagnoseMissingImport(Loc, SuggestedDef, MissingImportKind::Definition, 8722 /*Recover*/TreatAsComplete); 8723 return !TreatAsComplete; 8724 } else if (Def && !TemplateInstCallbacks.empty()) { 8725 CodeSynthesisContext TempInst; 8726 TempInst.Kind = CodeSynthesisContext::Memoization; 8727 TempInst.Template = Def; 8728 TempInst.Entity = Def; 8729 TempInst.PointOfInstantiation = Loc; 8730 atTemplateBegin(TemplateInstCallbacks, *this, TempInst); 8731 atTemplateEnd(TemplateInstCallbacks, *this, TempInst); 8732 } 8733 8734 return false; 8735 } 8736 8737 TagDecl *Tag = dyn_cast_or_null<TagDecl>(Def); 8738 ObjCInterfaceDecl *IFace = dyn_cast_or_null<ObjCInterfaceDecl>(Def); 8739 8740 // Give the external source a chance to provide a definition of the type. 8741 // This is kept separate from completing the redeclaration chain so that 8742 // external sources such as LLDB can avoid synthesizing a type definition 8743 // unless it's actually needed. 8744 if (Tag || IFace) { 8745 // Avoid diagnosing invalid decls as incomplete. 8746 if (Def->isInvalidDecl()) 8747 return true; 8748 8749 // Give the external AST source a chance to complete the type. 8750 if (auto *Source = Context.getExternalSource()) { 8751 if (Tag && Tag->hasExternalLexicalStorage()) 8752 Source->CompleteType(Tag); 8753 if (IFace && IFace->hasExternalLexicalStorage()) 8754 Source->CompleteType(IFace); 8755 // If the external source completed the type, go through the motions 8756 // again to ensure we're allowed to use the completed type. 8757 if (!T->isIncompleteType()) 8758 return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser); 8759 } 8760 } 8761 8762 // If we have a class template specialization or a class member of a 8763 // class template specialization, or an array with known size of such, 8764 // try to instantiate it. 8765 if (auto *RD = dyn_cast_or_null<CXXRecordDecl>(Tag)) { 8766 bool Instantiated = false; 8767 bool Diagnosed = false; 8768 if (RD->isDependentContext()) { 8769 // Don't try to instantiate a dependent class (eg, a member template of 8770 // an instantiated class template specialization). 8771 // FIXME: Can this ever happen? 8772 } else if (auto *ClassTemplateSpec = 8773 dyn_cast<ClassTemplateSpecializationDecl>(RD)) { 8774 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) { 8775 runWithSufficientStackSpace(Loc, [&] { 8776 Diagnosed = InstantiateClassTemplateSpecialization( 8777 Loc, ClassTemplateSpec, TSK_ImplicitInstantiation, 8778 /*Complain=*/Diagnoser); 8779 }); 8780 Instantiated = true; 8781 } 8782 } else { 8783 CXXRecordDecl *Pattern = RD->getInstantiatedFromMemberClass(); 8784 if (!RD->isBeingDefined() && Pattern) { 8785 MemberSpecializationInfo *MSI = RD->getMemberSpecializationInfo(); 8786 assert(MSI && "Missing member specialization information?"); 8787 // This record was instantiated from a class within a template. 8788 if (MSI->getTemplateSpecializationKind() != 8789 TSK_ExplicitSpecialization) { 8790 runWithSufficientStackSpace(Loc, [&] { 8791 Diagnosed = InstantiateClass(Loc, RD, Pattern, 8792 getTemplateInstantiationArgs(RD), 8793 TSK_ImplicitInstantiation, 8794 /*Complain=*/Diagnoser); 8795 }); 8796 Instantiated = true; 8797 } 8798 } 8799 } 8800 8801 if (Instantiated) { 8802 // Instantiate* might have already complained that the template is not 8803 // defined, if we asked it to. 8804 if (Diagnoser && Diagnosed) 8805 return true; 8806 // If we instantiated a definition, check that it's usable, even if 8807 // instantiation produced an error, so that repeated calls to this 8808 // function give consistent answers. 8809 if (!T->isIncompleteType()) 8810 return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser); 8811 } 8812 } 8813 8814 // FIXME: If we didn't instantiate a definition because of an explicit 8815 // specialization declaration, check that it's visible. 8816 8817 if (!Diagnoser) 8818 return true; 8819 8820 Diagnoser->diagnose(*this, Loc, T); 8821 8822 // If the type was a forward declaration of a class/struct/union 8823 // type, produce a note. 8824 if (Tag && !Tag->isInvalidDecl() && !Tag->getLocation().isInvalid()) 8825 Diag(Tag->getLocation(), 8826 Tag->isBeingDefined() ? diag::note_type_being_defined 8827 : diag::note_forward_declaration) 8828 << Context.getTagDeclType(Tag); 8829 8830 // If the Objective-C class was a forward declaration, produce a note. 8831 if (IFace && !IFace->isInvalidDecl() && !IFace->getLocation().isInvalid()) 8832 Diag(IFace->getLocation(), diag::note_forward_class); 8833 8834 // If we have external information that we can use to suggest a fix, 8835 // produce a note. 8836 if (ExternalSource) 8837 ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T); 8838 8839 return true; 8840 } 8841 8842 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, 8843 CompleteTypeKind Kind, unsigned DiagID) { 8844 BoundTypeDiagnoser<> Diagnoser(DiagID); 8845 return RequireCompleteType(Loc, T, Kind, Diagnoser); 8846 } 8847 8848 /// Get diagnostic %select index for tag kind for 8849 /// literal type diagnostic message. 8850 /// WARNING: Indexes apply to particular diagnostics only! 8851 /// 8852 /// \returns diagnostic %select index. 8853 static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) { 8854 switch (Tag) { 8855 case TTK_Struct: return 0; 8856 case TTK_Interface: return 1; 8857 case TTK_Class: return 2; 8858 default: llvm_unreachable("Invalid tag kind for literal type diagnostic!"); 8859 } 8860 } 8861 8862 /// Ensure that the type T is a literal type. 8863 /// 8864 /// This routine checks whether the type @p T is a literal type. If @p T is an 8865 /// incomplete type, an attempt is made to complete it. If @p T is a literal 8866 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type, 8867 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving 8868 /// it the type @p T), along with notes explaining why the type is not a 8869 /// literal type, and returns true. 8870 /// 8871 /// @param Loc The location in the source that the non-literal type 8872 /// diagnostic should refer to. 8873 /// 8874 /// @param T The type that this routine is examining for literalness. 8875 /// 8876 /// @param Diagnoser Emits a diagnostic if T is not a literal type. 8877 /// 8878 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted, 8879 /// @c false otherwise. 8880 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, 8881 TypeDiagnoser &Diagnoser) { 8882 assert(!T->isDependentType() && "type should not be dependent"); 8883 8884 QualType ElemType = Context.getBaseElementType(T); 8885 if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) && 8886 T->isLiteralType(Context)) 8887 return false; 8888 8889 Diagnoser.diagnose(*this, Loc, T); 8890 8891 if (T->isVariableArrayType()) 8892 return true; 8893 8894 const RecordType *RT = ElemType->getAs<RecordType>(); 8895 if (!RT) 8896 return true; 8897 8898 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 8899 8900 // A partially-defined class type can't be a literal type, because a literal 8901 // class type must have a trivial destructor (which can't be checked until 8902 // the class definition is complete). 8903 if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T)) 8904 return true; 8905 8906 // [expr.prim.lambda]p3: 8907 // This class type is [not] a literal type. 8908 if (RD->isLambda() && !getLangOpts().CPlusPlus17) { 8909 Diag(RD->getLocation(), diag::note_non_literal_lambda); 8910 return true; 8911 } 8912 8913 // If the class has virtual base classes, then it's not an aggregate, and 8914 // cannot have any constexpr constructors or a trivial default constructor, 8915 // so is non-literal. This is better to diagnose than the resulting absence 8916 // of constexpr constructors. 8917 if (RD->getNumVBases()) { 8918 Diag(RD->getLocation(), diag::note_non_literal_virtual_base) 8919 << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 8920 for (const auto &I : RD->vbases()) 8921 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here) 8922 << I.getSourceRange(); 8923 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() && 8924 !RD->hasTrivialDefaultConstructor()) { 8925 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD; 8926 } else if (RD->hasNonLiteralTypeFieldsOrBases()) { 8927 for (const auto &I : RD->bases()) { 8928 if (!I.getType()->isLiteralType(Context)) { 8929 Diag(I.getBeginLoc(), diag::note_non_literal_base_class) 8930 << RD << I.getType() << I.getSourceRange(); 8931 return true; 8932 } 8933 } 8934 for (const auto *I : RD->fields()) { 8935 if (!I->getType()->isLiteralType(Context) || 8936 I->getType().isVolatileQualified()) { 8937 Diag(I->getLocation(), diag::note_non_literal_field) 8938 << RD << I << I->getType() 8939 << I->getType().isVolatileQualified(); 8940 return true; 8941 } 8942 } 8943 } else if (getLangOpts().CPlusPlus20 ? !RD->hasConstexprDestructor() 8944 : !RD->hasTrivialDestructor()) { 8945 // All fields and bases are of literal types, so have trivial or constexpr 8946 // destructors. If this class's destructor is non-trivial / non-constexpr, 8947 // it must be user-declared. 8948 CXXDestructorDecl *Dtor = RD->getDestructor(); 8949 assert(Dtor && "class has literal fields and bases but no dtor?"); 8950 if (!Dtor) 8951 return true; 8952 8953 if (getLangOpts().CPlusPlus20) { 8954 Diag(Dtor->getLocation(), diag::note_non_literal_non_constexpr_dtor) 8955 << RD; 8956 } else { 8957 Diag(Dtor->getLocation(), Dtor->isUserProvided() 8958 ? diag::note_non_literal_user_provided_dtor 8959 : diag::note_non_literal_nontrivial_dtor) 8960 << RD; 8961 if (!Dtor->isUserProvided()) 8962 SpecialMemberIsTrivial(Dtor, CXXDestructor, TAH_IgnoreTrivialABI, 8963 /*Diagnose*/ true); 8964 } 8965 } 8966 8967 return true; 8968 } 8969 8970 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) { 8971 BoundTypeDiagnoser<> Diagnoser(DiagID); 8972 return RequireLiteralType(Loc, T, Diagnoser); 8973 } 8974 8975 /// Retrieve a version of the type 'T' that is elaborated by Keyword, qualified 8976 /// by the nested-name-specifier contained in SS, and that is (re)declared by 8977 /// OwnedTagDecl, which is nullptr if this is not a (re)declaration. 8978 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword, 8979 const CXXScopeSpec &SS, QualType T, 8980 TagDecl *OwnedTagDecl) { 8981 if (T.isNull()) 8982 return T; 8983 NestedNameSpecifier *NNS; 8984 if (SS.isValid()) 8985 NNS = SS.getScopeRep(); 8986 else { 8987 if (Keyword == ETK_None) 8988 return T; 8989 NNS = nullptr; 8990 } 8991 return Context.getElaboratedType(Keyword, NNS, T, OwnedTagDecl); 8992 } 8993 8994 QualType Sema::BuildTypeofExprType(Expr *E) { 8995 assert(!E->hasPlaceholderType() && "unexpected placeholder"); 8996 8997 if (!getLangOpts().CPlusPlus && E->refersToBitField()) 8998 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 2; 8999 9000 if (!E->isTypeDependent()) { 9001 QualType T = E->getType(); 9002 if (const TagType *TT = T->getAs<TagType>()) 9003 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc()); 9004 } 9005 return Context.getTypeOfExprType(E); 9006 } 9007 9008 /// getDecltypeForExpr - Given an expr, will return the decltype for 9009 /// that expression, according to the rules in C++11 9010 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18. 9011 QualType Sema::getDecltypeForExpr(Expr *E) { 9012 if (E->isTypeDependent()) 9013 return Context.DependentTy; 9014 9015 Expr *IDExpr = E; 9016 if (auto *ImplCastExpr = dyn_cast<ImplicitCastExpr>(E)) 9017 IDExpr = ImplCastExpr->getSubExpr(); 9018 9019 // C++11 [dcl.type.simple]p4: 9020 // The type denoted by decltype(e) is defined as follows: 9021 9022 // C++20: 9023 // - if E is an unparenthesized id-expression naming a non-type 9024 // template-parameter (13.2), decltype(E) is the type of the 9025 // template-parameter after performing any necessary type deduction 9026 // Note that this does not pick up the implicit 'const' for a template 9027 // parameter object. This rule makes no difference before C++20 so we apply 9028 // it unconditionally. 9029 if (const auto *SNTTPE = dyn_cast<SubstNonTypeTemplateParmExpr>(IDExpr)) 9030 return SNTTPE->getParameterType(Context); 9031 9032 // - if e is an unparenthesized id-expression or an unparenthesized class 9033 // member access (5.2.5), decltype(e) is the type of the entity named 9034 // by e. If there is no such entity, or if e names a set of overloaded 9035 // functions, the program is ill-formed; 9036 // 9037 // We apply the same rules for Objective-C ivar and property references. 9038 if (const auto *DRE = dyn_cast<DeclRefExpr>(IDExpr)) { 9039 const ValueDecl *VD = DRE->getDecl(); 9040 QualType T = VD->getType(); 9041 return isa<TemplateParamObjectDecl>(VD) ? T.getUnqualifiedType() : T; 9042 } 9043 if (const auto *ME = dyn_cast<MemberExpr>(IDExpr)) { 9044 if (const auto *VD = ME->getMemberDecl()) 9045 if (isa<FieldDecl>(VD) || isa<VarDecl>(VD)) 9046 return VD->getType(); 9047 } else if (const auto *IR = dyn_cast<ObjCIvarRefExpr>(IDExpr)) { 9048 return IR->getDecl()->getType(); 9049 } else if (const auto *PR = dyn_cast<ObjCPropertyRefExpr>(IDExpr)) { 9050 if (PR->isExplicitProperty()) 9051 return PR->getExplicitProperty()->getType(); 9052 } else if (const auto *PE = dyn_cast<PredefinedExpr>(IDExpr)) { 9053 return PE->getType(); 9054 } 9055 9056 // C++11 [expr.lambda.prim]p18: 9057 // Every occurrence of decltype((x)) where x is a possibly 9058 // parenthesized id-expression that names an entity of automatic 9059 // storage duration is treated as if x were transformed into an 9060 // access to a corresponding data member of the closure type that 9061 // would have been declared if x were an odr-use of the denoted 9062 // entity. 9063 if (getCurLambda() && isa<ParenExpr>(IDExpr)) { 9064 if (auto *DRE = dyn_cast<DeclRefExpr>(IDExpr->IgnoreParens())) { 9065 if (auto *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 9066 QualType T = getCapturedDeclRefType(Var, DRE->getLocation()); 9067 if (!T.isNull()) 9068 return Context.getLValueReferenceType(T); 9069 } 9070 } 9071 } 9072 9073 return Context.getReferenceQualifiedType(E); 9074 } 9075 9076 QualType Sema::BuildDecltypeType(Expr *E, bool AsUnevaluated) { 9077 assert(!E->hasPlaceholderType() && "unexpected placeholder"); 9078 9079 if (AsUnevaluated && CodeSynthesisContexts.empty() && 9080 !E->isInstantiationDependent() && E->HasSideEffects(Context, false)) { 9081 // The expression operand for decltype is in an unevaluated expression 9082 // context, so side effects could result in unintended consequences. 9083 // Exclude instantiation-dependent expressions, because 'decltype' is often 9084 // used to build SFINAE gadgets. 9085 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 9086 } 9087 return Context.getDecltypeType(E, getDecltypeForExpr(E)); 9088 } 9089 9090 QualType Sema::BuildUnaryTransformType(QualType BaseType, 9091 UnaryTransformType::UTTKind UKind, 9092 SourceLocation Loc) { 9093 switch (UKind) { 9094 case UnaryTransformType::EnumUnderlyingType: 9095 if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) { 9096 Diag(Loc, diag::err_only_enums_have_underlying_types); 9097 return QualType(); 9098 } else { 9099 QualType Underlying = BaseType; 9100 if (!BaseType->isDependentType()) { 9101 // The enum could be incomplete if we're parsing its definition or 9102 // recovering from an error. 9103 NamedDecl *FwdDecl = nullptr; 9104 if (BaseType->isIncompleteType(&FwdDecl)) { 9105 Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType; 9106 Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl; 9107 return QualType(); 9108 } 9109 9110 EnumDecl *ED = BaseType->castAs<EnumType>()->getDecl(); 9111 assert(ED && "EnumType has no EnumDecl"); 9112 9113 DiagnoseUseOfDecl(ED, Loc); 9114 9115 Underlying = ED->getIntegerType(); 9116 assert(!Underlying.isNull()); 9117 } 9118 return Context.getUnaryTransformType(BaseType, Underlying, 9119 UnaryTransformType::EnumUnderlyingType); 9120 } 9121 } 9122 llvm_unreachable("unknown unary transform type"); 9123 } 9124 9125 QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) { 9126 if (!isDependentOrGNUAutoType(T)) { 9127 // FIXME: It isn't entirely clear whether incomplete atomic types 9128 // are allowed or not; for simplicity, ban them for the moment. 9129 if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0)) 9130 return QualType(); 9131 9132 int DisallowedKind = -1; 9133 if (T->isArrayType()) 9134 DisallowedKind = 1; 9135 else if (T->isFunctionType()) 9136 DisallowedKind = 2; 9137 else if (T->isReferenceType()) 9138 DisallowedKind = 3; 9139 else if (T->isAtomicType()) 9140 DisallowedKind = 4; 9141 else if (T.hasQualifiers()) 9142 DisallowedKind = 5; 9143 else if (T->isSizelessType()) 9144 DisallowedKind = 6; 9145 else if (!T.isTriviallyCopyableType(Context)) 9146 // Some other non-trivially-copyable type (probably a C++ class) 9147 DisallowedKind = 7; 9148 else if (T->isBitIntType()) 9149 DisallowedKind = 8; 9150 9151 if (DisallowedKind != -1) { 9152 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T; 9153 return QualType(); 9154 } 9155 9156 // FIXME: Do we need any handling for ARC here? 9157 } 9158 9159 // Build the pointer type. 9160 return Context.getAtomicType(T); 9161 } 9162