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