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