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 Error = 15; // Generic 3542 break; 3543 case DeclaratorContext::File: 3544 case DeclaratorContext::Block: 3545 case DeclaratorContext::ForInit: 3546 case DeclaratorContext::SelectionInit: 3547 case DeclaratorContext::Condition: 3548 // FIXME: P0091R3 (erroneously) does not permit class template argument 3549 // deduction in conditions, for-init-statements, and other declarations 3550 // that are not simple-declarations. 3551 break; 3552 case DeclaratorContext::CXXNew: 3553 // FIXME: P0091R3 does not permit class template argument deduction here, 3554 // but we follow GCC and allow it anyway. 3555 if (!IsCXXAutoType && !isa<DeducedTemplateSpecializationType>(Deduced)) 3556 Error = 17; // 'new' type 3557 break; 3558 case DeclaratorContext::KNRTypeList: 3559 Error = 18; // K&R function parameter 3560 break; 3561 } 3562 3563 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 3564 Error = 11; 3565 3566 // In Objective-C it is an error to use 'auto' on a function declarator 3567 // (and everywhere for '__auto_type'). 3568 if (D.isFunctionDeclarator() && 3569 (!SemaRef.getLangOpts().CPlusPlus11 || !IsCXXAutoType)) 3570 Error = 13; 3571 3572 SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc(); 3573 if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId) 3574 AutoRange = D.getName().getSourceRange(); 3575 3576 if (Error != -1) { 3577 unsigned Kind; 3578 if (Auto) { 3579 switch (Auto->getKeyword()) { 3580 case AutoTypeKeyword::Auto: Kind = 0; break; 3581 case AutoTypeKeyword::DecltypeAuto: Kind = 1; break; 3582 case AutoTypeKeyword::GNUAutoType: Kind = 2; break; 3583 } 3584 } else { 3585 assert(isa<DeducedTemplateSpecializationType>(Deduced) && 3586 "unknown auto type"); 3587 Kind = 3; 3588 } 3589 3590 auto *DTST = dyn_cast<DeducedTemplateSpecializationType>(Deduced); 3591 TemplateName TN = DTST ? DTST->getTemplateName() : TemplateName(); 3592 3593 SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed) 3594 << Kind << Error << (int)SemaRef.getTemplateNameKindForDiagnostics(TN) 3595 << QualType(Deduced, 0) << AutoRange; 3596 if (auto *TD = TN.getAsTemplateDecl()) 3597 SemaRef.Diag(TD->getLocation(), diag::note_template_decl_here); 3598 3599 T = SemaRef.Context.IntTy; 3600 D.setInvalidType(true); 3601 } else if (Auto && D.getContext() != DeclaratorContext::LambdaExpr) { 3602 // If there was a trailing return type, we already got 3603 // warn_cxx98_compat_trailing_return_type in the parser. 3604 SemaRef.Diag(AutoRange.getBegin(), 3605 D.getContext() == DeclaratorContext::LambdaExprParameter 3606 ? diag::warn_cxx11_compat_generic_lambda 3607 : IsDeducedReturnType 3608 ? diag::warn_cxx11_compat_deduced_return_type 3609 : diag::warn_cxx98_compat_auto_type_specifier) 3610 << AutoRange; 3611 } 3612 } 3613 3614 if (SemaRef.getLangOpts().CPlusPlus && 3615 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) { 3616 // Check the contexts where C++ forbids the declaration of a new class 3617 // or enumeration in a type-specifier-seq. 3618 unsigned DiagID = 0; 3619 switch (D.getContext()) { 3620 case DeclaratorContext::TrailingReturn: 3621 case DeclaratorContext::TrailingReturnVar: 3622 // Class and enumeration definitions are syntactically not allowed in 3623 // trailing return types. 3624 llvm_unreachable("parser should not have allowed this"); 3625 break; 3626 case DeclaratorContext::File: 3627 case DeclaratorContext::Member: 3628 case DeclaratorContext::Block: 3629 case DeclaratorContext::ForInit: 3630 case DeclaratorContext::SelectionInit: 3631 case DeclaratorContext::BlockLiteral: 3632 case DeclaratorContext::LambdaExpr: 3633 // C++11 [dcl.type]p3: 3634 // A type-specifier-seq shall not define a class or enumeration unless 3635 // it appears in the type-id of an alias-declaration (7.1.3) that is not 3636 // the declaration of a template-declaration. 3637 case DeclaratorContext::AliasDecl: 3638 break; 3639 case DeclaratorContext::AliasTemplate: 3640 DiagID = diag::err_type_defined_in_alias_template; 3641 break; 3642 case DeclaratorContext::TypeName: 3643 case DeclaratorContext::FunctionalCast: 3644 case DeclaratorContext::ConversionId: 3645 case DeclaratorContext::TemplateParam: 3646 case DeclaratorContext::CXXNew: 3647 case DeclaratorContext::CXXCatch: 3648 case DeclaratorContext::ObjCCatch: 3649 case DeclaratorContext::TemplateArg: 3650 case DeclaratorContext::TemplateTypeArg: 3651 DiagID = diag::err_type_defined_in_type_specifier; 3652 break; 3653 case DeclaratorContext::Prototype: 3654 case DeclaratorContext::LambdaExprParameter: 3655 case DeclaratorContext::ObjCParameter: 3656 case DeclaratorContext::ObjCResult: 3657 case DeclaratorContext::KNRTypeList: 3658 case DeclaratorContext::RequiresExpr: 3659 // C++ [dcl.fct]p6: 3660 // Types shall not be defined in return or parameter types. 3661 DiagID = diag::err_type_defined_in_param_type; 3662 break; 3663 case DeclaratorContext::Condition: 3664 // C++ 6.4p2: 3665 // The type-specifier-seq shall not contain typedef and shall not declare 3666 // a new class or enumeration. 3667 DiagID = diag::err_type_defined_in_condition; 3668 break; 3669 } 3670 3671 if (DiagID != 0) { 3672 SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID) 3673 << SemaRef.Context.getTypeDeclType(OwnedTagDecl); 3674 D.setInvalidType(true); 3675 } 3676 } 3677 3678 assert(!T.isNull() && "This function should not return a null type"); 3679 return T; 3680 } 3681 3682 /// Produce an appropriate diagnostic for an ambiguity between a function 3683 /// declarator and a C++ direct-initializer. 3684 static void warnAboutAmbiguousFunction(Sema &S, Declarator &D, 3685 DeclaratorChunk &DeclType, QualType RT) { 3686 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 3687 assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity"); 3688 3689 // If the return type is void there is no ambiguity. 3690 if (RT->isVoidType()) 3691 return; 3692 3693 // An initializer for a non-class type can have at most one argument. 3694 if (!RT->isRecordType() && FTI.NumParams > 1) 3695 return; 3696 3697 // An initializer for a reference must have exactly one argument. 3698 if (RT->isReferenceType() && FTI.NumParams != 1) 3699 return; 3700 3701 // Only warn if this declarator is declaring a function at block scope, and 3702 // doesn't have a storage class (such as 'extern') specified. 3703 if (!D.isFunctionDeclarator() || 3704 D.getFunctionDefinitionKind() != FunctionDefinitionKind::Declaration || 3705 !S.CurContext->isFunctionOrMethod() || 3706 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_unspecified) 3707 return; 3708 3709 // Inside a condition, a direct initializer is not permitted. We allow one to 3710 // be parsed in order to give better diagnostics in condition parsing. 3711 if (D.getContext() == DeclaratorContext::Condition) 3712 return; 3713 3714 SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc); 3715 3716 S.Diag(DeclType.Loc, 3717 FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration 3718 : diag::warn_empty_parens_are_function_decl) 3719 << ParenRange; 3720 3721 // If the declaration looks like: 3722 // T var1, 3723 // f(); 3724 // and name lookup finds a function named 'f', then the ',' was 3725 // probably intended to be a ';'. 3726 if (!D.isFirstDeclarator() && D.getIdentifier()) { 3727 FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr); 3728 FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr); 3729 if (Comma.getFileID() != Name.getFileID() || 3730 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) { 3731 LookupResult Result(S, D.getIdentifier(), SourceLocation(), 3732 Sema::LookupOrdinaryName); 3733 if (S.LookupName(Result, S.getCurScope())) 3734 S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call) 3735 << FixItHint::CreateReplacement(D.getCommaLoc(), ";") 3736 << D.getIdentifier(); 3737 Result.suppressDiagnostics(); 3738 } 3739 } 3740 3741 if (FTI.NumParams > 0) { 3742 // For a declaration with parameters, eg. "T var(T());", suggest adding 3743 // parens around the first parameter to turn the declaration into a 3744 // variable declaration. 3745 SourceRange Range = FTI.Params[0].Param->getSourceRange(); 3746 SourceLocation B = Range.getBegin(); 3747 SourceLocation E = S.getLocForEndOfToken(Range.getEnd()); 3748 // FIXME: Maybe we should suggest adding braces instead of parens 3749 // in C++11 for classes that don't have an initializer_list constructor. 3750 S.Diag(B, diag::note_additional_parens_for_variable_declaration) 3751 << FixItHint::CreateInsertion(B, "(") 3752 << FixItHint::CreateInsertion(E, ")"); 3753 } else { 3754 // For a declaration without parameters, eg. "T var();", suggest replacing 3755 // the parens with an initializer to turn the declaration into a variable 3756 // declaration. 3757 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl(); 3758 3759 // Empty parens mean value-initialization, and no parens mean 3760 // default initialization. These are equivalent if the default 3761 // constructor is user-provided or if zero-initialization is a 3762 // no-op. 3763 if (RD && RD->hasDefinition() && 3764 (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor())) 3765 S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor) 3766 << FixItHint::CreateRemoval(ParenRange); 3767 else { 3768 std::string Init = 3769 S.getFixItZeroInitializerForType(RT, ParenRange.getBegin()); 3770 if (Init.empty() && S.LangOpts.CPlusPlus11) 3771 Init = "{}"; 3772 if (!Init.empty()) 3773 S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize) 3774 << FixItHint::CreateReplacement(ParenRange, Init); 3775 } 3776 } 3777 } 3778 3779 /// Produce an appropriate diagnostic for a declarator with top-level 3780 /// parentheses. 3781 static void warnAboutRedundantParens(Sema &S, Declarator &D, QualType T) { 3782 DeclaratorChunk &Paren = D.getTypeObject(D.getNumTypeObjects() - 1); 3783 assert(Paren.Kind == DeclaratorChunk::Paren && 3784 "do not have redundant top-level parentheses"); 3785 3786 // This is a syntactic check; we're not interested in cases that arise 3787 // during template instantiation. 3788 if (S.inTemplateInstantiation()) 3789 return; 3790 3791 // Check whether this could be intended to be a construction of a temporary 3792 // object in C++ via a function-style cast. 3793 bool CouldBeTemporaryObject = 3794 S.getLangOpts().CPlusPlus && D.isExpressionContext() && 3795 !D.isInvalidType() && D.getIdentifier() && 3796 D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier && 3797 (T->isRecordType() || T->isDependentType()) && 3798 D.getDeclSpec().getTypeQualifiers() == 0 && D.isFirstDeclarator(); 3799 3800 bool StartsWithDeclaratorId = true; 3801 for (auto &C : D.type_objects()) { 3802 switch (C.Kind) { 3803 case DeclaratorChunk::Paren: 3804 if (&C == &Paren) 3805 continue; 3806 LLVM_FALLTHROUGH; 3807 case DeclaratorChunk::Pointer: 3808 StartsWithDeclaratorId = false; 3809 continue; 3810 3811 case DeclaratorChunk::Array: 3812 if (!C.Arr.NumElts) 3813 CouldBeTemporaryObject = false; 3814 continue; 3815 3816 case DeclaratorChunk::Reference: 3817 // FIXME: Suppress the warning here if there is no initializer; we're 3818 // going to give an error anyway. 3819 // We assume that something like 'T (&x) = y;' is highly likely to not 3820 // be intended to be a temporary object. 3821 CouldBeTemporaryObject = false; 3822 StartsWithDeclaratorId = false; 3823 continue; 3824 3825 case DeclaratorChunk::Function: 3826 // In a new-type-id, function chunks require parentheses. 3827 if (D.getContext() == DeclaratorContext::CXXNew) 3828 return; 3829 // FIXME: "A(f())" deserves a vexing-parse warning, not just a 3830 // redundant-parens warning, but we don't know whether the function 3831 // chunk was syntactically valid as an expression here. 3832 CouldBeTemporaryObject = false; 3833 continue; 3834 3835 case DeclaratorChunk::BlockPointer: 3836 case DeclaratorChunk::MemberPointer: 3837 case DeclaratorChunk::Pipe: 3838 // These cannot appear in expressions. 3839 CouldBeTemporaryObject = false; 3840 StartsWithDeclaratorId = false; 3841 continue; 3842 } 3843 } 3844 3845 // FIXME: If there is an initializer, assume that this is not intended to be 3846 // a construction of a temporary object. 3847 3848 // Check whether the name has already been declared; if not, this is not a 3849 // function-style cast. 3850 if (CouldBeTemporaryObject) { 3851 LookupResult Result(S, D.getIdentifier(), SourceLocation(), 3852 Sema::LookupOrdinaryName); 3853 if (!S.LookupName(Result, S.getCurScope())) 3854 CouldBeTemporaryObject = false; 3855 Result.suppressDiagnostics(); 3856 } 3857 3858 SourceRange ParenRange(Paren.Loc, Paren.EndLoc); 3859 3860 if (!CouldBeTemporaryObject) { 3861 // If we have A (::B), the parentheses affect the meaning of the program. 3862 // Suppress the warning in that case. Don't bother looking at the DeclSpec 3863 // here: even (e.g.) "int ::x" is visually ambiguous even though it's 3864 // formally unambiguous. 3865 if (StartsWithDeclaratorId && D.getCXXScopeSpec().isValid()) { 3866 for (NestedNameSpecifier *NNS = D.getCXXScopeSpec().getScopeRep(); NNS; 3867 NNS = NNS->getPrefix()) { 3868 if (NNS->getKind() == NestedNameSpecifier::Global) 3869 return; 3870 } 3871 } 3872 3873 S.Diag(Paren.Loc, diag::warn_redundant_parens_around_declarator) 3874 << ParenRange << FixItHint::CreateRemoval(Paren.Loc) 3875 << FixItHint::CreateRemoval(Paren.EndLoc); 3876 return; 3877 } 3878 3879 S.Diag(Paren.Loc, diag::warn_parens_disambiguated_as_variable_declaration) 3880 << ParenRange << D.getIdentifier(); 3881 auto *RD = T->getAsCXXRecordDecl(); 3882 if (!RD || !RD->hasDefinition() || RD->hasNonTrivialDestructor()) 3883 S.Diag(Paren.Loc, diag::note_raii_guard_add_name) 3884 << FixItHint::CreateInsertion(Paren.Loc, " varname") << T 3885 << D.getIdentifier(); 3886 // FIXME: A cast to void is probably a better suggestion in cases where it's 3887 // valid (when there is no initializer and we're not in a condition). 3888 S.Diag(D.getBeginLoc(), diag::note_function_style_cast_add_parentheses) 3889 << FixItHint::CreateInsertion(D.getBeginLoc(), "(") 3890 << FixItHint::CreateInsertion(S.getLocForEndOfToken(D.getEndLoc()), ")"); 3891 S.Diag(Paren.Loc, diag::note_remove_parens_for_variable_declaration) 3892 << FixItHint::CreateRemoval(Paren.Loc) 3893 << FixItHint::CreateRemoval(Paren.EndLoc); 3894 } 3895 3896 /// Helper for figuring out the default CC for a function declarator type. If 3897 /// this is the outermost chunk, then we can determine the CC from the 3898 /// declarator context. If not, then this could be either a member function 3899 /// type or normal function type. 3900 static CallingConv getCCForDeclaratorChunk( 3901 Sema &S, Declarator &D, const ParsedAttributesView &AttrList, 3902 const DeclaratorChunk::FunctionTypeInfo &FTI, unsigned ChunkIndex) { 3903 assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function); 3904 3905 // Check for an explicit CC attribute. 3906 for (const ParsedAttr &AL : AttrList) { 3907 switch (AL.getKind()) { 3908 CALLING_CONV_ATTRS_CASELIST : { 3909 // Ignore attributes that don't validate or can't apply to the 3910 // function type. We'll diagnose the failure to apply them in 3911 // handleFunctionTypeAttr. 3912 CallingConv CC; 3913 if (!S.CheckCallingConvAttr(AL, CC) && 3914 (!FTI.isVariadic || supportsVariadicCall(CC))) { 3915 return CC; 3916 } 3917 break; 3918 } 3919 3920 default: 3921 break; 3922 } 3923 } 3924 3925 bool IsCXXInstanceMethod = false; 3926 3927 if (S.getLangOpts().CPlusPlus) { 3928 // Look inwards through parentheses to see if this chunk will form a 3929 // member pointer type or if we're the declarator. Any type attributes 3930 // between here and there will override the CC we choose here. 3931 unsigned I = ChunkIndex; 3932 bool FoundNonParen = false; 3933 while (I && !FoundNonParen) { 3934 --I; 3935 if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren) 3936 FoundNonParen = true; 3937 } 3938 3939 if (FoundNonParen) { 3940 // If we're not the declarator, we're a regular function type unless we're 3941 // in a member pointer. 3942 IsCXXInstanceMethod = 3943 D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer; 3944 } else if (D.getContext() == DeclaratorContext::LambdaExpr) { 3945 // This can only be a call operator for a lambda, which is an instance 3946 // method. 3947 IsCXXInstanceMethod = true; 3948 } else { 3949 // We're the innermost decl chunk, so must be a function declarator. 3950 assert(D.isFunctionDeclarator()); 3951 3952 // If we're inside a record, we're declaring a method, but it could be 3953 // explicitly or implicitly static. 3954 IsCXXInstanceMethod = 3955 D.isFirstDeclarationOfMember() && 3956 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 3957 !D.isStaticMember(); 3958 } 3959 } 3960 3961 CallingConv CC = S.Context.getDefaultCallingConvention(FTI.isVariadic, 3962 IsCXXInstanceMethod); 3963 3964 // Attribute AT_OpenCLKernel affects the calling convention for SPIR 3965 // and AMDGPU targets, hence it cannot be treated as a calling 3966 // convention attribute. This is the simplest place to infer 3967 // calling convention for OpenCL kernels. 3968 if (S.getLangOpts().OpenCL) { 3969 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) { 3970 if (AL.getKind() == ParsedAttr::AT_OpenCLKernel) { 3971 CC = CC_OpenCLKernel; 3972 break; 3973 } 3974 } 3975 } else if (S.getLangOpts().CUDA) { 3976 // If we're compiling CUDA/HIP code and targeting SPIR-V we need to make 3977 // sure the kernels will be marked with the right calling convention so that 3978 // they will be visible by the APIs that ingest SPIR-V. 3979 llvm::Triple Triple = S.Context.getTargetInfo().getTriple(); 3980 if (Triple.getArch() == llvm::Triple::spirv32 || 3981 Triple.getArch() == llvm::Triple::spirv64) { 3982 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) { 3983 if (AL.getKind() == ParsedAttr::AT_CUDAGlobal) { 3984 CC = CC_OpenCLKernel; 3985 break; 3986 } 3987 } 3988 } 3989 } 3990 3991 return CC; 3992 } 3993 3994 namespace { 3995 /// A simple notion of pointer kinds, which matches up with the various 3996 /// pointer declarators. 3997 enum class SimplePointerKind { 3998 Pointer, 3999 BlockPointer, 4000 MemberPointer, 4001 Array, 4002 }; 4003 } // end anonymous namespace 4004 4005 IdentifierInfo *Sema::getNullabilityKeyword(NullabilityKind nullability) { 4006 switch (nullability) { 4007 case NullabilityKind::NonNull: 4008 if (!Ident__Nonnull) 4009 Ident__Nonnull = PP.getIdentifierInfo("_Nonnull"); 4010 return Ident__Nonnull; 4011 4012 case NullabilityKind::Nullable: 4013 if (!Ident__Nullable) 4014 Ident__Nullable = PP.getIdentifierInfo("_Nullable"); 4015 return Ident__Nullable; 4016 4017 case NullabilityKind::NullableResult: 4018 if (!Ident__Nullable_result) 4019 Ident__Nullable_result = PP.getIdentifierInfo("_Nullable_result"); 4020 return Ident__Nullable_result; 4021 4022 case NullabilityKind::Unspecified: 4023 if (!Ident__Null_unspecified) 4024 Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified"); 4025 return Ident__Null_unspecified; 4026 } 4027 llvm_unreachable("Unknown nullability kind."); 4028 } 4029 4030 /// Retrieve the identifier "NSError". 4031 IdentifierInfo *Sema::getNSErrorIdent() { 4032 if (!Ident_NSError) 4033 Ident_NSError = PP.getIdentifierInfo("NSError"); 4034 4035 return Ident_NSError; 4036 } 4037 4038 /// Check whether there is a nullability attribute of any kind in the given 4039 /// attribute list. 4040 static bool hasNullabilityAttr(const ParsedAttributesView &attrs) { 4041 for (const ParsedAttr &AL : attrs) { 4042 if (AL.getKind() == ParsedAttr::AT_TypeNonNull || 4043 AL.getKind() == ParsedAttr::AT_TypeNullable || 4044 AL.getKind() == ParsedAttr::AT_TypeNullableResult || 4045 AL.getKind() == ParsedAttr::AT_TypeNullUnspecified) 4046 return true; 4047 } 4048 4049 return false; 4050 } 4051 4052 namespace { 4053 /// Describes the kind of a pointer a declarator describes. 4054 enum class PointerDeclaratorKind { 4055 // Not a pointer. 4056 NonPointer, 4057 // Single-level pointer. 4058 SingleLevelPointer, 4059 // Multi-level pointer (of any pointer kind). 4060 MultiLevelPointer, 4061 // CFFooRef* 4062 MaybePointerToCFRef, 4063 // CFErrorRef* 4064 CFErrorRefPointer, 4065 // NSError** 4066 NSErrorPointerPointer, 4067 }; 4068 4069 /// Describes a declarator chunk wrapping a pointer that marks inference as 4070 /// unexpected. 4071 // These values must be kept in sync with diagnostics. 4072 enum class PointerWrappingDeclaratorKind { 4073 /// Pointer is top-level. 4074 None = -1, 4075 /// Pointer is an array element. 4076 Array = 0, 4077 /// Pointer is the referent type of a C++ reference. 4078 Reference = 1 4079 }; 4080 } // end anonymous namespace 4081 4082 /// Classify the given declarator, whose type-specified is \c type, based on 4083 /// what kind of pointer it refers to. 4084 /// 4085 /// This is used to determine the default nullability. 4086 static PointerDeclaratorKind 4087 classifyPointerDeclarator(Sema &S, QualType type, Declarator &declarator, 4088 PointerWrappingDeclaratorKind &wrappingKind) { 4089 unsigned numNormalPointers = 0; 4090 4091 // For any dependent type, we consider it a non-pointer. 4092 if (type->isDependentType()) 4093 return PointerDeclaratorKind::NonPointer; 4094 4095 // Look through the declarator chunks to identify pointers. 4096 for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) { 4097 DeclaratorChunk &chunk = declarator.getTypeObject(i); 4098 switch (chunk.Kind) { 4099 case DeclaratorChunk::Array: 4100 if (numNormalPointers == 0) 4101 wrappingKind = PointerWrappingDeclaratorKind::Array; 4102 break; 4103 4104 case DeclaratorChunk::Function: 4105 case DeclaratorChunk::Pipe: 4106 break; 4107 4108 case DeclaratorChunk::BlockPointer: 4109 case DeclaratorChunk::MemberPointer: 4110 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer 4111 : PointerDeclaratorKind::SingleLevelPointer; 4112 4113 case DeclaratorChunk::Paren: 4114 break; 4115 4116 case DeclaratorChunk::Reference: 4117 if (numNormalPointers == 0) 4118 wrappingKind = PointerWrappingDeclaratorKind::Reference; 4119 break; 4120 4121 case DeclaratorChunk::Pointer: 4122 ++numNormalPointers; 4123 if (numNormalPointers > 2) 4124 return PointerDeclaratorKind::MultiLevelPointer; 4125 break; 4126 } 4127 } 4128 4129 // Then, dig into the type specifier itself. 4130 unsigned numTypeSpecifierPointers = 0; 4131 do { 4132 // Decompose normal pointers. 4133 if (auto ptrType = type->getAs<PointerType>()) { 4134 ++numNormalPointers; 4135 4136 if (numNormalPointers > 2) 4137 return PointerDeclaratorKind::MultiLevelPointer; 4138 4139 type = ptrType->getPointeeType(); 4140 ++numTypeSpecifierPointers; 4141 continue; 4142 } 4143 4144 // Decompose block pointers. 4145 if (type->getAs<BlockPointerType>()) { 4146 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer 4147 : PointerDeclaratorKind::SingleLevelPointer; 4148 } 4149 4150 // Decompose member pointers. 4151 if (type->getAs<MemberPointerType>()) { 4152 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer 4153 : PointerDeclaratorKind::SingleLevelPointer; 4154 } 4155 4156 // Look at Objective-C object pointers. 4157 if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) { 4158 ++numNormalPointers; 4159 ++numTypeSpecifierPointers; 4160 4161 // If this is NSError**, report that. 4162 if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) { 4163 if (objcClassDecl->getIdentifier() == S.getNSErrorIdent() && 4164 numNormalPointers == 2 && numTypeSpecifierPointers < 2) { 4165 return PointerDeclaratorKind::NSErrorPointerPointer; 4166 } 4167 } 4168 4169 break; 4170 } 4171 4172 // Look at Objective-C class types. 4173 if (auto objcClass = type->getAs<ObjCInterfaceType>()) { 4174 if (objcClass->getInterface()->getIdentifier() == S.getNSErrorIdent()) { 4175 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2) 4176 return PointerDeclaratorKind::NSErrorPointerPointer; 4177 } 4178 4179 break; 4180 } 4181 4182 // If at this point we haven't seen a pointer, we won't see one. 4183 if (numNormalPointers == 0) 4184 return PointerDeclaratorKind::NonPointer; 4185 4186 if (auto recordType = type->getAs<RecordType>()) { 4187 RecordDecl *recordDecl = recordType->getDecl(); 4188 4189 // If this is CFErrorRef*, report it as such. 4190 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2 && 4191 S.isCFError(recordDecl)) { 4192 return PointerDeclaratorKind::CFErrorRefPointer; 4193 } 4194 break; 4195 } 4196 4197 break; 4198 } while (true); 4199 4200 switch (numNormalPointers) { 4201 case 0: 4202 return PointerDeclaratorKind::NonPointer; 4203 4204 case 1: 4205 return PointerDeclaratorKind::SingleLevelPointer; 4206 4207 case 2: 4208 return PointerDeclaratorKind::MaybePointerToCFRef; 4209 4210 default: 4211 return PointerDeclaratorKind::MultiLevelPointer; 4212 } 4213 } 4214 4215 bool Sema::isCFError(RecordDecl *RD) { 4216 // If we already know about CFError, test it directly. 4217 if (CFError) 4218 return CFError == RD; 4219 4220 // Check whether this is CFError, which we identify based on its bridge to 4221 // NSError. CFErrorRef used to be declared with "objc_bridge" but is now 4222 // declared with "objc_bridge_mutable", so look for either one of the two 4223 // attributes. 4224 if (RD->getTagKind() == TTK_Struct) { 4225 IdentifierInfo *bridgedType = nullptr; 4226 if (auto bridgeAttr = RD->getAttr<ObjCBridgeAttr>()) 4227 bridgedType = bridgeAttr->getBridgedType(); 4228 else if (auto bridgeAttr = RD->getAttr<ObjCBridgeMutableAttr>()) 4229 bridgedType = bridgeAttr->getBridgedType(); 4230 4231 if (bridgedType == getNSErrorIdent()) { 4232 CFError = RD; 4233 return true; 4234 } 4235 } 4236 4237 return false; 4238 } 4239 4240 static FileID getNullabilityCompletenessCheckFileID(Sema &S, 4241 SourceLocation loc) { 4242 // If we're anywhere in a function, method, or closure context, don't perform 4243 // completeness checks. 4244 for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) { 4245 if (ctx->isFunctionOrMethod()) 4246 return FileID(); 4247 4248 if (ctx->isFileContext()) 4249 break; 4250 } 4251 4252 // We only care about the expansion location. 4253 loc = S.SourceMgr.getExpansionLoc(loc); 4254 FileID file = S.SourceMgr.getFileID(loc); 4255 if (file.isInvalid()) 4256 return FileID(); 4257 4258 // Retrieve file information. 4259 bool invalid = false; 4260 const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid); 4261 if (invalid || !sloc.isFile()) 4262 return FileID(); 4263 4264 // We don't want to perform completeness checks on the main file or in 4265 // system headers. 4266 const SrcMgr::FileInfo &fileInfo = sloc.getFile(); 4267 if (fileInfo.getIncludeLoc().isInvalid()) 4268 return FileID(); 4269 if (fileInfo.getFileCharacteristic() != SrcMgr::C_User && 4270 S.Diags.getSuppressSystemWarnings()) { 4271 return FileID(); 4272 } 4273 4274 return file; 4275 } 4276 4277 /// Creates a fix-it to insert a C-style nullability keyword at \p pointerLoc, 4278 /// taking into account whitespace before and after. 4279 template <typename DiagBuilderT> 4280 static void fixItNullability(Sema &S, DiagBuilderT &Diag, 4281 SourceLocation PointerLoc, 4282 NullabilityKind Nullability) { 4283 assert(PointerLoc.isValid()); 4284 if (PointerLoc.isMacroID()) 4285 return; 4286 4287 SourceLocation FixItLoc = S.getLocForEndOfToken(PointerLoc); 4288 if (!FixItLoc.isValid() || FixItLoc == PointerLoc) 4289 return; 4290 4291 const char *NextChar = S.SourceMgr.getCharacterData(FixItLoc); 4292 if (!NextChar) 4293 return; 4294 4295 SmallString<32> InsertionTextBuf{" "}; 4296 InsertionTextBuf += getNullabilitySpelling(Nullability); 4297 InsertionTextBuf += " "; 4298 StringRef InsertionText = InsertionTextBuf.str(); 4299 4300 if (isWhitespace(*NextChar)) { 4301 InsertionText = InsertionText.drop_back(); 4302 } else if (NextChar[-1] == '[') { 4303 if (NextChar[0] == ']') 4304 InsertionText = InsertionText.drop_back().drop_front(); 4305 else 4306 InsertionText = InsertionText.drop_front(); 4307 } else if (!isAsciiIdentifierContinue(NextChar[0], /*allow dollar*/ true) && 4308 !isAsciiIdentifierContinue(NextChar[-1], /*allow dollar*/ true)) { 4309 InsertionText = InsertionText.drop_back().drop_front(); 4310 } 4311 4312 Diag << FixItHint::CreateInsertion(FixItLoc, InsertionText); 4313 } 4314 4315 static void emitNullabilityConsistencyWarning(Sema &S, 4316 SimplePointerKind PointerKind, 4317 SourceLocation PointerLoc, 4318 SourceLocation PointerEndLoc) { 4319 assert(PointerLoc.isValid()); 4320 4321 if (PointerKind == SimplePointerKind::Array) { 4322 S.Diag(PointerLoc, diag::warn_nullability_missing_array); 4323 } else { 4324 S.Diag(PointerLoc, diag::warn_nullability_missing) 4325 << static_cast<unsigned>(PointerKind); 4326 } 4327 4328 auto FixItLoc = PointerEndLoc.isValid() ? PointerEndLoc : PointerLoc; 4329 if (FixItLoc.isMacroID()) 4330 return; 4331 4332 auto addFixIt = [&](NullabilityKind Nullability) { 4333 auto Diag = S.Diag(FixItLoc, diag::note_nullability_fix_it); 4334 Diag << static_cast<unsigned>(Nullability); 4335 Diag << static_cast<unsigned>(PointerKind); 4336 fixItNullability(S, Diag, FixItLoc, Nullability); 4337 }; 4338 addFixIt(NullabilityKind::Nullable); 4339 addFixIt(NullabilityKind::NonNull); 4340 } 4341 4342 /// Complains about missing nullability if the file containing \p pointerLoc 4343 /// has other uses of nullability (either the keywords or the \c assume_nonnull 4344 /// pragma). 4345 /// 4346 /// If the file has \e not seen other uses of nullability, this particular 4347 /// pointer is saved for possible later diagnosis. See recordNullabilitySeen(). 4348 static void 4349 checkNullabilityConsistency(Sema &S, SimplePointerKind pointerKind, 4350 SourceLocation pointerLoc, 4351 SourceLocation pointerEndLoc = SourceLocation()) { 4352 // Determine which file we're performing consistency checking for. 4353 FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc); 4354 if (file.isInvalid()) 4355 return; 4356 4357 // If we haven't seen any type nullability in this file, we won't warn now 4358 // about anything. 4359 FileNullability &fileNullability = S.NullabilityMap[file]; 4360 if (!fileNullability.SawTypeNullability) { 4361 // If this is the first pointer declarator in the file, and the appropriate 4362 // warning is on, record it in case we need to diagnose it retroactively. 4363 diag::kind diagKind; 4364 if (pointerKind == SimplePointerKind::Array) 4365 diagKind = diag::warn_nullability_missing_array; 4366 else 4367 diagKind = diag::warn_nullability_missing; 4368 4369 if (fileNullability.PointerLoc.isInvalid() && 4370 !S.Context.getDiagnostics().isIgnored(diagKind, pointerLoc)) { 4371 fileNullability.PointerLoc = pointerLoc; 4372 fileNullability.PointerEndLoc = pointerEndLoc; 4373 fileNullability.PointerKind = static_cast<unsigned>(pointerKind); 4374 } 4375 4376 return; 4377 } 4378 4379 // Complain about missing nullability. 4380 emitNullabilityConsistencyWarning(S, pointerKind, pointerLoc, pointerEndLoc); 4381 } 4382 4383 /// Marks that a nullability feature has been used in the file containing 4384 /// \p loc. 4385 /// 4386 /// If this file already had pointer types in it that were missing nullability, 4387 /// the first such instance is retroactively diagnosed. 4388 /// 4389 /// \sa checkNullabilityConsistency 4390 static void recordNullabilitySeen(Sema &S, SourceLocation loc) { 4391 FileID file = getNullabilityCompletenessCheckFileID(S, loc); 4392 if (file.isInvalid()) 4393 return; 4394 4395 FileNullability &fileNullability = S.NullabilityMap[file]; 4396 if (fileNullability.SawTypeNullability) 4397 return; 4398 fileNullability.SawTypeNullability = true; 4399 4400 // If we haven't seen any type nullability before, now we have. Retroactively 4401 // diagnose the first unannotated pointer, if there was one. 4402 if (fileNullability.PointerLoc.isInvalid()) 4403 return; 4404 4405 auto kind = static_cast<SimplePointerKind>(fileNullability.PointerKind); 4406 emitNullabilityConsistencyWarning(S, kind, fileNullability.PointerLoc, 4407 fileNullability.PointerEndLoc); 4408 } 4409 4410 /// Returns true if any of the declarator chunks before \p endIndex include a 4411 /// level of indirection: array, pointer, reference, or pointer-to-member. 4412 /// 4413 /// Because declarator chunks are stored in outer-to-inner order, testing 4414 /// every chunk before \p endIndex is testing all chunks that embed the current 4415 /// chunk as part of their type. 4416 /// 4417 /// It is legal to pass the result of Declarator::getNumTypeObjects() as the 4418 /// end index, in which case all chunks are tested. 4419 static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex) { 4420 unsigned i = endIndex; 4421 while (i != 0) { 4422 // Walk outwards along the declarator chunks. 4423 --i; 4424 const DeclaratorChunk &DC = D.getTypeObject(i); 4425 switch (DC.Kind) { 4426 case DeclaratorChunk::Paren: 4427 break; 4428 case DeclaratorChunk::Array: 4429 case DeclaratorChunk::Pointer: 4430 case DeclaratorChunk::Reference: 4431 case DeclaratorChunk::MemberPointer: 4432 return true; 4433 case DeclaratorChunk::Function: 4434 case DeclaratorChunk::BlockPointer: 4435 case DeclaratorChunk::Pipe: 4436 // These are invalid anyway, so just ignore. 4437 break; 4438 } 4439 } 4440 return false; 4441 } 4442 4443 static bool IsNoDerefableChunk(DeclaratorChunk Chunk) { 4444 return (Chunk.Kind == DeclaratorChunk::Pointer || 4445 Chunk.Kind == DeclaratorChunk::Array); 4446 } 4447 4448 template<typename AttrT> 4449 static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) { 4450 AL.setUsedAsTypeAttr(); 4451 return ::new (Ctx) AttrT(Ctx, AL); 4452 } 4453 4454 static Attr *createNullabilityAttr(ASTContext &Ctx, ParsedAttr &Attr, 4455 NullabilityKind NK) { 4456 switch (NK) { 4457 case NullabilityKind::NonNull: 4458 return createSimpleAttr<TypeNonNullAttr>(Ctx, Attr); 4459 4460 case NullabilityKind::Nullable: 4461 return createSimpleAttr<TypeNullableAttr>(Ctx, Attr); 4462 4463 case NullabilityKind::NullableResult: 4464 return createSimpleAttr<TypeNullableResultAttr>(Ctx, Attr); 4465 4466 case NullabilityKind::Unspecified: 4467 return createSimpleAttr<TypeNullUnspecifiedAttr>(Ctx, Attr); 4468 } 4469 llvm_unreachable("unknown NullabilityKind"); 4470 } 4471 4472 // Diagnose whether this is a case with the multiple addr spaces. 4473 // Returns true if this is an invalid case. 4474 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified 4475 // by qualifiers for two or more different address spaces." 4476 static bool DiagnoseMultipleAddrSpaceAttributes(Sema &S, LangAS ASOld, 4477 LangAS ASNew, 4478 SourceLocation AttrLoc) { 4479 if (ASOld != LangAS::Default) { 4480 if (ASOld != ASNew) { 4481 S.Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers); 4482 return true; 4483 } 4484 // Emit a warning if they are identical; it's likely unintended. 4485 S.Diag(AttrLoc, 4486 diag::warn_attribute_address_multiple_identical_qualifiers); 4487 } 4488 return false; 4489 } 4490 4491 static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state, 4492 QualType declSpecType, 4493 TypeSourceInfo *TInfo) { 4494 // The TypeSourceInfo that this function returns will not be a null type. 4495 // If there is an error, this function will fill in a dummy type as fallback. 4496 QualType T = declSpecType; 4497 Declarator &D = state.getDeclarator(); 4498 Sema &S = state.getSema(); 4499 ASTContext &Context = S.Context; 4500 const LangOptions &LangOpts = S.getLangOpts(); 4501 4502 // The name we're declaring, if any. 4503 DeclarationName Name; 4504 if (D.getIdentifier()) 4505 Name = D.getIdentifier(); 4506 4507 // Does this declaration declare a typedef-name? 4508 bool IsTypedefName = 4509 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef || 4510 D.getContext() == DeclaratorContext::AliasDecl || 4511 D.getContext() == DeclaratorContext::AliasTemplate; 4512 4513 // Does T refer to a function type with a cv-qualifier or a ref-qualifier? 4514 bool IsQualifiedFunction = T->isFunctionProtoType() && 4515 (!T->castAs<FunctionProtoType>()->getMethodQuals().empty() || 4516 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None); 4517 4518 // If T is 'decltype(auto)', the only declarators we can have are parens 4519 // and at most one function declarator if this is a function declaration. 4520 // If T is a deduced class template specialization type, we can have no 4521 // declarator chunks at all. 4522 if (auto *DT = T->getAs<DeducedType>()) { 4523 const AutoType *AT = T->getAs<AutoType>(); 4524 bool IsClassTemplateDeduction = isa<DeducedTemplateSpecializationType>(DT); 4525 if ((AT && AT->isDecltypeAuto()) || IsClassTemplateDeduction) { 4526 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 4527 unsigned Index = E - I - 1; 4528 DeclaratorChunk &DeclChunk = D.getTypeObject(Index); 4529 unsigned DiagId = IsClassTemplateDeduction 4530 ? diag::err_deduced_class_template_compound_type 4531 : diag::err_decltype_auto_compound_type; 4532 unsigned DiagKind = 0; 4533 switch (DeclChunk.Kind) { 4534 case DeclaratorChunk::Paren: 4535 // FIXME: Rejecting this is a little silly. 4536 if (IsClassTemplateDeduction) { 4537 DiagKind = 4; 4538 break; 4539 } 4540 continue; 4541 case DeclaratorChunk::Function: { 4542 if (IsClassTemplateDeduction) { 4543 DiagKind = 3; 4544 break; 4545 } 4546 unsigned FnIndex; 4547 if (D.isFunctionDeclarationContext() && 4548 D.isFunctionDeclarator(FnIndex) && FnIndex == Index) 4549 continue; 4550 DiagId = diag::err_decltype_auto_function_declarator_not_declaration; 4551 break; 4552 } 4553 case DeclaratorChunk::Pointer: 4554 case DeclaratorChunk::BlockPointer: 4555 case DeclaratorChunk::MemberPointer: 4556 DiagKind = 0; 4557 break; 4558 case DeclaratorChunk::Reference: 4559 DiagKind = 1; 4560 break; 4561 case DeclaratorChunk::Array: 4562 DiagKind = 2; 4563 break; 4564 case DeclaratorChunk::Pipe: 4565 break; 4566 } 4567 4568 S.Diag(DeclChunk.Loc, DiagId) << DiagKind; 4569 D.setInvalidType(true); 4570 break; 4571 } 4572 } 4573 } 4574 4575 // Determine whether we should infer _Nonnull on pointer types. 4576 Optional<NullabilityKind> inferNullability; 4577 bool inferNullabilityCS = false; 4578 bool inferNullabilityInnerOnly = false; 4579 bool inferNullabilityInnerOnlyComplete = false; 4580 4581 // Are we in an assume-nonnull region? 4582 bool inAssumeNonNullRegion = false; 4583 SourceLocation assumeNonNullLoc = S.PP.getPragmaAssumeNonNullLoc(); 4584 if (assumeNonNullLoc.isValid()) { 4585 inAssumeNonNullRegion = true; 4586 recordNullabilitySeen(S, assumeNonNullLoc); 4587 } 4588 4589 // Whether to complain about missing nullability specifiers or not. 4590 enum { 4591 /// Never complain. 4592 CAMN_No, 4593 /// Complain on the inner pointers (but not the outermost 4594 /// pointer). 4595 CAMN_InnerPointers, 4596 /// Complain about any pointers that don't have nullability 4597 /// specified or inferred. 4598 CAMN_Yes 4599 } complainAboutMissingNullability = CAMN_No; 4600 unsigned NumPointersRemaining = 0; 4601 auto complainAboutInferringWithinChunk = PointerWrappingDeclaratorKind::None; 4602 4603 if (IsTypedefName) { 4604 // For typedefs, we do not infer any nullability (the default), 4605 // and we only complain about missing nullability specifiers on 4606 // inner pointers. 4607 complainAboutMissingNullability = CAMN_InnerPointers; 4608 4609 if (T->canHaveNullability(/*ResultIfUnknown*/false) && 4610 !T->getNullability(S.Context)) { 4611 // Note that we allow but don't require nullability on dependent types. 4612 ++NumPointersRemaining; 4613 } 4614 4615 for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) { 4616 DeclaratorChunk &chunk = D.getTypeObject(i); 4617 switch (chunk.Kind) { 4618 case DeclaratorChunk::Array: 4619 case DeclaratorChunk::Function: 4620 case DeclaratorChunk::Pipe: 4621 break; 4622 4623 case DeclaratorChunk::BlockPointer: 4624 case DeclaratorChunk::MemberPointer: 4625 ++NumPointersRemaining; 4626 break; 4627 4628 case DeclaratorChunk::Paren: 4629 case DeclaratorChunk::Reference: 4630 continue; 4631 4632 case DeclaratorChunk::Pointer: 4633 ++NumPointersRemaining; 4634 continue; 4635 } 4636 } 4637 } else { 4638 bool isFunctionOrMethod = false; 4639 switch (auto context = state.getDeclarator().getContext()) { 4640 case DeclaratorContext::ObjCParameter: 4641 case DeclaratorContext::ObjCResult: 4642 case DeclaratorContext::Prototype: 4643 case DeclaratorContext::TrailingReturn: 4644 case DeclaratorContext::TrailingReturnVar: 4645 isFunctionOrMethod = true; 4646 LLVM_FALLTHROUGH; 4647 4648 case DeclaratorContext::Member: 4649 if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) { 4650 complainAboutMissingNullability = CAMN_No; 4651 break; 4652 } 4653 4654 // Weak properties are inferred to be nullable. 4655 if (state.getDeclarator().isObjCWeakProperty() && inAssumeNonNullRegion) { 4656 inferNullability = NullabilityKind::Nullable; 4657 break; 4658 } 4659 4660 LLVM_FALLTHROUGH; 4661 4662 case DeclaratorContext::File: 4663 case DeclaratorContext::KNRTypeList: { 4664 complainAboutMissingNullability = CAMN_Yes; 4665 4666 // Nullability inference depends on the type and declarator. 4667 auto wrappingKind = PointerWrappingDeclaratorKind::None; 4668 switch (classifyPointerDeclarator(S, T, D, wrappingKind)) { 4669 case PointerDeclaratorKind::NonPointer: 4670 case PointerDeclaratorKind::MultiLevelPointer: 4671 // Cannot infer nullability. 4672 break; 4673 4674 case PointerDeclaratorKind::SingleLevelPointer: 4675 // Infer _Nonnull if we are in an assumes-nonnull region. 4676 if (inAssumeNonNullRegion) { 4677 complainAboutInferringWithinChunk = wrappingKind; 4678 inferNullability = NullabilityKind::NonNull; 4679 inferNullabilityCS = (context == DeclaratorContext::ObjCParameter || 4680 context == DeclaratorContext::ObjCResult); 4681 } 4682 break; 4683 4684 case PointerDeclaratorKind::CFErrorRefPointer: 4685 case PointerDeclaratorKind::NSErrorPointerPointer: 4686 // Within a function or method signature, infer _Nullable at both 4687 // levels. 4688 if (isFunctionOrMethod && inAssumeNonNullRegion) 4689 inferNullability = NullabilityKind::Nullable; 4690 break; 4691 4692 case PointerDeclaratorKind::MaybePointerToCFRef: 4693 if (isFunctionOrMethod) { 4694 // On pointer-to-pointer parameters marked cf_returns_retained or 4695 // cf_returns_not_retained, if the outer pointer is explicit then 4696 // infer the inner pointer as _Nullable. 4697 auto hasCFReturnsAttr = 4698 [](const ParsedAttributesView &AttrList) -> bool { 4699 return AttrList.hasAttribute(ParsedAttr::AT_CFReturnsRetained) || 4700 AttrList.hasAttribute(ParsedAttr::AT_CFReturnsNotRetained); 4701 }; 4702 if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) { 4703 if (hasCFReturnsAttr(D.getAttributes()) || 4704 hasCFReturnsAttr(InnermostChunk->getAttrs()) || 4705 hasCFReturnsAttr(D.getDeclSpec().getAttributes())) { 4706 inferNullability = NullabilityKind::Nullable; 4707 inferNullabilityInnerOnly = true; 4708 } 4709 } 4710 } 4711 break; 4712 } 4713 break; 4714 } 4715 4716 case DeclaratorContext::ConversionId: 4717 complainAboutMissingNullability = CAMN_Yes; 4718 break; 4719 4720 case DeclaratorContext::AliasDecl: 4721 case DeclaratorContext::AliasTemplate: 4722 case DeclaratorContext::Block: 4723 case DeclaratorContext::BlockLiteral: 4724 case DeclaratorContext::Condition: 4725 case DeclaratorContext::CXXCatch: 4726 case DeclaratorContext::CXXNew: 4727 case DeclaratorContext::ForInit: 4728 case DeclaratorContext::SelectionInit: 4729 case DeclaratorContext::LambdaExpr: 4730 case DeclaratorContext::LambdaExprParameter: 4731 case DeclaratorContext::ObjCCatch: 4732 case DeclaratorContext::TemplateParam: 4733 case DeclaratorContext::TemplateArg: 4734 case DeclaratorContext::TemplateTypeArg: 4735 case DeclaratorContext::TypeName: 4736 case DeclaratorContext::FunctionalCast: 4737 case DeclaratorContext::RequiresExpr: 4738 // Don't infer in these contexts. 4739 break; 4740 } 4741 } 4742 4743 // Local function that returns true if its argument looks like a va_list. 4744 auto isVaList = [&S](QualType T) -> bool { 4745 auto *typedefTy = T->getAs<TypedefType>(); 4746 if (!typedefTy) 4747 return false; 4748 TypedefDecl *vaListTypedef = S.Context.getBuiltinVaListDecl(); 4749 do { 4750 if (typedefTy->getDecl() == vaListTypedef) 4751 return true; 4752 if (auto *name = typedefTy->getDecl()->getIdentifier()) 4753 if (name->isStr("va_list")) 4754 return true; 4755 typedefTy = typedefTy->desugar()->getAs<TypedefType>(); 4756 } while (typedefTy); 4757 return false; 4758 }; 4759 4760 // Local function that checks the nullability for a given pointer declarator. 4761 // Returns true if _Nonnull was inferred. 4762 auto inferPointerNullability = 4763 [&](SimplePointerKind pointerKind, SourceLocation pointerLoc, 4764 SourceLocation pointerEndLoc, 4765 ParsedAttributesView &attrs, AttributePool &Pool) -> ParsedAttr * { 4766 // We've seen a pointer. 4767 if (NumPointersRemaining > 0) 4768 --NumPointersRemaining; 4769 4770 // If a nullability attribute is present, there's nothing to do. 4771 if (hasNullabilityAttr(attrs)) 4772 return nullptr; 4773 4774 // If we're supposed to infer nullability, do so now. 4775 if (inferNullability && !inferNullabilityInnerOnlyComplete) { 4776 ParsedAttr::Syntax syntax = inferNullabilityCS 4777 ? ParsedAttr::AS_ContextSensitiveKeyword 4778 : ParsedAttr::AS_Keyword; 4779 ParsedAttr *nullabilityAttr = Pool.create( 4780 S.getNullabilityKeyword(*inferNullability), SourceRange(pointerLoc), 4781 nullptr, SourceLocation(), nullptr, 0, syntax); 4782 4783 attrs.addAtEnd(nullabilityAttr); 4784 4785 if (inferNullabilityCS) { 4786 state.getDeclarator().getMutableDeclSpec().getObjCQualifiers() 4787 ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability); 4788 } 4789 4790 if (pointerLoc.isValid() && 4791 complainAboutInferringWithinChunk != 4792 PointerWrappingDeclaratorKind::None) { 4793 auto Diag = 4794 S.Diag(pointerLoc, diag::warn_nullability_inferred_on_nested_type); 4795 Diag << static_cast<int>(complainAboutInferringWithinChunk); 4796 fixItNullability(S, Diag, pointerLoc, NullabilityKind::NonNull); 4797 } 4798 4799 if (inferNullabilityInnerOnly) 4800 inferNullabilityInnerOnlyComplete = true; 4801 return nullabilityAttr; 4802 } 4803 4804 // If we're supposed to complain about missing nullability, do so 4805 // now if it's truly missing. 4806 switch (complainAboutMissingNullability) { 4807 case CAMN_No: 4808 break; 4809 4810 case CAMN_InnerPointers: 4811 if (NumPointersRemaining == 0) 4812 break; 4813 LLVM_FALLTHROUGH; 4814 4815 case CAMN_Yes: 4816 checkNullabilityConsistency(S, pointerKind, pointerLoc, pointerEndLoc); 4817 } 4818 return nullptr; 4819 }; 4820 4821 // If the type itself could have nullability but does not, infer pointer 4822 // nullability and perform consistency checking. 4823 if (S.CodeSynthesisContexts.empty()) { 4824 if (T->canHaveNullability(/*ResultIfUnknown*/false) && 4825 !T->getNullability(S.Context)) { 4826 if (isVaList(T)) { 4827 // Record that we've seen a pointer, but do nothing else. 4828 if (NumPointersRemaining > 0) 4829 --NumPointersRemaining; 4830 } else { 4831 SimplePointerKind pointerKind = SimplePointerKind::Pointer; 4832 if (T->isBlockPointerType()) 4833 pointerKind = SimplePointerKind::BlockPointer; 4834 else if (T->isMemberPointerType()) 4835 pointerKind = SimplePointerKind::MemberPointer; 4836 4837 if (auto *attr = inferPointerNullability( 4838 pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(), 4839 D.getDeclSpec().getEndLoc(), 4840 D.getMutableDeclSpec().getAttributes(), 4841 D.getMutableDeclSpec().getAttributePool())) { 4842 T = state.getAttributedType( 4843 createNullabilityAttr(Context, *attr, *inferNullability), T, T); 4844 } 4845 } 4846 } 4847 4848 if (complainAboutMissingNullability == CAMN_Yes && 4849 T->isArrayType() && !T->getNullability(S.Context) && !isVaList(T) && 4850 D.isPrototypeContext() && 4851 !hasOuterPointerLikeChunk(D, D.getNumTypeObjects())) { 4852 checkNullabilityConsistency(S, SimplePointerKind::Array, 4853 D.getDeclSpec().getTypeSpecTypeLoc()); 4854 } 4855 } 4856 4857 bool ExpectNoDerefChunk = 4858 state.getCurrentAttributes().hasAttribute(ParsedAttr::AT_NoDeref); 4859 4860 // Walk the DeclTypeInfo, building the recursive type as we go. 4861 // DeclTypeInfos are ordered from the identifier out, which is 4862 // opposite of what we want :). 4863 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 4864 unsigned chunkIndex = e - i - 1; 4865 state.setCurrentChunkIndex(chunkIndex); 4866 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex); 4867 IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren; 4868 switch (DeclType.Kind) { 4869 case DeclaratorChunk::Paren: 4870 if (i == 0) 4871 warnAboutRedundantParens(S, D, T); 4872 T = S.BuildParenType(T); 4873 break; 4874 case DeclaratorChunk::BlockPointer: 4875 // If blocks are disabled, emit an error. 4876 if (!LangOpts.Blocks) 4877 S.Diag(DeclType.Loc, diag::err_blocks_disable) << LangOpts.OpenCL; 4878 4879 // Handle pointer nullability. 4880 inferPointerNullability(SimplePointerKind::BlockPointer, DeclType.Loc, 4881 DeclType.EndLoc, DeclType.getAttrs(), 4882 state.getDeclarator().getAttributePool()); 4883 4884 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name); 4885 if (DeclType.Cls.TypeQuals || LangOpts.OpenCL) { 4886 // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly 4887 // qualified with const. 4888 if (LangOpts.OpenCL) 4889 DeclType.Cls.TypeQuals |= DeclSpec::TQ_const; 4890 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals); 4891 } 4892 break; 4893 case DeclaratorChunk::Pointer: 4894 // Verify that we're not building a pointer to pointer to function with 4895 // exception specification. 4896 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { 4897 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 4898 D.setInvalidType(true); 4899 // Build the type anyway. 4900 } 4901 4902 // Handle pointer nullability 4903 inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc, 4904 DeclType.EndLoc, DeclType.getAttrs(), 4905 state.getDeclarator().getAttributePool()); 4906 4907 if (LangOpts.ObjC && T->getAs<ObjCObjectType>()) { 4908 T = Context.getObjCObjectPointerType(T); 4909 if (DeclType.Ptr.TypeQuals) 4910 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals); 4911 break; 4912 } 4913 4914 // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used. 4915 // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used. 4916 // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed. 4917 if (LangOpts.OpenCL) { 4918 if (T->isImageType() || T->isSamplerT() || T->isPipeType() || 4919 T->isBlockPointerType()) { 4920 S.Diag(D.getIdentifierLoc(), diag::err_opencl_pointer_to_type) << T; 4921 D.setInvalidType(true); 4922 } 4923 } 4924 4925 T = S.BuildPointerType(T, DeclType.Loc, Name); 4926 if (DeclType.Ptr.TypeQuals) 4927 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals); 4928 break; 4929 case DeclaratorChunk::Reference: { 4930 // Verify that we're not building a reference to pointer to function with 4931 // exception specification. 4932 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { 4933 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 4934 D.setInvalidType(true); 4935 // Build the type anyway. 4936 } 4937 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name); 4938 4939 if (DeclType.Ref.HasRestrict) 4940 T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict); 4941 break; 4942 } 4943 case DeclaratorChunk::Array: { 4944 // Verify that we're not building an array of pointers to function with 4945 // exception specification. 4946 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { 4947 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 4948 D.setInvalidType(true); 4949 // Build the type anyway. 4950 } 4951 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr; 4952 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts); 4953 ArrayType::ArraySizeModifier ASM; 4954 if (ATI.isStar) 4955 ASM = ArrayType::Star; 4956 else if (ATI.hasStatic) 4957 ASM = ArrayType::Static; 4958 else 4959 ASM = ArrayType::Normal; 4960 if (ASM == ArrayType::Star && !D.isPrototypeContext()) { 4961 // FIXME: This check isn't quite right: it allows star in prototypes 4962 // for function definitions, and disallows some edge cases detailed 4963 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html 4964 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype); 4965 ASM = ArrayType::Normal; 4966 D.setInvalidType(true); 4967 } 4968 4969 // C99 6.7.5.2p1: The optional type qualifiers and the keyword static 4970 // shall appear only in a declaration of a function parameter with an 4971 // array type, ... 4972 if (ASM == ArrayType::Static || ATI.TypeQuals) { 4973 if (!(D.isPrototypeContext() || 4974 D.getContext() == DeclaratorContext::KNRTypeList)) { 4975 S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) << 4976 (ASM == ArrayType::Static ? "'static'" : "type qualifier"); 4977 // Remove the 'static' and the type qualifiers. 4978 if (ASM == ArrayType::Static) 4979 ASM = ArrayType::Normal; 4980 ATI.TypeQuals = 0; 4981 D.setInvalidType(true); 4982 } 4983 4984 // C99 6.7.5.2p1: ... and then only in the outermost array type 4985 // derivation. 4986 if (hasOuterPointerLikeChunk(D, chunkIndex)) { 4987 S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) << 4988 (ASM == ArrayType::Static ? "'static'" : "type qualifier"); 4989 if (ASM == ArrayType::Static) 4990 ASM = ArrayType::Normal; 4991 ATI.TypeQuals = 0; 4992 D.setInvalidType(true); 4993 } 4994 } 4995 const AutoType *AT = T->getContainedAutoType(); 4996 // Allow arrays of auto if we are a generic lambda parameter. 4997 // i.e. [](auto (&array)[5]) { return array[0]; }; OK 4998 if (AT && D.getContext() != DeclaratorContext::LambdaExprParameter) { 4999 // We've already diagnosed this for decltype(auto). 5000 if (!AT->isDecltypeAuto()) 5001 S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto) 5002 << getPrintableNameForEntity(Name) << T; 5003 T = QualType(); 5004 break; 5005 } 5006 5007 // Array parameters can be marked nullable as well, although it's not 5008 // necessary if they're marked 'static'. 5009 if (complainAboutMissingNullability == CAMN_Yes && 5010 !hasNullabilityAttr(DeclType.getAttrs()) && 5011 ASM != ArrayType::Static && 5012 D.isPrototypeContext() && 5013 !hasOuterPointerLikeChunk(D, chunkIndex)) { 5014 checkNullabilityConsistency(S, SimplePointerKind::Array, DeclType.Loc); 5015 } 5016 5017 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals, 5018 SourceRange(DeclType.Loc, DeclType.EndLoc), Name); 5019 break; 5020 } 5021 case DeclaratorChunk::Function: { 5022 // If the function declarator has a prototype (i.e. it is not () and 5023 // does not have a K&R-style identifier list), then the arguments are part 5024 // of the type, otherwise the argument list is (). 5025 DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 5026 IsQualifiedFunction = 5027 FTI.hasMethodTypeQualifiers() || FTI.hasRefQualifier(); 5028 5029 // Check for auto functions and trailing return type and adjust the 5030 // return type accordingly. 5031 if (!D.isInvalidType()) { 5032 // trailing-return-type is only required if we're declaring a function, 5033 // and not, for instance, a pointer to a function. 5034 if (D.getDeclSpec().hasAutoTypeSpec() && 5035 !FTI.hasTrailingReturnType() && chunkIndex == 0) { 5036 if (!S.getLangOpts().CPlusPlus14) { 5037 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 5038 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto 5039 ? diag::err_auto_missing_trailing_return 5040 : diag::err_deduced_return_type); 5041 T = Context.IntTy; 5042 D.setInvalidType(true); 5043 } else { 5044 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 5045 diag::warn_cxx11_compat_deduced_return_type); 5046 } 5047 } else if (FTI.hasTrailingReturnType()) { 5048 // T must be exactly 'auto' at this point. See CWG issue 681. 5049 if (isa<ParenType>(T)) { 5050 S.Diag(D.getBeginLoc(), diag::err_trailing_return_in_parens) 5051 << T << D.getSourceRange(); 5052 D.setInvalidType(true); 5053 } else if (D.getName().getKind() == 5054 UnqualifiedIdKind::IK_DeductionGuideName) { 5055 if (T != Context.DependentTy) { 5056 S.Diag(D.getDeclSpec().getBeginLoc(), 5057 diag::err_deduction_guide_with_complex_decl) 5058 << D.getSourceRange(); 5059 D.setInvalidType(true); 5060 } 5061 } else if (D.getContext() != DeclaratorContext::LambdaExpr && 5062 (T.hasQualifiers() || !isa<AutoType>(T) || 5063 cast<AutoType>(T)->getKeyword() != 5064 AutoTypeKeyword::Auto || 5065 cast<AutoType>(T)->isConstrained())) { 5066 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 5067 diag::err_trailing_return_without_auto) 5068 << T << D.getDeclSpec().getSourceRange(); 5069 D.setInvalidType(true); 5070 } 5071 T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo); 5072 if (T.isNull()) { 5073 // An error occurred parsing the trailing return type. 5074 T = Context.IntTy; 5075 D.setInvalidType(true); 5076 } else if (AutoType *Auto = T->getContainedAutoType()) { 5077 // If the trailing return type contains an `auto`, we may need to 5078 // invent a template parameter for it, for cases like 5079 // `auto f() -> C auto` or `[](auto (*p) -> auto) {}`. 5080 InventedTemplateParameterInfo *InventedParamInfo = nullptr; 5081 if (D.getContext() == DeclaratorContext::Prototype) 5082 InventedParamInfo = &S.InventedParameterInfos.back(); 5083 else if (D.getContext() == DeclaratorContext::LambdaExprParameter) 5084 InventedParamInfo = S.getCurLambda(); 5085 if (InventedParamInfo) { 5086 std::tie(T, TInfo) = InventTemplateParameter( 5087 state, T, TInfo, Auto, *InventedParamInfo); 5088 } 5089 } 5090 } else { 5091 // This function type is not the type of the entity being declared, 5092 // so checking the 'auto' is not the responsibility of this chunk. 5093 } 5094 } 5095 5096 // C99 6.7.5.3p1: The return type may not be a function or array type. 5097 // For conversion functions, we'll diagnose this particular error later. 5098 if (!D.isInvalidType() && (T->isArrayType() || T->isFunctionType()) && 5099 (D.getName().getKind() != 5100 UnqualifiedIdKind::IK_ConversionFunctionId)) { 5101 unsigned diagID = diag::err_func_returning_array_function; 5102 // Last processing chunk in block context means this function chunk 5103 // represents the block. 5104 if (chunkIndex == 0 && 5105 D.getContext() == DeclaratorContext::BlockLiteral) 5106 diagID = diag::err_block_returning_array_function; 5107 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T; 5108 T = Context.IntTy; 5109 D.setInvalidType(true); 5110 } 5111 5112 // Do not allow returning half FP value. 5113 // FIXME: This really should be in BuildFunctionType. 5114 if (T->isHalfType()) { 5115 if (S.getLangOpts().OpenCL) { 5116 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", 5117 S.getLangOpts())) { 5118 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return) 5119 << T << 0 /*pointer hint*/; 5120 D.setInvalidType(true); 5121 } 5122 } else if (!S.getLangOpts().HalfArgsAndReturns) { 5123 S.Diag(D.getIdentifierLoc(), 5124 diag::err_parameters_retval_cannot_have_fp16_type) << 1; 5125 D.setInvalidType(true); 5126 } 5127 } 5128 5129 if (LangOpts.OpenCL) { 5130 // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a 5131 // function. 5132 if (T->isBlockPointerType() || T->isImageType() || T->isSamplerT() || 5133 T->isPipeType()) { 5134 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return) 5135 << T << 1 /*hint off*/; 5136 D.setInvalidType(true); 5137 } 5138 // OpenCL doesn't support variadic functions and blocks 5139 // (s6.9.e and s6.12.5 OpenCL v2.0) except for printf. 5140 // We also allow here any toolchain reserved identifiers. 5141 if (FTI.isVariadic && 5142 !S.getOpenCLOptions().isAvailableOption( 5143 "__cl_clang_variadic_functions", S.getLangOpts()) && 5144 !(D.getIdentifier() && 5145 ((D.getIdentifier()->getName() == "printf" && 5146 LangOpts.getOpenCLCompatibleVersion() >= 120) || 5147 D.getIdentifier()->getName().startswith("__")))) { 5148 S.Diag(D.getIdentifierLoc(), diag::err_opencl_variadic_function); 5149 D.setInvalidType(true); 5150 } 5151 } 5152 5153 // Methods cannot return interface types. All ObjC objects are 5154 // passed by reference. 5155 if (T->isObjCObjectType()) { 5156 SourceLocation DiagLoc, FixitLoc; 5157 if (TInfo) { 5158 DiagLoc = TInfo->getTypeLoc().getBeginLoc(); 5159 FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getEndLoc()); 5160 } else { 5161 DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc(); 5162 FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getEndLoc()); 5163 } 5164 S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value) 5165 << 0 << T 5166 << FixItHint::CreateInsertion(FixitLoc, "*"); 5167 5168 T = Context.getObjCObjectPointerType(T); 5169 if (TInfo) { 5170 TypeLocBuilder TLB; 5171 TLB.pushFullCopy(TInfo->getTypeLoc()); 5172 ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T); 5173 TLoc.setStarLoc(FixitLoc); 5174 TInfo = TLB.getTypeSourceInfo(Context, T); 5175 } 5176 5177 D.setInvalidType(true); 5178 } 5179 5180 // cv-qualifiers on return types are pointless except when the type is a 5181 // class type in C++. 5182 if ((T.getCVRQualifiers() || T->isAtomicType()) && 5183 !(S.getLangOpts().CPlusPlus && 5184 (T->isDependentType() || T->isRecordType()))) { 5185 if (T->isVoidType() && !S.getLangOpts().CPlusPlus && 5186 D.getFunctionDefinitionKind() == 5187 FunctionDefinitionKind::Definition) { 5188 // [6.9.1/3] qualified void return is invalid on a C 5189 // function definition. Apparently ok on declarations and 5190 // in C++ though (!) 5191 S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T; 5192 } else 5193 diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex); 5194 5195 // C++2a [dcl.fct]p12: 5196 // A volatile-qualified return type is deprecated 5197 if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20) 5198 S.Diag(DeclType.Loc, diag::warn_deprecated_volatile_return) << T; 5199 } 5200 5201 // Objective-C ARC ownership qualifiers are ignored on the function 5202 // return type (by type canonicalization). Complain if this attribute 5203 // was written here. 5204 if (T.getQualifiers().hasObjCLifetime()) { 5205 SourceLocation AttrLoc; 5206 if (chunkIndex + 1 < D.getNumTypeObjects()) { 5207 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1); 5208 for (const ParsedAttr &AL : ReturnTypeChunk.getAttrs()) { 5209 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) { 5210 AttrLoc = AL.getLoc(); 5211 break; 5212 } 5213 } 5214 } 5215 if (AttrLoc.isInvalid()) { 5216 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) { 5217 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) { 5218 AttrLoc = AL.getLoc(); 5219 break; 5220 } 5221 } 5222 } 5223 5224 if (AttrLoc.isValid()) { 5225 // The ownership attributes are almost always written via 5226 // the predefined 5227 // __strong/__weak/__autoreleasing/__unsafe_unretained. 5228 if (AttrLoc.isMacroID()) 5229 AttrLoc = 5230 S.SourceMgr.getImmediateExpansionRange(AttrLoc).getBegin(); 5231 5232 S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type) 5233 << T.getQualifiers().getObjCLifetime(); 5234 } 5235 } 5236 5237 if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) { 5238 // C++ [dcl.fct]p6: 5239 // Types shall not be defined in return or parameter types. 5240 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 5241 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type) 5242 << Context.getTypeDeclType(Tag); 5243 } 5244 5245 // Exception specs are not allowed in typedefs. Complain, but add it 5246 // anyway. 5247 if (IsTypedefName && FTI.getExceptionSpecType() && !LangOpts.CPlusPlus17) 5248 S.Diag(FTI.getExceptionSpecLocBeg(), 5249 diag::err_exception_spec_in_typedef) 5250 << (D.getContext() == DeclaratorContext::AliasDecl || 5251 D.getContext() == DeclaratorContext::AliasTemplate); 5252 5253 // If we see "T var();" or "T var(T());" at block scope, it is probably 5254 // an attempt to initialize a variable, not a function declaration. 5255 if (FTI.isAmbiguous) 5256 warnAboutAmbiguousFunction(S, D, DeclType, T); 5257 5258 FunctionType::ExtInfo EI( 5259 getCCForDeclaratorChunk(S, D, DeclType.getAttrs(), FTI, chunkIndex)); 5260 5261 // OpenCL disallows functions without a prototype, but it doesn't enforce 5262 // strict prototypes as in C2x because it allows a function definition to 5263 // have an identifier list. See OpenCL 3.0 6.11/g for more details. 5264 if (!FTI.NumParams && !FTI.isVariadic && 5265 !LangOpts.requiresStrictPrototypes() && !LangOpts.OpenCL) { 5266 // Simple void foo(), where the incoming T is the result type. 5267 T = Context.getFunctionNoProtoType(T, EI); 5268 } else { 5269 // We allow a zero-parameter variadic function in C if the 5270 // function is marked with the "overloadable" attribute. Scan 5271 // for this attribute now. 5272 if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) 5273 if (!D.getAttributes().hasAttribute(ParsedAttr::AT_Overloadable) && 5274 !D.getDeclSpec().getAttributes().hasAttribute( 5275 ParsedAttr::AT_Overloadable)) 5276 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param); 5277 5278 if (FTI.NumParams && FTI.Params[0].Param == nullptr) { 5279 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function 5280 // definition. 5281 S.Diag(FTI.Params[0].IdentLoc, 5282 diag::err_ident_list_in_fn_declaration); 5283 D.setInvalidType(true); 5284 // Recover by creating a K&R-style function type, if possible. 5285 T = (!LangOpts.requiresStrictPrototypes() && !LangOpts.OpenCL) 5286 ? Context.getFunctionNoProtoType(T, EI) 5287 : Context.IntTy; 5288 break; 5289 } 5290 5291 FunctionProtoType::ExtProtoInfo EPI; 5292 EPI.ExtInfo = EI; 5293 EPI.Variadic = FTI.isVariadic; 5294 EPI.EllipsisLoc = FTI.getEllipsisLoc(); 5295 EPI.HasTrailingReturn = FTI.hasTrailingReturnType(); 5296 EPI.TypeQuals.addCVRUQualifiers( 5297 FTI.MethodQualifiers ? FTI.MethodQualifiers->getTypeQualifiers() 5298 : 0); 5299 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None 5300 : FTI.RefQualifierIsLValueRef? RQ_LValue 5301 : RQ_RValue; 5302 5303 // Otherwise, we have a function with a parameter list that is 5304 // potentially variadic. 5305 SmallVector<QualType, 16> ParamTys; 5306 ParamTys.reserve(FTI.NumParams); 5307 5308 SmallVector<FunctionProtoType::ExtParameterInfo, 16> 5309 ExtParameterInfos(FTI.NumParams); 5310 bool HasAnyInterestingExtParameterInfos = false; 5311 5312 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 5313 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 5314 QualType ParamTy = Param->getType(); 5315 assert(!ParamTy.isNull() && "Couldn't parse type?"); 5316 5317 // Look for 'void'. void is allowed only as a single parameter to a 5318 // function with no other parameters (C99 6.7.5.3p10). We record 5319 // int(void) as a FunctionProtoType with an empty parameter list. 5320 if (ParamTy->isVoidType()) { 5321 // If this is something like 'float(int, void)', reject it. 'void' 5322 // is an incomplete type (C99 6.2.5p19) and function decls cannot 5323 // have parameters of incomplete type. 5324 if (FTI.NumParams != 1 || FTI.isVariadic) { 5325 S.Diag(FTI.Params[i].IdentLoc, diag::err_void_only_param); 5326 ParamTy = Context.IntTy; 5327 Param->setType(ParamTy); 5328 } else if (FTI.Params[i].Ident) { 5329 // Reject, but continue to parse 'int(void abc)'. 5330 S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type); 5331 ParamTy = Context.IntTy; 5332 Param->setType(ParamTy); 5333 } else { 5334 // Reject, but continue to parse 'float(const void)'. 5335 if (ParamTy.hasQualifiers()) 5336 S.Diag(DeclType.Loc, diag::err_void_param_qualified); 5337 5338 // Do not add 'void' to the list. 5339 break; 5340 } 5341 } else if (ParamTy->isHalfType()) { 5342 // Disallow half FP parameters. 5343 // FIXME: This really should be in BuildFunctionType. 5344 if (S.getLangOpts().OpenCL) { 5345 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", 5346 S.getLangOpts())) { 5347 S.Diag(Param->getLocation(), diag::err_opencl_invalid_param) 5348 << ParamTy << 0; 5349 D.setInvalidType(); 5350 Param->setInvalidDecl(); 5351 } 5352 } else if (!S.getLangOpts().HalfArgsAndReturns) { 5353 S.Diag(Param->getLocation(), 5354 diag::err_parameters_retval_cannot_have_fp16_type) << 0; 5355 D.setInvalidType(); 5356 } 5357 } else if (!FTI.hasPrototype) { 5358 if (ParamTy->isPromotableIntegerType()) { 5359 ParamTy = Context.getPromotedIntegerType(ParamTy); 5360 Param->setKNRPromoted(true); 5361 } else if (const BuiltinType* BTy = ParamTy->getAs<BuiltinType>()) { 5362 if (BTy->getKind() == BuiltinType::Float) { 5363 ParamTy = Context.DoubleTy; 5364 Param->setKNRPromoted(true); 5365 } 5366 } 5367 } else if (S.getLangOpts().OpenCL && ParamTy->isBlockPointerType()) { 5368 // OpenCL 2.0 s6.12.5: A block cannot be a parameter of a function. 5369 S.Diag(Param->getLocation(), diag::err_opencl_invalid_param) 5370 << ParamTy << 1 /*hint off*/; 5371 D.setInvalidType(); 5372 } 5373 5374 if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) { 5375 ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(true); 5376 HasAnyInterestingExtParameterInfos = true; 5377 } 5378 5379 if (auto attr = Param->getAttr<ParameterABIAttr>()) { 5380 ExtParameterInfos[i] = 5381 ExtParameterInfos[i].withABI(attr->getABI()); 5382 HasAnyInterestingExtParameterInfos = true; 5383 } 5384 5385 if (Param->hasAttr<PassObjectSizeAttr>()) { 5386 ExtParameterInfos[i] = ExtParameterInfos[i].withHasPassObjectSize(); 5387 HasAnyInterestingExtParameterInfos = true; 5388 } 5389 5390 if (Param->hasAttr<NoEscapeAttr>()) { 5391 ExtParameterInfos[i] = ExtParameterInfos[i].withIsNoEscape(true); 5392 HasAnyInterestingExtParameterInfos = true; 5393 } 5394 5395 ParamTys.push_back(ParamTy); 5396 } 5397 5398 if (HasAnyInterestingExtParameterInfos) { 5399 EPI.ExtParameterInfos = ExtParameterInfos.data(); 5400 checkExtParameterInfos(S, ParamTys, EPI, 5401 [&](unsigned i) { return FTI.Params[i].Param->getLocation(); }); 5402 } 5403 5404 SmallVector<QualType, 4> Exceptions; 5405 SmallVector<ParsedType, 2> DynamicExceptions; 5406 SmallVector<SourceRange, 2> DynamicExceptionRanges; 5407 Expr *NoexceptExpr = nullptr; 5408 5409 if (FTI.getExceptionSpecType() == EST_Dynamic) { 5410 // FIXME: It's rather inefficient to have to split into two vectors 5411 // here. 5412 unsigned N = FTI.getNumExceptions(); 5413 DynamicExceptions.reserve(N); 5414 DynamicExceptionRanges.reserve(N); 5415 for (unsigned I = 0; I != N; ++I) { 5416 DynamicExceptions.push_back(FTI.Exceptions[I].Ty); 5417 DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range); 5418 } 5419 } else if (isComputedNoexcept(FTI.getExceptionSpecType())) { 5420 NoexceptExpr = FTI.NoexceptExpr; 5421 } 5422 5423 S.checkExceptionSpecification(D.isFunctionDeclarationContext(), 5424 FTI.getExceptionSpecType(), 5425 DynamicExceptions, 5426 DynamicExceptionRanges, 5427 NoexceptExpr, 5428 Exceptions, 5429 EPI.ExceptionSpec); 5430 5431 // FIXME: Set address space from attrs for C++ mode here. 5432 // OpenCLCPlusPlus: A class member function has an address space. 5433 auto IsClassMember = [&]() { 5434 return (!state.getDeclarator().getCXXScopeSpec().isEmpty() && 5435 state.getDeclarator() 5436 .getCXXScopeSpec() 5437 .getScopeRep() 5438 ->getKind() == NestedNameSpecifier::TypeSpec) || 5439 state.getDeclarator().getContext() == 5440 DeclaratorContext::Member || 5441 state.getDeclarator().getContext() == 5442 DeclaratorContext::LambdaExpr; 5443 }; 5444 5445 if (state.getSema().getLangOpts().OpenCLCPlusPlus && IsClassMember()) { 5446 LangAS ASIdx = LangAS::Default; 5447 // Take address space attr if any and mark as invalid to avoid adding 5448 // them later while creating QualType. 5449 if (FTI.MethodQualifiers) 5450 for (ParsedAttr &attr : FTI.MethodQualifiers->getAttributes()) { 5451 LangAS ASIdxNew = attr.asOpenCLLangAS(); 5452 if (DiagnoseMultipleAddrSpaceAttributes(S, ASIdx, ASIdxNew, 5453 attr.getLoc())) 5454 D.setInvalidType(true); 5455 else 5456 ASIdx = ASIdxNew; 5457 } 5458 // If a class member function's address space is not set, set it to 5459 // __generic. 5460 LangAS AS = 5461 (ASIdx == LangAS::Default ? S.getDefaultCXXMethodAddrSpace() 5462 : ASIdx); 5463 EPI.TypeQuals.addAddressSpace(AS); 5464 } 5465 T = Context.getFunctionType(T, ParamTys, EPI); 5466 } 5467 break; 5468 } 5469 case DeclaratorChunk::MemberPointer: { 5470 // The scope spec must refer to a class, or be dependent. 5471 CXXScopeSpec &SS = DeclType.Mem.Scope(); 5472 QualType ClsType; 5473 5474 // Handle pointer nullability. 5475 inferPointerNullability(SimplePointerKind::MemberPointer, DeclType.Loc, 5476 DeclType.EndLoc, DeclType.getAttrs(), 5477 state.getDeclarator().getAttributePool()); 5478 5479 if (SS.isInvalid()) { 5480 // Avoid emitting extra errors if we already errored on the scope. 5481 D.setInvalidType(true); 5482 } else if (S.isDependentScopeSpecifier(SS) || 5483 isa_and_nonnull<CXXRecordDecl>(S.computeDeclContext(SS))) { 5484 NestedNameSpecifier *NNS = SS.getScopeRep(); 5485 NestedNameSpecifier *NNSPrefix = NNS->getPrefix(); 5486 switch (NNS->getKind()) { 5487 case NestedNameSpecifier::Identifier: 5488 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix, 5489 NNS->getAsIdentifier()); 5490 break; 5491 5492 case NestedNameSpecifier::Namespace: 5493 case NestedNameSpecifier::NamespaceAlias: 5494 case NestedNameSpecifier::Global: 5495 case NestedNameSpecifier::Super: 5496 llvm_unreachable("Nested-name-specifier must name a type"); 5497 5498 case NestedNameSpecifier::TypeSpec: 5499 case NestedNameSpecifier::TypeSpecWithTemplate: 5500 ClsType = QualType(NNS->getAsType(), 0); 5501 // Note: if the NNS has a prefix and ClsType is a nondependent 5502 // TemplateSpecializationType, then the NNS prefix is NOT included 5503 // in ClsType; hence we wrap ClsType into an ElaboratedType. 5504 // NOTE: in particular, no wrap occurs if ClsType already is an 5505 // Elaborated, DependentName, or DependentTemplateSpecialization. 5506 if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType())) 5507 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType); 5508 break; 5509 } 5510 } else { 5511 S.Diag(DeclType.Mem.Scope().getBeginLoc(), 5512 diag::err_illegal_decl_mempointer_in_nonclass) 5513 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name") 5514 << DeclType.Mem.Scope().getRange(); 5515 D.setInvalidType(true); 5516 } 5517 5518 if (!ClsType.isNull()) 5519 T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc, 5520 D.getIdentifier()); 5521 if (T.isNull()) { 5522 T = Context.IntTy; 5523 D.setInvalidType(true); 5524 } else if (DeclType.Mem.TypeQuals) { 5525 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals); 5526 } 5527 break; 5528 } 5529 5530 case DeclaratorChunk::Pipe: { 5531 T = S.BuildReadPipeType(T, DeclType.Loc); 5532 processTypeAttrs(state, T, TAL_DeclSpec, 5533 D.getMutableDeclSpec().getAttributes()); 5534 break; 5535 } 5536 } 5537 5538 if (T.isNull()) { 5539 D.setInvalidType(true); 5540 T = Context.IntTy; 5541 } 5542 5543 // See if there are any attributes on this declarator chunk. 5544 processTypeAttrs(state, T, TAL_DeclChunk, DeclType.getAttrs()); 5545 5546 if (DeclType.Kind != DeclaratorChunk::Paren) { 5547 if (ExpectNoDerefChunk && !IsNoDerefableChunk(DeclType)) 5548 S.Diag(DeclType.Loc, diag::warn_noderef_on_non_pointer_or_array); 5549 5550 ExpectNoDerefChunk = state.didParseNoDeref(); 5551 } 5552 } 5553 5554 if (ExpectNoDerefChunk) 5555 S.Diag(state.getDeclarator().getBeginLoc(), 5556 diag::warn_noderef_on_non_pointer_or_array); 5557 5558 // GNU warning -Wstrict-prototypes 5559 // Warn if a function declaration or definition is without a prototype. 5560 // This warning is issued for all kinds of unprototyped function 5561 // declarations (i.e. function type typedef, function pointer etc.) 5562 // C99 6.7.5.3p14: 5563 // The empty list in a function declarator that is not part of a definition 5564 // of that function specifies that no information about the number or types 5565 // of the parameters is supplied. 5566 // See ActOnFinishFunctionBody() and MergeFunctionDecl() for handling of 5567 // function declarations whose behavior changes in C2x. 5568 if (!LangOpts.requiresStrictPrototypes()) { 5569 bool IsBlock = false; 5570 for (const DeclaratorChunk &DeclType : D.type_objects()) { 5571 switch (DeclType.Kind) { 5572 case DeclaratorChunk::BlockPointer: 5573 IsBlock = true; 5574 break; 5575 case DeclaratorChunk::Function: { 5576 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 5577 // We suppress the warning when there's no LParen location, as this 5578 // indicates the declaration was an implicit declaration, which gets 5579 // warned about separately via -Wimplicit-function-declaration. We also 5580 // suppress the warning when we know the function has a prototype. 5581 if (!FTI.hasPrototype && FTI.NumParams == 0 && !FTI.isVariadic && 5582 FTI.getLParenLoc().isValid()) 5583 S.Diag(DeclType.Loc, diag::warn_strict_prototypes) 5584 << IsBlock 5585 << FixItHint::CreateInsertion(FTI.getRParenLoc(), "void"); 5586 IsBlock = false; 5587 break; 5588 } 5589 default: 5590 break; 5591 } 5592 } 5593 } 5594 5595 assert(!T.isNull() && "T must not be null after this point"); 5596 5597 if (LangOpts.CPlusPlus && T->isFunctionType()) { 5598 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>(); 5599 assert(FnTy && "Why oh why is there not a FunctionProtoType here?"); 5600 5601 // C++ 8.3.5p4: 5602 // A cv-qualifier-seq shall only be part of the function type 5603 // for a nonstatic member function, the function type to which a pointer 5604 // to member refers, or the top-level function type of a function typedef 5605 // declaration. 5606 // 5607 // Core issue 547 also allows cv-qualifiers on function types that are 5608 // top-level template type arguments. 5609 enum { NonMember, Member, DeductionGuide } Kind = NonMember; 5610 if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName) 5611 Kind = DeductionGuide; 5612 else if (!D.getCXXScopeSpec().isSet()) { 5613 if ((D.getContext() == DeclaratorContext::Member || 5614 D.getContext() == DeclaratorContext::LambdaExpr) && 5615 !D.getDeclSpec().isFriendSpecified()) 5616 Kind = Member; 5617 } else { 5618 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec()); 5619 if (!DC || DC->isRecord()) 5620 Kind = Member; 5621 } 5622 5623 // C++11 [dcl.fct]p6 (w/DR1417): 5624 // An attempt to specify a function type with a cv-qualifier-seq or a 5625 // ref-qualifier (including by typedef-name) is ill-formed unless it is: 5626 // - the function type for a non-static member function, 5627 // - the function type to which a pointer to member refers, 5628 // - the top-level function type of a function typedef declaration or 5629 // alias-declaration, 5630 // - the type-id in the default argument of a type-parameter, or 5631 // - the type-id of a template-argument for a type-parameter 5632 // 5633 // FIXME: Checking this here is insufficient. We accept-invalid on: 5634 // 5635 // template<typename T> struct S { void f(T); }; 5636 // S<int() const> s; 5637 // 5638 // ... for instance. 5639 if (IsQualifiedFunction && 5640 !(Kind == Member && 5641 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) && 5642 !IsTypedefName && D.getContext() != DeclaratorContext::TemplateArg && 5643 D.getContext() != DeclaratorContext::TemplateTypeArg) { 5644 SourceLocation Loc = D.getBeginLoc(); 5645 SourceRange RemovalRange; 5646 unsigned I; 5647 if (D.isFunctionDeclarator(I)) { 5648 SmallVector<SourceLocation, 4> RemovalLocs; 5649 const DeclaratorChunk &Chunk = D.getTypeObject(I); 5650 assert(Chunk.Kind == DeclaratorChunk::Function); 5651 5652 if (Chunk.Fun.hasRefQualifier()) 5653 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc()); 5654 5655 if (Chunk.Fun.hasMethodTypeQualifiers()) 5656 Chunk.Fun.MethodQualifiers->forEachQualifier( 5657 [&](DeclSpec::TQ TypeQual, StringRef QualName, 5658 SourceLocation SL) { RemovalLocs.push_back(SL); }); 5659 5660 if (!RemovalLocs.empty()) { 5661 llvm::sort(RemovalLocs, 5662 BeforeThanCompare<SourceLocation>(S.getSourceManager())); 5663 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back()); 5664 Loc = RemovalLocs.front(); 5665 } 5666 } 5667 5668 S.Diag(Loc, diag::err_invalid_qualified_function_type) 5669 << Kind << D.isFunctionDeclarator() << T 5670 << getFunctionQualifiersAsString(FnTy) 5671 << FixItHint::CreateRemoval(RemovalRange); 5672 5673 // Strip the cv-qualifiers and ref-qualifiers from the type. 5674 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo(); 5675 EPI.TypeQuals.removeCVRQualifiers(); 5676 EPI.RefQualifier = RQ_None; 5677 5678 T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(), 5679 EPI); 5680 // Rebuild any parens around the identifier in the function type. 5681 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 5682 if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren) 5683 break; 5684 T = S.BuildParenType(T); 5685 } 5686 } 5687 } 5688 5689 // Apply any undistributed attributes from the declarator. 5690 processTypeAttrs(state, T, TAL_DeclName, D.getAttributes()); 5691 5692 // Diagnose any ignored type attributes. 5693 state.diagnoseIgnoredTypeAttrs(T); 5694 5695 // C++0x [dcl.constexpr]p9: 5696 // A constexpr specifier used in an object declaration declares the object 5697 // as const. 5698 if (D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Constexpr && 5699 T->isObjectType()) 5700 T.addConst(); 5701 5702 // C++2a [dcl.fct]p4: 5703 // A parameter with volatile-qualified type is deprecated 5704 if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20 && 5705 (D.getContext() == DeclaratorContext::Prototype || 5706 D.getContext() == DeclaratorContext::LambdaExprParameter)) 5707 S.Diag(D.getIdentifierLoc(), diag::warn_deprecated_volatile_param) << T; 5708 5709 // If there was an ellipsis in the declarator, the declaration declares a 5710 // parameter pack whose type may be a pack expansion type. 5711 if (D.hasEllipsis()) { 5712 // C++0x [dcl.fct]p13: 5713 // A declarator-id or abstract-declarator containing an ellipsis shall 5714 // only be used in a parameter-declaration. Such a parameter-declaration 5715 // is a parameter pack (14.5.3). [...] 5716 switch (D.getContext()) { 5717 case DeclaratorContext::Prototype: 5718 case DeclaratorContext::LambdaExprParameter: 5719 case DeclaratorContext::RequiresExpr: 5720 // C++0x [dcl.fct]p13: 5721 // [...] When it is part of a parameter-declaration-clause, the 5722 // parameter pack is a function parameter pack (14.5.3). The type T 5723 // of the declarator-id of the function parameter pack shall contain 5724 // a template parameter pack; each template parameter pack in T is 5725 // expanded by the function parameter pack. 5726 // 5727 // We represent function parameter packs as function parameters whose 5728 // type is a pack expansion. 5729 if (!T->containsUnexpandedParameterPack() && 5730 (!LangOpts.CPlusPlus20 || !T->getContainedAutoType())) { 5731 S.Diag(D.getEllipsisLoc(), 5732 diag::err_function_parameter_pack_without_parameter_packs) 5733 << T << D.getSourceRange(); 5734 D.setEllipsisLoc(SourceLocation()); 5735 } else { 5736 T = Context.getPackExpansionType(T, None, /*ExpectPackInType=*/false); 5737 } 5738 break; 5739 case DeclaratorContext::TemplateParam: 5740 // C++0x [temp.param]p15: 5741 // If a template-parameter is a [...] is a parameter-declaration that 5742 // declares a parameter pack (8.3.5), then the template-parameter is a 5743 // template parameter pack (14.5.3). 5744 // 5745 // Note: core issue 778 clarifies that, if there are any unexpanded 5746 // parameter packs in the type of the non-type template parameter, then 5747 // it expands those parameter packs. 5748 if (T->containsUnexpandedParameterPack()) 5749 T = Context.getPackExpansionType(T, None); 5750 else 5751 S.Diag(D.getEllipsisLoc(), 5752 LangOpts.CPlusPlus11 5753 ? diag::warn_cxx98_compat_variadic_templates 5754 : diag::ext_variadic_templates); 5755 break; 5756 5757 case DeclaratorContext::File: 5758 case DeclaratorContext::KNRTypeList: 5759 case DeclaratorContext::ObjCParameter: // FIXME: special diagnostic here? 5760 case DeclaratorContext::ObjCResult: // FIXME: special diagnostic here? 5761 case DeclaratorContext::TypeName: 5762 case DeclaratorContext::FunctionalCast: 5763 case DeclaratorContext::CXXNew: 5764 case DeclaratorContext::AliasDecl: 5765 case DeclaratorContext::AliasTemplate: 5766 case DeclaratorContext::Member: 5767 case DeclaratorContext::Block: 5768 case DeclaratorContext::ForInit: 5769 case DeclaratorContext::SelectionInit: 5770 case DeclaratorContext::Condition: 5771 case DeclaratorContext::CXXCatch: 5772 case DeclaratorContext::ObjCCatch: 5773 case DeclaratorContext::BlockLiteral: 5774 case DeclaratorContext::LambdaExpr: 5775 case DeclaratorContext::ConversionId: 5776 case DeclaratorContext::TrailingReturn: 5777 case DeclaratorContext::TrailingReturnVar: 5778 case DeclaratorContext::TemplateArg: 5779 case DeclaratorContext::TemplateTypeArg: 5780 // FIXME: We may want to allow parameter packs in block-literal contexts 5781 // in the future. 5782 S.Diag(D.getEllipsisLoc(), 5783 diag::err_ellipsis_in_declarator_not_parameter); 5784 D.setEllipsisLoc(SourceLocation()); 5785 break; 5786 } 5787 } 5788 5789 assert(!T.isNull() && "T must not be null at the end of this function"); 5790 if (D.isInvalidType()) 5791 return Context.getTrivialTypeSourceInfo(T); 5792 5793 return GetTypeSourceInfoForDeclarator(state, T, TInfo); 5794 } 5795 5796 /// GetTypeForDeclarator - Convert the type for the specified 5797 /// declarator to Type instances. 5798 /// 5799 /// The result of this call will never be null, but the associated 5800 /// type may be a null type if there's an unrecoverable error. 5801 TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) { 5802 // Determine the type of the declarator. Not all forms of declarator 5803 // have a type. 5804 5805 TypeProcessingState state(*this, D); 5806 5807 TypeSourceInfo *ReturnTypeInfo = nullptr; 5808 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); 5809 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount) 5810 inferARCWriteback(state, T); 5811 5812 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo); 5813 } 5814 5815 static void transferARCOwnershipToDeclSpec(Sema &S, 5816 QualType &declSpecTy, 5817 Qualifiers::ObjCLifetime ownership) { 5818 if (declSpecTy->isObjCRetainableType() && 5819 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) { 5820 Qualifiers qs; 5821 qs.addObjCLifetime(ownership); 5822 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs); 5823 } 5824 } 5825 5826 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, 5827 Qualifiers::ObjCLifetime ownership, 5828 unsigned chunkIndex) { 5829 Sema &S = state.getSema(); 5830 Declarator &D = state.getDeclarator(); 5831 5832 // Look for an explicit lifetime attribute. 5833 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex); 5834 if (chunk.getAttrs().hasAttribute(ParsedAttr::AT_ObjCOwnership)) 5835 return; 5836 5837 const char *attrStr = nullptr; 5838 switch (ownership) { 5839 case Qualifiers::OCL_None: llvm_unreachable("no ownership!"); 5840 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break; 5841 case Qualifiers::OCL_Strong: attrStr = "strong"; break; 5842 case Qualifiers::OCL_Weak: attrStr = "weak"; break; 5843 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break; 5844 } 5845 5846 IdentifierLoc *Arg = new (S.Context) IdentifierLoc; 5847 Arg->Ident = &S.Context.Idents.get(attrStr); 5848 Arg->Loc = SourceLocation(); 5849 5850 ArgsUnion Args(Arg); 5851 5852 // If there wasn't one, add one (with an invalid source location 5853 // so that we don't make an AttributedType for it). 5854 ParsedAttr *attr = D.getAttributePool().create( 5855 &S.Context.Idents.get("objc_ownership"), SourceLocation(), 5856 /*scope*/ nullptr, SourceLocation(), 5857 /*args*/ &Args, 1, ParsedAttr::AS_GNU); 5858 chunk.getAttrs().addAtEnd(attr); 5859 // TODO: mark whether we did this inference? 5860 } 5861 5862 /// Used for transferring ownership in casts resulting in l-values. 5863 static void transferARCOwnership(TypeProcessingState &state, 5864 QualType &declSpecTy, 5865 Qualifiers::ObjCLifetime ownership) { 5866 Sema &S = state.getSema(); 5867 Declarator &D = state.getDeclarator(); 5868 5869 int inner = -1; 5870 bool hasIndirection = false; 5871 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 5872 DeclaratorChunk &chunk = D.getTypeObject(i); 5873 switch (chunk.Kind) { 5874 case DeclaratorChunk::Paren: 5875 // Ignore parens. 5876 break; 5877 5878 case DeclaratorChunk::Array: 5879 case DeclaratorChunk::Reference: 5880 case DeclaratorChunk::Pointer: 5881 if (inner != -1) 5882 hasIndirection = true; 5883 inner = i; 5884 break; 5885 5886 case DeclaratorChunk::BlockPointer: 5887 if (inner != -1) 5888 transferARCOwnershipToDeclaratorChunk(state, ownership, i); 5889 return; 5890 5891 case DeclaratorChunk::Function: 5892 case DeclaratorChunk::MemberPointer: 5893 case DeclaratorChunk::Pipe: 5894 return; 5895 } 5896 } 5897 5898 if (inner == -1) 5899 return; 5900 5901 DeclaratorChunk &chunk = D.getTypeObject(inner); 5902 if (chunk.Kind == DeclaratorChunk::Pointer) { 5903 if (declSpecTy->isObjCRetainableType()) 5904 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); 5905 if (declSpecTy->isObjCObjectType() && hasIndirection) 5906 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner); 5907 } else { 5908 assert(chunk.Kind == DeclaratorChunk::Array || 5909 chunk.Kind == DeclaratorChunk::Reference); 5910 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); 5911 } 5912 } 5913 5914 TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) { 5915 TypeProcessingState state(*this, D); 5916 5917 TypeSourceInfo *ReturnTypeInfo = nullptr; 5918 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); 5919 5920 if (getLangOpts().ObjC) { 5921 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy); 5922 if (ownership != Qualifiers::OCL_None) 5923 transferARCOwnership(state, declSpecTy, ownership); 5924 } 5925 5926 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo); 5927 } 5928 5929 static void fillAttributedTypeLoc(AttributedTypeLoc TL, 5930 TypeProcessingState &State) { 5931 TL.setAttr(State.takeAttrForAttributedType(TL.getTypePtr())); 5932 } 5933 5934 namespace { 5935 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> { 5936 Sema &SemaRef; 5937 ASTContext &Context; 5938 TypeProcessingState &State; 5939 const DeclSpec &DS; 5940 5941 public: 5942 TypeSpecLocFiller(Sema &S, ASTContext &Context, TypeProcessingState &State, 5943 const DeclSpec &DS) 5944 : SemaRef(S), Context(Context), State(State), DS(DS) {} 5945 5946 void VisitAttributedTypeLoc(AttributedTypeLoc TL) { 5947 Visit(TL.getModifiedLoc()); 5948 fillAttributedTypeLoc(TL, State); 5949 } 5950 void VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) { 5951 Visit(TL.getWrappedLoc()); 5952 } 5953 void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) { 5954 Visit(TL.getInnerLoc()); 5955 TL.setExpansionLoc( 5956 State.getExpansionLocForMacroQualifiedType(TL.getTypePtr())); 5957 } 5958 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 5959 Visit(TL.getUnqualifiedLoc()); 5960 } 5961 // Allow to fill pointee's type locations, e.g., 5962 // int __attr * __attr * __attr *p; 5963 void VisitPointerTypeLoc(PointerTypeLoc TL) { Visit(TL.getNextTypeLoc()); } 5964 void VisitTypedefTypeLoc(TypedefTypeLoc TL) { 5965 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 5966 } 5967 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { 5968 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 5969 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires 5970 // addition field. What we have is good enough for display of location 5971 // of 'fixit' on interface name. 5972 TL.setNameEndLoc(DS.getEndLoc()); 5973 } 5974 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { 5975 TypeSourceInfo *RepTInfo = nullptr; 5976 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo); 5977 TL.copy(RepTInfo->getTypeLoc()); 5978 } 5979 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 5980 TypeSourceInfo *RepTInfo = nullptr; 5981 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo); 5982 TL.copy(RepTInfo->getTypeLoc()); 5983 } 5984 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) { 5985 TypeSourceInfo *TInfo = nullptr; 5986 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 5987 5988 // If we got no declarator info from previous Sema routines, 5989 // just fill with the typespec loc. 5990 if (!TInfo) { 5991 TL.initialize(Context, DS.getTypeSpecTypeNameLoc()); 5992 return; 5993 } 5994 5995 TypeLoc OldTL = TInfo->getTypeLoc(); 5996 if (TInfo->getType()->getAs<ElaboratedType>()) { 5997 ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>(); 5998 TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc() 5999 .castAs<TemplateSpecializationTypeLoc>(); 6000 TL.copy(NamedTL); 6001 } else { 6002 TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>()); 6003 assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc()); 6004 } 6005 6006 } 6007 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { 6008 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr); 6009 TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); 6010 TL.setParensRange(DS.getTypeofParensRange()); 6011 } 6012 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { 6013 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType); 6014 TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); 6015 TL.setParensRange(DS.getTypeofParensRange()); 6016 assert(DS.getRepAsType()); 6017 TypeSourceInfo *TInfo = nullptr; 6018 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 6019 TL.setUnderlyingTInfo(TInfo); 6020 } 6021 void VisitDecltypeTypeLoc(DecltypeTypeLoc TL) { 6022 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype); 6023 TL.setDecltypeLoc(DS.getTypeSpecTypeLoc()); 6024 TL.setRParenLoc(DS.getTypeofParensRange().getEnd()); 6025 } 6026 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) { 6027 // FIXME: This holds only because we only have one unary transform. 6028 assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType); 6029 TL.setKWLoc(DS.getTypeSpecTypeLoc()); 6030 TL.setParensRange(DS.getTypeofParensRange()); 6031 assert(DS.getRepAsType()); 6032 TypeSourceInfo *TInfo = nullptr; 6033 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 6034 TL.setUnderlyingTInfo(TInfo); 6035 } 6036 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { 6037 // By default, use the source location of the type specifier. 6038 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc()); 6039 if (TL.needsExtraLocalData()) { 6040 // Set info for the written builtin specifiers. 6041 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs(); 6042 // Try to have a meaningful source location. 6043 if (TL.getWrittenSignSpec() != TypeSpecifierSign::Unspecified) 6044 TL.expandBuiltinRange(DS.getTypeSpecSignLoc()); 6045 if (TL.getWrittenWidthSpec() != TypeSpecifierWidth::Unspecified) 6046 TL.expandBuiltinRange(DS.getTypeSpecWidthRange()); 6047 } 6048 } 6049 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { 6050 ElaboratedTypeKeyword Keyword 6051 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType()); 6052 if (DS.getTypeSpecType() == TST_typename) { 6053 TypeSourceInfo *TInfo = nullptr; 6054 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 6055 if (TInfo) { 6056 TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>()); 6057 return; 6058 } 6059 } 6060 TL.setElaboratedKeywordLoc(Keyword != ETK_None 6061 ? DS.getTypeSpecTypeLoc() 6062 : SourceLocation()); 6063 const CXXScopeSpec& SS = DS.getTypeSpecScope(); 6064 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 6065 Visit(TL.getNextTypeLoc().getUnqualifiedLoc()); 6066 } 6067 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { 6068 assert(DS.getTypeSpecType() == TST_typename); 6069 TypeSourceInfo *TInfo = nullptr; 6070 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 6071 assert(TInfo); 6072 TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>()); 6073 } 6074 void VisitDependentTemplateSpecializationTypeLoc( 6075 DependentTemplateSpecializationTypeLoc TL) { 6076 assert(DS.getTypeSpecType() == TST_typename); 6077 TypeSourceInfo *TInfo = nullptr; 6078 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 6079 assert(TInfo); 6080 TL.copy( 6081 TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>()); 6082 } 6083 void VisitAutoTypeLoc(AutoTypeLoc TL) { 6084 assert(DS.getTypeSpecType() == TST_auto || 6085 DS.getTypeSpecType() == TST_decltype_auto || 6086 DS.getTypeSpecType() == TST_auto_type || 6087 DS.getTypeSpecType() == TST_unspecified); 6088 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 6089 if (DS.getTypeSpecType() == TST_decltype_auto) 6090 TL.setRParenLoc(DS.getTypeofParensRange().getEnd()); 6091 if (!DS.isConstrainedAuto()) 6092 return; 6093 TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId(); 6094 if (!TemplateId) 6095 return; 6096 if (DS.getTypeSpecScope().isNotEmpty()) 6097 TL.setNestedNameSpecifierLoc( 6098 DS.getTypeSpecScope().getWithLocInContext(Context)); 6099 else 6100 TL.setNestedNameSpecifierLoc(NestedNameSpecifierLoc()); 6101 TL.setTemplateKWLoc(TemplateId->TemplateKWLoc); 6102 TL.setConceptNameLoc(TemplateId->TemplateNameLoc); 6103 TL.setFoundDecl(nullptr); 6104 TL.setLAngleLoc(TemplateId->LAngleLoc); 6105 TL.setRAngleLoc(TemplateId->RAngleLoc); 6106 if (TemplateId->NumArgs == 0) 6107 return; 6108 TemplateArgumentListInfo TemplateArgsInfo; 6109 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 6110 TemplateId->NumArgs); 6111 SemaRef.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo); 6112 for (unsigned I = 0; I < TemplateId->NumArgs; ++I) 6113 TL.setArgLocInfo(I, TemplateArgsInfo.arguments()[I].getLocInfo()); 6114 } 6115 void VisitTagTypeLoc(TagTypeLoc TL) { 6116 TL.setNameLoc(DS.getTypeSpecTypeNameLoc()); 6117 } 6118 void VisitAtomicTypeLoc(AtomicTypeLoc TL) { 6119 // An AtomicTypeLoc can come from either an _Atomic(...) type specifier 6120 // or an _Atomic qualifier. 6121 if (DS.getTypeSpecType() == DeclSpec::TST_atomic) { 6122 TL.setKWLoc(DS.getTypeSpecTypeLoc()); 6123 TL.setParensRange(DS.getTypeofParensRange()); 6124 6125 TypeSourceInfo *TInfo = nullptr; 6126 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 6127 assert(TInfo); 6128 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc()); 6129 } else { 6130 TL.setKWLoc(DS.getAtomicSpecLoc()); 6131 // No parens, to indicate this was spelled as an _Atomic qualifier. 6132 TL.setParensRange(SourceRange()); 6133 Visit(TL.getValueLoc()); 6134 } 6135 } 6136 6137 void VisitPipeTypeLoc(PipeTypeLoc TL) { 6138 TL.setKWLoc(DS.getTypeSpecTypeLoc()); 6139 6140 TypeSourceInfo *TInfo = nullptr; 6141 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 6142 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc()); 6143 } 6144 6145 void VisitExtIntTypeLoc(BitIntTypeLoc TL) { 6146 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 6147 } 6148 6149 void VisitDependentExtIntTypeLoc(DependentBitIntTypeLoc TL) { 6150 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 6151 } 6152 6153 void VisitTypeLoc(TypeLoc TL) { 6154 // FIXME: add other typespec types and change this to an assert. 6155 TL.initialize(Context, DS.getTypeSpecTypeLoc()); 6156 } 6157 }; 6158 6159 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> { 6160 ASTContext &Context; 6161 TypeProcessingState &State; 6162 const DeclaratorChunk &Chunk; 6163 6164 public: 6165 DeclaratorLocFiller(ASTContext &Context, TypeProcessingState &State, 6166 const DeclaratorChunk &Chunk) 6167 : Context(Context), State(State), Chunk(Chunk) {} 6168 6169 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 6170 llvm_unreachable("qualified type locs not expected here!"); 6171 } 6172 void VisitDecayedTypeLoc(DecayedTypeLoc TL) { 6173 llvm_unreachable("decayed type locs not expected here!"); 6174 } 6175 6176 void VisitAttributedTypeLoc(AttributedTypeLoc TL) { 6177 fillAttributedTypeLoc(TL, State); 6178 } 6179 void VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) { 6180 // nothing 6181 } 6182 void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) { 6183 // nothing 6184 } 6185 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { 6186 assert(Chunk.Kind == DeclaratorChunk::BlockPointer); 6187 TL.setCaretLoc(Chunk.Loc); 6188 } 6189 void VisitPointerTypeLoc(PointerTypeLoc TL) { 6190 assert(Chunk.Kind == DeclaratorChunk::Pointer); 6191 TL.setStarLoc(Chunk.Loc); 6192 } 6193 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 6194 assert(Chunk.Kind == DeclaratorChunk::Pointer); 6195 TL.setStarLoc(Chunk.Loc); 6196 } 6197 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { 6198 assert(Chunk.Kind == DeclaratorChunk::MemberPointer); 6199 const CXXScopeSpec& SS = Chunk.Mem.Scope(); 6200 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context); 6201 6202 const Type* ClsTy = TL.getClass(); 6203 QualType ClsQT = QualType(ClsTy, 0); 6204 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0); 6205 // Now copy source location info into the type loc component. 6206 TypeLoc ClsTL = ClsTInfo->getTypeLoc(); 6207 switch (NNSLoc.getNestedNameSpecifier()->getKind()) { 6208 case NestedNameSpecifier::Identifier: 6209 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc"); 6210 { 6211 DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>(); 6212 DNTLoc.setElaboratedKeywordLoc(SourceLocation()); 6213 DNTLoc.setQualifierLoc(NNSLoc.getPrefix()); 6214 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc()); 6215 } 6216 break; 6217 6218 case NestedNameSpecifier::TypeSpec: 6219 case NestedNameSpecifier::TypeSpecWithTemplate: 6220 if (isa<ElaboratedType>(ClsTy)) { 6221 ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>(); 6222 ETLoc.setElaboratedKeywordLoc(SourceLocation()); 6223 ETLoc.setQualifierLoc(NNSLoc.getPrefix()); 6224 TypeLoc NamedTL = ETLoc.getNamedTypeLoc(); 6225 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc()); 6226 } else { 6227 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc()); 6228 } 6229 break; 6230 6231 case NestedNameSpecifier::Namespace: 6232 case NestedNameSpecifier::NamespaceAlias: 6233 case NestedNameSpecifier::Global: 6234 case NestedNameSpecifier::Super: 6235 llvm_unreachable("Nested-name-specifier must name a type"); 6236 } 6237 6238 // Finally fill in MemberPointerLocInfo fields. 6239 TL.setStarLoc(Chunk.Mem.StarLoc); 6240 TL.setClassTInfo(ClsTInfo); 6241 } 6242 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { 6243 assert(Chunk.Kind == DeclaratorChunk::Reference); 6244 // 'Amp' is misleading: this might have been originally 6245 /// spelled with AmpAmp. 6246 TL.setAmpLoc(Chunk.Loc); 6247 } 6248 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { 6249 assert(Chunk.Kind == DeclaratorChunk::Reference); 6250 assert(!Chunk.Ref.LValueRef); 6251 TL.setAmpAmpLoc(Chunk.Loc); 6252 } 6253 void VisitArrayTypeLoc(ArrayTypeLoc TL) { 6254 assert(Chunk.Kind == DeclaratorChunk::Array); 6255 TL.setLBracketLoc(Chunk.Loc); 6256 TL.setRBracketLoc(Chunk.EndLoc); 6257 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts)); 6258 } 6259 void VisitFunctionTypeLoc(FunctionTypeLoc TL) { 6260 assert(Chunk.Kind == DeclaratorChunk::Function); 6261 TL.setLocalRangeBegin(Chunk.Loc); 6262 TL.setLocalRangeEnd(Chunk.EndLoc); 6263 6264 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun; 6265 TL.setLParenLoc(FTI.getLParenLoc()); 6266 TL.setRParenLoc(FTI.getRParenLoc()); 6267 for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) { 6268 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 6269 TL.setParam(tpi++, Param); 6270 } 6271 TL.setExceptionSpecRange(FTI.getExceptionSpecRange()); 6272 } 6273 void VisitParenTypeLoc(ParenTypeLoc TL) { 6274 assert(Chunk.Kind == DeclaratorChunk::Paren); 6275 TL.setLParenLoc(Chunk.Loc); 6276 TL.setRParenLoc(Chunk.EndLoc); 6277 } 6278 void VisitPipeTypeLoc(PipeTypeLoc TL) { 6279 assert(Chunk.Kind == DeclaratorChunk::Pipe); 6280 TL.setKWLoc(Chunk.Loc); 6281 } 6282 void VisitBitIntTypeLoc(BitIntTypeLoc TL) { 6283 TL.setNameLoc(Chunk.Loc); 6284 } 6285 void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) { 6286 TL.setExpansionLoc(Chunk.Loc); 6287 } 6288 void VisitVectorTypeLoc(VectorTypeLoc TL) { TL.setNameLoc(Chunk.Loc); } 6289 void VisitDependentVectorTypeLoc(DependentVectorTypeLoc TL) { 6290 TL.setNameLoc(Chunk.Loc); 6291 } 6292 void VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) { 6293 TL.setNameLoc(Chunk.Loc); 6294 } 6295 void 6296 VisitDependentSizedExtVectorTypeLoc(DependentSizedExtVectorTypeLoc TL) { 6297 TL.setNameLoc(Chunk.Loc); 6298 } 6299 6300 void VisitTypeLoc(TypeLoc TL) { 6301 llvm_unreachable("unsupported TypeLoc kind in declarator!"); 6302 } 6303 }; 6304 } // end anonymous namespace 6305 6306 static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) { 6307 SourceLocation Loc; 6308 switch (Chunk.Kind) { 6309 case DeclaratorChunk::Function: 6310 case DeclaratorChunk::Array: 6311 case DeclaratorChunk::Paren: 6312 case DeclaratorChunk::Pipe: 6313 llvm_unreachable("cannot be _Atomic qualified"); 6314 6315 case DeclaratorChunk::Pointer: 6316 Loc = Chunk.Ptr.AtomicQualLoc; 6317 break; 6318 6319 case DeclaratorChunk::BlockPointer: 6320 case DeclaratorChunk::Reference: 6321 case DeclaratorChunk::MemberPointer: 6322 // FIXME: Provide a source location for the _Atomic keyword. 6323 break; 6324 } 6325 6326 ATL.setKWLoc(Loc); 6327 ATL.setParensRange(SourceRange()); 6328 } 6329 6330 static void 6331 fillDependentAddressSpaceTypeLoc(DependentAddressSpaceTypeLoc DASTL, 6332 const ParsedAttributesView &Attrs) { 6333 for (const ParsedAttr &AL : Attrs) { 6334 if (AL.getKind() == ParsedAttr::AT_AddressSpace) { 6335 DASTL.setAttrNameLoc(AL.getLoc()); 6336 DASTL.setAttrExprOperand(AL.getArgAsExpr(0)); 6337 DASTL.setAttrOperandParensRange(SourceRange()); 6338 return; 6339 } 6340 } 6341 6342 llvm_unreachable( 6343 "no address_space attribute found at the expected location!"); 6344 } 6345 6346 static void fillMatrixTypeLoc(MatrixTypeLoc MTL, 6347 const ParsedAttributesView &Attrs) { 6348 for (const ParsedAttr &AL : Attrs) { 6349 if (AL.getKind() == ParsedAttr::AT_MatrixType) { 6350 MTL.setAttrNameLoc(AL.getLoc()); 6351 MTL.setAttrRowOperand(AL.getArgAsExpr(0)); 6352 MTL.setAttrColumnOperand(AL.getArgAsExpr(1)); 6353 MTL.setAttrOperandParensRange(SourceRange()); 6354 return; 6355 } 6356 } 6357 6358 llvm_unreachable("no matrix_type attribute found at the expected location!"); 6359 } 6360 6361 /// Create and instantiate a TypeSourceInfo with type source information. 6362 /// 6363 /// \param T QualType referring to the type as written in source code. 6364 /// 6365 /// \param ReturnTypeInfo For declarators whose return type does not show 6366 /// up in the normal place in the declaration specifiers (such as a C++ 6367 /// conversion function), this pointer will refer to a type source information 6368 /// for that return type. 6369 static TypeSourceInfo * 6370 GetTypeSourceInfoForDeclarator(TypeProcessingState &State, 6371 QualType T, TypeSourceInfo *ReturnTypeInfo) { 6372 Sema &S = State.getSema(); 6373 Declarator &D = State.getDeclarator(); 6374 6375 TypeSourceInfo *TInfo = S.Context.CreateTypeSourceInfo(T); 6376 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc(); 6377 6378 // Handle parameter packs whose type is a pack expansion. 6379 if (isa<PackExpansionType>(T)) { 6380 CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc()); 6381 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); 6382 } 6383 6384 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 6385 // An AtomicTypeLoc might be produced by an atomic qualifier in this 6386 // declarator chunk. 6387 if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) { 6388 fillAtomicQualLoc(ATL, D.getTypeObject(i)); 6389 CurrTL = ATL.getValueLoc().getUnqualifiedLoc(); 6390 } 6391 6392 while (MacroQualifiedTypeLoc TL = CurrTL.getAs<MacroQualifiedTypeLoc>()) { 6393 TL.setExpansionLoc( 6394 State.getExpansionLocForMacroQualifiedType(TL.getTypePtr())); 6395 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); 6396 } 6397 6398 while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) { 6399 fillAttributedTypeLoc(TL, State); 6400 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); 6401 } 6402 6403 while (DependentAddressSpaceTypeLoc TL = 6404 CurrTL.getAs<DependentAddressSpaceTypeLoc>()) { 6405 fillDependentAddressSpaceTypeLoc(TL, D.getTypeObject(i).getAttrs()); 6406 CurrTL = TL.getPointeeTypeLoc().getUnqualifiedLoc(); 6407 } 6408 6409 if (MatrixTypeLoc TL = CurrTL.getAs<MatrixTypeLoc>()) 6410 fillMatrixTypeLoc(TL, D.getTypeObject(i).getAttrs()); 6411 6412 // FIXME: Ordering here? 6413 while (AdjustedTypeLoc TL = CurrTL.getAs<AdjustedTypeLoc>()) 6414 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); 6415 6416 DeclaratorLocFiller(S.Context, State, D.getTypeObject(i)).Visit(CurrTL); 6417 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); 6418 } 6419 6420 // If we have different source information for the return type, use 6421 // that. This really only applies to C++ conversion functions. 6422 if (ReturnTypeInfo) { 6423 TypeLoc TL = ReturnTypeInfo->getTypeLoc(); 6424 assert(TL.getFullDataSize() == CurrTL.getFullDataSize()); 6425 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize()); 6426 } else { 6427 TypeSpecLocFiller(S, S.Context, State, D.getDeclSpec()).Visit(CurrTL); 6428 } 6429 6430 return TInfo; 6431 } 6432 6433 /// Create a LocInfoType to hold the given QualType and TypeSourceInfo. 6434 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) { 6435 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser 6436 // and Sema during declaration parsing. Try deallocating/caching them when 6437 // it's appropriate, instead of allocating them and keeping them around. 6438 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType), 6439 TypeAlignment); 6440 new (LocT) LocInfoType(T, TInfo); 6441 assert(LocT->getTypeClass() != T->getTypeClass() && 6442 "LocInfoType's TypeClass conflicts with an existing Type class"); 6443 return ParsedType::make(QualType(LocT, 0)); 6444 } 6445 6446 void LocInfoType::getAsStringInternal(std::string &Str, 6447 const PrintingPolicy &Policy) const { 6448 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*" 6449 " was used directly instead of getting the QualType through" 6450 " GetTypeFromParser"); 6451 } 6452 6453 TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) { 6454 // C99 6.7.6: Type names have no identifier. This is already validated by 6455 // the parser. 6456 assert(D.getIdentifier() == nullptr && 6457 "Type name should have no identifier!"); 6458 6459 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 6460 QualType T = TInfo->getType(); 6461 if (D.isInvalidType()) 6462 return true; 6463 6464 // Make sure there are no unused decl attributes on the declarator. 6465 // We don't want to do this for ObjC parameters because we're going 6466 // to apply them to the actual parameter declaration. 6467 // Likewise, we don't want to do this for alias declarations, because 6468 // we are actually going to build a declaration from this eventually. 6469 if (D.getContext() != DeclaratorContext::ObjCParameter && 6470 D.getContext() != DeclaratorContext::AliasDecl && 6471 D.getContext() != DeclaratorContext::AliasTemplate) 6472 checkUnusedDeclAttributes(D); 6473 6474 if (getLangOpts().CPlusPlus) { 6475 // Check that there are no default arguments (C++ only). 6476 CheckExtraCXXDefaultArguments(D); 6477 } 6478 6479 return CreateParsedType(T, TInfo); 6480 } 6481 6482 ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) { 6483 QualType T = Context.getObjCInstanceType(); 6484 TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 6485 return CreateParsedType(T, TInfo); 6486 } 6487 6488 //===----------------------------------------------------------------------===// 6489 // Type Attribute Processing 6490 //===----------------------------------------------------------------------===// 6491 6492 /// Build an AddressSpace index from a constant expression and diagnose any 6493 /// errors related to invalid address_spaces. Returns true on successfully 6494 /// building an AddressSpace index. 6495 static bool BuildAddressSpaceIndex(Sema &S, LangAS &ASIdx, 6496 const Expr *AddrSpace, 6497 SourceLocation AttrLoc) { 6498 if (!AddrSpace->isValueDependent()) { 6499 Optional<llvm::APSInt> OptAddrSpace = 6500 AddrSpace->getIntegerConstantExpr(S.Context); 6501 if (!OptAddrSpace) { 6502 S.Diag(AttrLoc, diag::err_attribute_argument_type) 6503 << "'address_space'" << AANT_ArgumentIntegerConstant 6504 << AddrSpace->getSourceRange(); 6505 return false; 6506 } 6507 llvm::APSInt &addrSpace = *OptAddrSpace; 6508 6509 // Bounds checking. 6510 if (addrSpace.isSigned()) { 6511 if (addrSpace.isNegative()) { 6512 S.Diag(AttrLoc, diag::err_attribute_address_space_negative) 6513 << AddrSpace->getSourceRange(); 6514 return false; 6515 } 6516 addrSpace.setIsSigned(false); 6517 } 6518 6519 llvm::APSInt max(addrSpace.getBitWidth()); 6520 max = 6521 Qualifiers::MaxAddressSpace - (unsigned)LangAS::FirstTargetAddressSpace; 6522 6523 if (addrSpace > max) { 6524 S.Diag(AttrLoc, diag::err_attribute_address_space_too_high) 6525 << (unsigned)max.getZExtValue() << AddrSpace->getSourceRange(); 6526 return false; 6527 } 6528 6529 ASIdx = 6530 getLangASFromTargetAS(static_cast<unsigned>(addrSpace.getZExtValue())); 6531 return true; 6532 } 6533 6534 // Default value for DependentAddressSpaceTypes 6535 ASIdx = LangAS::Default; 6536 return true; 6537 } 6538 6539 /// BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an expression 6540 /// is uninstantiated. If instantiated it will apply the appropriate address 6541 /// space to the type. This function allows dependent template variables to be 6542 /// used in conjunction with the address_space attribute 6543 QualType Sema::BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace, 6544 SourceLocation AttrLoc) { 6545 if (!AddrSpace->isValueDependent()) { 6546 if (DiagnoseMultipleAddrSpaceAttributes(*this, T.getAddressSpace(), ASIdx, 6547 AttrLoc)) 6548 return QualType(); 6549 6550 return Context.getAddrSpaceQualType(T, ASIdx); 6551 } 6552 6553 // A check with similar intentions as checking if a type already has an 6554 // address space except for on a dependent types, basically if the 6555 // current type is already a DependentAddressSpaceType then its already 6556 // lined up to have another address space on it and we can't have 6557 // multiple address spaces on the one pointer indirection 6558 if (T->getAs<DependentAddressSpaceType>()) { 6559 Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers); 6560 return QualType(); 6561 } 6562 6563 return Context.getDependentAddressSpaceType(T, AddrSpace, AttrLoc); 6564 } 6565 6566 QualType Sema::BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace, 6567 SourceLocation AttrLoc) { 6568 LangAS ASIdx; 6569 if (!BuildAddressSpaceIndex(*this, ASIdx, AddrSpace, AttrLoc)) 6570 return QualType(); 6571 return BuildAddressSpaceAttr(T, ASIdx, AddrSpace, AttrLoc); 6572 } 6573 6574 static void HandleBTFTypeTagAttribute(QualType &Type, const ParsedAttr &Attr, 6575 TypeProcessingState &State) { 6576 Sema &S = State.getSema(); 6577 6578 // Check the number of attribute arguments. 6579 if (Attr.getNumArgs() != 1) { 6580 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 6581 << Attr << 1; 6582 Attr.setInvalid(); 6583 return; 6584 } 6585 6586 // Ensure the argument is a string. 6587 auto *StrLiteral = dyn_cast<StringLiteral>(Attr.getArgAsExpr(0)); 6588 if (!StrLiteral) { 6589 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) 6590 << Attr << AANT_ArgumentString; 6591 Attr.setInvalid(); 6592 return; 6593 } 6594 6595 ASTContext &Ctx = S.Context; 6596 StringRef BTFTypeTag = StrLiteral->getString(); 6597 Type = State.getBTFTagAttributedType( 6598 ::new (Ctx) BTFTypeTagAttr(Ctx, Attr, BTFTypeTag), Type); 6599 } 6600 6601 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the 6602 /// specified type. The attribute contains 1 argument, the id of the address 6603 /// space for the type. 6604 static void HandleAddressSpaceTypeAttribute(QualType &Type, 6605 const ParsedAttr &Attr, 6606 TypeProcessingState &State) { 6607 Sema &S = State.getSema(); 6608 6609 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be 6610 // qualified by an address-space qualifier." 6611 if (Type->isFunctionType()) { 6612 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type); 6613 Attr.setInvalid(); 6614 return; 6615 } 6616 6617 LangAS ASIdx; 6618 if (Attr.getKind() == ParsedAttr::AT_AddressSpace) { 6619 6620 // Check the attribute arguments. 6621 if (Attr.getNumArgs() != 1) { 6622 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr 6623 << 1; 6624 Attr.setInvalid(); 6625 return; 6626 } 6627 6628 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); 6629 LangAS ASIdx; 6630 if (!BuildAddressSpaceIndex(S, ASIdx, ASArgExpr, Attr.getLoc())) { 6631 Attr.setInvalid(); 6632 return; 6633 } 6634 6635 ASTContext &Ctx = S.Context; 6636 auto *ASAttr = 6637 ::new (Ctx) AddressSpaceAttr(Ctx, Attr, static_cast<unsigned>(ASIdx)); 6638 6639 // If the expression is not value dependent (not templated), then we can 6640 // apply the address space qualifiers just to the equivalent type. 6641 // Otherwise, we make an AttributedType with the modified and equivalent 6642 // type the same, and wrap it in a DependentAddressSpaceType. When this 6643 // dependent type is resolved, the qualifier is added to the equivalent type 6644 // later. 6645 QualType T; 6646 if (!ASArgExpr->isValueDependent()) { 6647 QualType EquivType = 6648 S.BuildAddressSpaceAttr(Type, ASIdx, ASArgExpr, Attr.getLoc()); 6649 if (EquivType.isNull()) { 6650 Attr.setInvalid(); 6651 return; 6652 } 6653 T = State.getAttributedType(ASAttr, Type, EquivType); 6654 } else { 6655 T = State.getAttributedType(ASAttr, Type, Type); 6656 T = S.BuildAddressSpaceAttr(T, ASIdx, ASArgExpr, Attr.getLoc()); 6657 } 6658 6659 if (!T.isNull()) 6660 Type = T; 6661 else 6662 Attr.setInvalid(); 6663 } else { 6664 // The keyword-based type attributes imply which address space to use. 6665 ASIdx = S.getLangOpts().SYCLIsDevice ? Attr.asSYCLLangAS() 6666 : Attr.asOpenCLLangAS(); 6667 6668 if (ASIdx == LangAS::Default) 6669 llvm_unreachable("Invalid address space"); 6670 6671 if (DiagnoseMultipleAddrSpaceAttributes(S, Type.getAddressSpace(), ASIdx, 6672 Attr.getLoc())) { 6673 Attr.setInvalid(); 6674 return; 6675 } 6676 6677 Type = S.Context.getAddrSpaceQualType(Type, ASIdx); 6678 } 6679 } 6680 6681 /// handleObjCOwnershipTypeAttr - Process an objc_ownership 6682 /// attribute on the specified type. 6683 /// 6684 /// Returns 'true' if the attribute was handled. 6685 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state, 6686 ParsedAttr &attr, QualType &type) { 6687 bool NonObjCPointer = false; 6688 6689 if (!type->isDependentType() && !type->isUndeducedType()) { 6690 if (const PointerType *ptr = type->getAs<PointerType>()) { 6691 QualType pointee = ptr->getPointeeType(); 6692 if (pointee->isObjCRetainableType() || pointee->isPointerType()) 6693 return false; 6694 // It is important not to lose the source info that there was an attribute 6695 // applied to non-objc pointer. We will create an attributed type but 6696 // its type will be the same as the original type. 6697 NonObjCPointer = true; 6698 } else if (!type->isObjCRetainableType()) { 6699 return false; 6700 } 6701 6702 // Don't accept an ownership attribute in the declspec if it would 6703 // just be the return type of a block pointer. 6704 if (state.isProcessingDeclSpec()) { 6705 Declarator &D = state.getDeclarator(); 6706 if (maybeMovePastReturnType(D, D.getNumTypeObjects(), 6707 /*onlyBlockPointers=*/true)) 6708 return false; 6709 } 6710 } 6711 6712 Sema &S = state.getSema(); 6713 SourceLocation AttrLoc = attr.getLoc(); 6714 if (AttrLoc.isMacroID()) 6715 AttrLoc = 6716 S.getSourceManager().getImmediateExpansionRange(AttrLoc).getBegin(); 6717 6718 if (!attr.isArgIdent(0)) { 6719 S.Diag(AttrLoc, diag::err_attribute_argument_type) << attr 6720 << AANT_ArgumentString; 6721 attr.setInvalid(); 6722 return true; 6723 } 6724 6725 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident; 6726 Qualifiers::ObjCLifetime lifetime; 6727 if (II->isStr("none")) 6728 lifetime = Qualifiers::OCL_ExplicitNone; 6729 else if (II->isStr("strong")) 6730 lifetime = Qualifiers::OCL_Strong; 6731 else if (II->isStr("weak")) 6732 lifetime = Qualifiers::OCL_Weak; 6733 else if (II->isStr("autoreleasing")) 6734 lifetime = Qualifiers::OCL_Autoreleasing; 6735 else { 6736 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported) << attr << II; 6737 attr.setInvalid(); 6738 return true; 6739 } 6740 6741 // Just ignore lifetime attributes other than __weak and __unsafe_unretained 6742 // outside of ARC mode. 6743 if (!S.getLangOpts().ObjCAutoRefCount && 6744 lifetime != Qualifiers::OCL_Weak && 6745 lifetime != Qualifiers::OCL_ExplicitNone) { 6746 return true; 6747 } 6748 6749 SplitQualType underlyingType = type.split(); 6750 6751 // Check for redundant/conflicting ownership qualifiers. 6752 if (Qualifiers::ObjCLifetime previousLifetime 6753 = type.getQualifiers().getObjCLifetime()) { 6754 // If it's written directly, that's an error. 6755 if (S.Context.hasDirectOwnershipQualifier(type)) { 6756 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant) 6757 << type; 6758 return true; 6759 } 6760 6761 // Otherwise, if the qualifiers actually conflict, pull sugar off 6762 // and remove the ObjCLifetime qualifiers. 6763 if (previousLifetime != lifetime) { 6764 // It's possible to have multiple local ObjCLifetime qualifiers. We 6765 // can't stop after we reach a type that is directly qualified. 6766 const Type *prevTy = nullptr; 6767 while (!prevTy || prevTy != underlyingType.Ty) { 6768 prevTy = underlyingType.Ty; 6769 underlyingType = underlyingType.getSingleStepDesugaredType(); 6770 } 6771 underlyingType.Quals.removeObjCLifetime(); 6772 } 6773 } 6774 6775 underlyingType.Quals.addObjCLifetime(lifetime); 6776 6777 if (NonObjCPointer) { 6778 StringRef name = attr.getAttrName()->getName(); 6779 switch (lifetime) { 6780 case Qualifiers::OCL_None: 6781 case Qualifiers::OCL_ExplicitNone: 6782 break; 6783 case Qualifiers::OCL_Strong: name = "__strong"; break; 6784 case Qualifiers::OCL_Weak: name = "__weak"; break; 6785 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break; 6786 } 6787 S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name 6788 << TDS_ObjCObjOrBlock << type; 6789 } 6790 6791 // Don't actually add the __unsafe_unretained qualifier in non-ARC files, 6792 // because having both 'T' and '__unsafe_unretained T' exist in the type 6793 // system causes unfortunate widespread consistency problems. (For example, 6794 // they're not considered compatible types, and we mangle them identicially 6795 // as template arguments.) These problems are all individually fixable, 6796 // but it's easier to just not add the qualifier and instead sniff it out 6797 // in specific places using isObjCInertUnsafeUnretainedType(). 6798 // 6799 // Doing this does means we miss some trivial consistency checks that 6800 // would've triggered in ARC, but that's better than trying to solve all 6801 // the coexistence problems with __unsafe_unretained. 6802 if (!S.getLangOpts().ObjCAutoRefCount && 6803 lifetime == Qualifiers::OCL_ExplicitNone) { 6804 type = state.getAttributedType( 6805 createSimpleAttr<ObjCInertUnsafeUnretainedAttr>(S.Context, attr), 6806 type, type); 6807 return true; 6808 } 6809 6810 QualType origType = type; 6811 if (!NonObjCPointer) 6812 type = S.Context.getQualifiedType(underlyingType); 6813 6814 // If we have a valid source location for the attribute, use an 6815 // AttributedType instead. 6816 if (AttrLoc.isValid()) { 6817 type = state.getAttributedType(::new (S.Context) 6818 ObjCOwnershipAttr(S.Context, attr, II), 6819 origType, type); 6820 } 6821 6822 auto diagnoseOrDelay = [](Sema &S, SourceLocation loc, 6823 unsigned diagnostic, QualType type) { 6824 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) { 6825 S.DelayedDiagnostics.add( 6826 sema::DelayedDiagnostic::makeForbiddenType( 6827 S.getSourceManager().getExpansionLoc(loc), 6828 diagnostic, type, /*ignored*/ 0)); 6829 } else { 6830 S.Diag(loc, diagnostic); 6831 } 6832 }; 6833 6834 // Sometimes, __weak isn't allowed. 6835 if (lifetime == Qualifiers::OCL_Weak && 6836 !S.getLangOpts().ObjCWeak && !NonObjCPointer) { 6837 6838 // Use a specialized diagnostic if the runtime just doesn't support them. 6839 unsigned diagnostic = 6840 (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled 6841 : diag::err_arc_weak_no_runtime); 6842 6843 // In any case, delay the diagnostic until we know what we're parsing. 6844 diagnoseOrDelay(S, AttrLoc, diagnostic, type); 6845 6846 attr.setInvalid(); 6847 return true; 6848 } 6849 6850 // Forbid __weak for class objects marked as 6851 // objc_arc_weak_reference_unavailable 6852 if (lifetime == Qualifiers::OCL_Weak) { 6853 if (const ObjCObjectPointerType *ObjT = 6854 type->getAs<ObjCObjectPointerType>()) { 6855 if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) { 6856 if (Class->isArcWeakrefUnavailable()) { 6857 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class); 6858 S.Diag(ObjT->getInterfaceDecl()->getLocation(), 6859 diag::note_class_declared); 6860 } 6861 } 6862 } 6863 } 6864 6865 return true; 6866 } 6867 6868 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type 6869 /// attribute on the specified type. Returns true to indicate that 6870 /// the attribute was handled, false to indicate that the type does 6871 /// not permit the attribute. 6872 static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr, 6873 QualType &type) { 6874 Sema &S = state.getSema(); 6875 6876 // Delay if this isn't some kind of pointer. 6877 if (!type->isPointerType() && 6878 !type->isObjCObjectPointerType() && 6879 !type->isBlockPointerType()) 6880 return false; 6881 6882 if (type.getObjCGCAttr() != Qualifiers::GCNone) { 6883 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc); 6884 attr.setInvalid(); 6885 return true; 6886 } 6887 6888 // Check the attribute arguments. 6889 if (!attr.isArgIdent(0)) { 6890 S.Diag(attr.getLoc(), diag::err_attribute_argument_type) 6891 << attr << AANT_ArgumentString; 6892 attr.setInvalid(); 6893 return true; 6894 } 6895 Qualifiers::GC GCAttr; 6896 if (attr.getNumArgs() > 1) { 6897 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << attr 6898 << 1; 6899 attr.setInvalid(); 6900 return true; 6901 } 6902 6903 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident; 6904 if (II->isStr("weak")) 6905 GCAttr = Qualifiers::Weak; 6906 else if (II->isStr("strong")) 6907 GCAttr = Qualifiers::Strong; 6908 else { 6909 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported) 6910 << attr << II; 6911 attr.setInvalid(); 6912 return true; 6913 } 6914 6915 QualType origType = type; 6916 type = S.Context.getObjCGCQualType(origType, GCAttr); 6917 6918 // Make an attributed type to preserve the source information. 6919 if (attr.getLoc().isValid()) 6920 type = state.getAttributedType( 6921 ::new (S.Context) ObjCGCAttr(S.Context, attr, II), origType, type); 6922 6923 return true; 6924 } 6925 6926 namespace { 6927 /// A helper class to unwrap a type down to a function for the 6928 /// purposes of applying attributes there. 6929 /// 6930 /// Use: 6931 /// FunctionTypeUnwrapper unwrapped(SemaRef, T); 6932 /// if (unwrapped.isFunctionType()) { 6933 /// const FunctionType *fn = unwrapped.get(); 6934 /// // change fn somehow 6935 /// T = unwrapped.wrap(fn); 6936 /// } 6937 struct FunctionTypeUnwrapper { 6938 enum WrapKind { 6939 Desugar, 6940 Attributed, 6941 Parens, 6942 Array, 6943 Pointer, 6944 BlockPointer, 6945 Reference, 6946 MemberPointer, 6947 MacroQualified, 6948 }; 6949 6950 QualType Original; 6951 const FunctionType *Fn; 6952 SmallVector<unsigned char /*WrapKind*/, 8> Stack; 6953 6954 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) { 6955 while (true) { 6956 const Type *Ty = T.getTypePtr(); 6957 if (isa<FunctionType>(Ty)) { 6958 Fn = cast<FunctionType>(Ty); 6959 return; 6960 } else if (isa<ParenType>(Ty)) { 6961 T = cast<ParenType>(Ty)->getInnerType(); 6962 Stack.push_back(Parens); 6963 } else if (isa<ConstantArrayType>(Ty) || isa<VariableArrayType>(Ty) || 6964 isa<IncompleteArrayType>(Ty)) { 6965 T = cast<ArrayType>(Ty)->getElementType(); 6966 Stack.push_back(Array); 6967 } else if (isa<PointerType>(Ty)) { 6968 T = cast<PointerType>(Ty)->getPointeeType(); 6969 Stack.push_back(Pointer); 6970 } else if (isa<BlockPointerType>(Ty)) { 6971 T = cast<BlockPointerType>(Ty)->getPointeeType(); 6972 Stack.push_back(BlockPointer); 6973 } else if (isa<MemberPointerType>(Ty)) { 6974 T = cast<MemberPointerType>(Ty)->getPointeeType(); 6975 Stack.push_back(MemberPointer); 6976 } else if (isa<ReferenceType>(Ty)) { 6977 T = cast<ReferenceType>(Ty)->getPointeeType(); 6978 Stack.push_back(Reference); 6979 } else if (isa<AttributedType>(Ty)) { 6980 T = cast<AttributedType>(Ty)->getEquivalentType(); 6981 Stack.push_back(Attributed); 6982 } else if (isa<MacroQualifiedType>(Ty)) { 6983 T = cast<MacroQualifiedType>(Ty)->getUnderlyingType(); 6984 Stack.push_back(MacroQualified); 6985 } else { 6986 const Type *DTy = Ty->getUnqualifiedDesugaredType(); 6987 if (Ty == DTy) { 6988 Fn = nullptr; 6989 return; 6990 } 6991 6992 T = QualType(DTy, 0); 6993 Stack.push_back(Desugar); 6994 } 6995 } 6996 } 6997 6998 bool isFunctionType() const { return (Fn != nullptr); } 6999 const FunctionType *get() const { return Fn; } 7000 7001 QualType wrap(Sema &S, const FunctionType *New) { 7002 // If T wasn't modified from the unwrapped type, do nothing. 7003 if (New == get()) return Original; 7004 7005 Fn = New; 7006 return wrap(S.Context, Original, 0); 7007 } 7008 7009 private: 7010 QualType wrap(ASTContext &C, QualType Old, unsigned I) { 7011 if (I == Stack.size()) 7012 return C.getQualifiedType(Fn, Old.getQualifiers()); 7013 7014 // Build up the inner type, applying the qualifiers from the old 7015 // type to the new type. 7016 SplitQualType SplitOld = Old.split(); 7017 7018 // As a special case, tail-recurse if there are no qualifiers. 7019 if (SplitOld.Quals.empty()) 7020 return wrap(C, SplitOld.Ty, I); 7021 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals); 7022 } 7023 7024 QualType wrap(ASTContext &C, const Type *Old, unsigned I) { 7025 if (I == Stack.size()) return QualType(Fn, 0); 7026 7027 switch (static_cast<WrapKind>(Stack[I++])) { 7028 case Desugar: 7029 // This is the point at which we potentially lose source 7030 // information. 7031 return wrap(C, Old->getUnqualifiedDesugaredType(), I); 7032 7033 case Attributed: 7034 return wrap(C, cast<AttributedType>(Old)->getEquivalentType(), I); 7035 7036 case Parens: { 7037 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I); 7038 return C.getParenType(New); 7039 } 7040 7041 case MacroQualified: 7042 return wrap(C, cast<MacroQualifiedType>(Old)->getUnderlyingType(), I); 7043 7044 case Array: { 7045 if (const auto *CAT = dyn_cast<ConstantArrayType>(Old)) { 7046 QualType New = wrap(C, CAT->getElementType(), I); 7047 return C.getConstantArrayType(New, CAT->getSize(), CAT->getSizeExpr(), 7048 CAT->getSizeModifier(), 7049 CAT->getIndexTypeCVRQualifiers()); 7050 } 7051 7052 if (const auto *VAT = dyn_cast<VariableArrayType>(Old)) { 7053 QualType New = wrap(C, VAT->getElementType(), I); 7054 return C.getVariableArrayType( 7055 New, VAT->getSizeExpr(), VAT->getSizeModifier(), 7056 VAT->getIndexTypeCVRQualifiers(), VAT->getBracketsRange()); 7057 } 7058 7059 const auto *IAT = cast<IncompleteArrayType>(Old); 7060 QualType New = wrap(C, IAT->getElementType(), I); 7061 return C.getIncompleteArrayType(New, IAT->getSizeModifier(), 7062 IAT->getIndexTypeCVRQualifiers()); 7063 } 7064 7065 case Pointer: { 7066 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I); 7067 return C.getPointerType(New); 7068 } 7069 7070 case BlockPointer: { 7071 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I); 7072 return C.getBlockPointerType(New); 7073 } 7074 7075 case MemberPointer: { 7076 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old); 7077 QualType New = wrap(C, OldMPT->getPointeeType(), I); 7078 return C.getMemberPointerType(New, OldMPT->getClass()); 7079 } 7080 7081 case Reference: { 7082 const ReferenceType *OldRef = cast<ReferenceType>(Old); 7083 QualType New = wrap(C, OldRef->getPointeeType(), I); 7084 if (isa<LValueReferenceType>(OldRef)) 7085 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue()); 7086 else 7087 return C.getRValueReferenceType(New); 7088 } 7089 } 7090 7091 llvm_unreachable("unknown wrapping kind"); 7092 } 7093 }; 7094 } // end anonymous namespace 7095 7096 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State, 7097 ParsedAttr &PAttr, QualType &Type) { 7098 Sema &S = State.getSema(); 7099 7100 Attr *A; 7101 switch (PAttr.getKind()) { 7102 default: llvm_unreachable("Unknown attribute kind"); 7103 case ParsedAttr::AT_Ptr32: 7104 A = createSimpleAttr<Ptr32Attr>(S.Context, PAttr); 7105 break; 7106 case ParsedAttr::AT_Ptr64: 7107 A = createSimpleAttr<Ptr64Attr>(S.Context, PAttr); 7108 break; 7109 case ParsedAttr::AT_SPtr: 7110 A = createSimpleAttr<SPtrAttr>(S.Context, PAttr); 7111 break; 7112 case ParsedAttr::AT_UPtr: 7113 A = createSimpleAttr<UPtrAttr>(S.Context, PAttr); 7114 break; 7115 } 7116 7117 std::bitset<attr::LastAttr> Attrs; 7118 attr::Kind NewAttrKind = A->getKind(); 7119 QualType Desugared = Type; 7120 const AttributedType *AT = dyn_cast<AttributedType>(Type); 7121 while (AT) { 7122 Attrs[AT->getAttrKind()] = true; 7123 Desugared = AT->getModifiedType(); 7124 AT = dyn_cast<AttributedType>(Desugared); 7125 } 7126 7127 // You cannot specify duplicate type attributes, so if the attribute has 7128 // already been applied, flag it. 7129 if (Attrs[NewAttrKind]) { 7130 S.Diag(PAttr.getLoc(), diag::warn_duplicate_attribute_exact) << PAttr; 7131 return true; 7132 } 7133 Attrs[NewAttrKind] = true; 7134 7135 // You cannot have both __sptr and __uptr on the same type, nor can you 7136 // have __ptr32 and __ptr64. 7137 if (Attrs[attr::Ptr32] && Attrs[attr::Ptr64]) { 7138 S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible) 7139 << "'__ptr32'" 7140 << "'__ptr64'"; 7141 return true; 7142 } else if (Attrs[attr::SPtr] && Attrs[attr::UPtr]) { 7143 S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible) 7144 << "'__sptr'" 7145 << "'__uptr'"; 7146 return true; 7147 } 7148 7149 // Pointer type qualifiers can only operate on pointer types, but not 7150 // pointer-to-member types. 7151 // 7152 // FIXME: Should we really be disallowing this attribute if there is any 7153 // type sugar between it and the pointer (other than attributes)? Eg, this 7154 // disallows the attribute on a parenthesized pointer. 7155 // And if so, should we really allow *any* type attribute? 7156 if (!isa<PointerType>(Desugared)) { 7157 if (Type->isMemberPointerType()) 7158 S.Diag(PAttr.getLoc(), diag::err_attribute_no_member_pointers) << PAttr; 7159 else 7160 S.Diag(PAttr.getLoc(), diag::err_attribute_pointers_only) << PAttr << 0; 7161 return true; 7162 } 7163 7164 // Add address space to type based on its attributes. 7165 LangAS ASIdx = LangAS::Default; 7166 uint64_t PtrWidth = S.Context.getTargetInfo().getPointerWidth(0); 7167 if (PtrWidth == 32) { 7168 if (Attrs[attr::Ptr64]) 7169 ASIdx = LangAS::ptr64; 7170 else if (Attrs[attr::UPtr]) 7171 ASIdx = LangAS::ptr32_uptr; 7172 } else if (PtrWidth == 64 && Attrs[attr::Ptr32]) { 7173 if (Attrs[attr::UPtr]) 7174 ASIdx = LangAS::ptr32_uptr; 7175 else 7176 ASIdx = LangAS::ptr32_sptr; 7177 } 7178 7179 QualType Pointee = Type->getPointeeType(); 7180 if (ASIdx != LangAS::Default) 7181 Pointee = S.Context.getAddrSpaceQualType( 7182 S.Context.removeAddrSpaceQualType(Pointee), ASIdx); 7183 Type = State.getAttributedType(A, Type, S.Context.getPointerType(Pointee)); 7184 return false; 7185 } 7186 7187 /// Map a nullability attribute kind to a nullability kind. 7188 static NullabilityKind mapNullabilityAttrKind(ParsedAttr::Kind kind) { 7189 switch (kind) { 7190 case ParsedAttr::AT_TypeNonNull: 7191 return NullabilityKind::NonNull; 7192 7193 case ParsedAttr::AT_TypeNullable: 7194 return NullabilityKind::Nullable; 7195 7196 case ParsedAttr::AT_TypeNullableResult: 7197 return NullabilityKind::NullableResult; 7198 7199 case ParsedAttr::AT_TypeNullUnspecified: 7200 return NullabilityKind::Unspecified; 7201 7202 default: 7203 llvm_unreachable("not a nullability attribute kind"); 7204 } 7205 } 7206 7207 /// Applies a nullability type specifier to the given type, if possible. 7208 /// 7209 /// \param state The type processing state. 7210 /// 7211 /// \param type The type to which the nullability specifier will be 7212 /// added. On success, this type will be updated appropriately. 7213 /// 7214 /// \param attr The attribute as written on the type. 7215 /// 7216 /// \param allowOnArrayType Whether to accept nullability specifiers on an 7217 /// array type (e.g., because it will decay to a pointer). 7218 /// 7219 /// \returns true if a problem has been diagnosed, false on success. 7220 static bool checkNullabilityTypeSpecifier(TypeProcessingState &state, 7221 QualType &type, 7222 ParsedAttr &attr, 7223 bool allowOnArrayType) { 7224 Sema &S = state.getSema(); 7225 7226 NullabilityKind nullability = mapNullabilityAttrKind(attr.getKind()); 7227 SourceLocation nullabilityLoc = attr.getLoc(); 7228 bool isContextSensitive = attr.isContextSensitiveKeywordAttribute(); 7229 7230 recordNullabilitySeen(S, nullabilityLoc); 7231 7232 // Check for existing nullability attributes on the type. 7233 QualType desugared = type; 7234 while (auto attributed = dyn_cast<AttributedType>(desugared.getTypePtr())) { 7235 // Check whether there is already a null 7236 if (auto existingNullability = attributed->getImmediateNullability()) { 7237 // Duplicated nullability. 7238 if (nullability == *existingNullability) { 7239 S.Diag(nullabilityLoc, diag::warn_nullability_duplicate) 7240 << DiagNullabilityKind(nullability, isContextSensitive) 7241 << FixItHint::CreateRemoval(nullabilityLoc); 7242 7243 break; 7244 } 7245 7246 // Conflicting nullability. 7247 S.Diag(nullabilityLoc, diag::err_nullability_conflicting) 7248 << DiagNullabilityKind(nullability, isContextSensitive) 7249 << DiagNullabilityKind(*existingNullability, false); 7250 return true; 7251 } 7252 7253 desugared = attributed->getModifiedType(); 7254 } 7255 7256 // If there is already a different nullability specifier, complain. 7257 // This (unlike the code above) looks through typedefs that might 7258 // have nullability specifiers on them, which means we cannot 7259 // provide a useful Fix-It. 7260 if (auto existingNullability = desugared->getNullability(S.Context)) { 7261 if (nullability != *existingNullability) { 7262 S.Diag(nullabilityLoc, diag::err_nullability_conflicting) 7263 << DiagNullabilityKind(nullability, isContextSensitive) 7264 << DiagNullabilityKind(*existingNullability, false); 7265 7266 // Try to find the typedef with the existing nullability specifier. 7267 if (auto typedefType = desugared->getAs<TypedefType>()) { 7268 TypedefNameDecl *typedefDecl = typedefType->getDecl(); 7269 QualType underlyingType = typedefDecl->getUnderlyingType(); 7270 if (auto typedefNullability 7271 = AttributedType::stripOuterNullability(underlyingType)) { 7272 if (*typedefNullability == *existingNullability) { 7273 S.Diag(typedefDecl->getLocation(), diag::note_nullability_here) 7274 << DiagNullabilityKind(*existingNullability, false); 7275 } 7276 } 7277 } 7278 7279 return true; 7280 } 7281 } 7282 7283 // If this definitely isn't a pointer type, reject the specifier. 7284 if (!desugared->canHaveNullability() && 7285 !(allowOnArrayType && desugared->isArrayType())) { 7286 S.Diag(nullabilityLoc, diag::err_nullability_nonpointer) 7287 << DiagNullabilityKind(nullability, isContextSensitive) << type; 7288 return true; 7289 } 7290 7291 // For the context-sensitive keywords/Objective-C property 7292 // attributes, require that the type be a single-level pointer. 7293 if (isContextSensitive) { 7294 // Make sure that the pointee isn't itself a pointer type. 7295 const Type *pointeeType = nullptr; 7296 if (desugared->isArrayType()) 7297 pointeeType = desugared->getArrayElementTypeNoTypeQual(); 7298 else if (desugared->isAnyPointerType()) 7299 pointeeType = desugared->getPointeeType().getTypePtr(); 7300 7301 if (pointeeType && (pointeeType->isAnyPointerType() || 7302 pointeeType->isObjCObjectPointerType() || 7303 pointeeType->isMemberPointerType())) { 7304 S.Diag(nullabilityLoc, diag::err_nullability_cs_multilevel) 7305 << DiagNullabilityKind(nullability, true) 7306 << type; 7307 S.Diag(nullabilityLoc, diag::note_nullability_type_specifier) 7308 << DiagNullabilityKind(nullability, false) 7309 << type 7310 << FixItHint::CreateReplacement(nullabilityLoc, 7311 getNullabilitySpelling(nullability)); 7312 return true; 7313 } 7314 } 7315 7316 // Form the attributed type. 7317 type = state.getAttributedType( 7318 createNullabilityAttr(S.Context, attr, nullability), type, type); 7319 return false; 7320 } 7321 7322 /// Check the application of the Objective-C '__kindof' qualifier to 7323 /// the given type. 7324 static bool checkObjCKindOfType(TypeProcessingState &state, QualType &type, 7325 ParsedAttr &attr) { 7326 Sema &S = state.getSema(); 7327 7328 if (isa<ObjCTypeParamType>(type)) { 7329 // Build the attributed type to record where __kindof occurred. 7330 type = state.getAttributedType( 7331 createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, type); 7332 return false; 7333 } 7334 7335 // Find out if it's an Objective-C object or object pointer type; 7336 const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>(); 7337 const ObjCObjectType *objType = ptrType ? ptrType->getObjectType() 7338 : type->getAs<ObjCObjectType>(); 7339 7340 // If not, we can't apply __kindof. 7341 if (!objType) { 7342 // FIXME: Handle dependent types that aren't yet object types. 7343 S.Diag(attr.getLoc(), diag::err_objc_kindof_nonobject) 7344 << type; 7345 return true; 7346 } 7347 7348 // Rebuild the "equivalent" type, which pushes __kindof down into 7349 // the object type. 7350 // There is no need to apply kindof on an unqualified id type. 7351 QualType equivType = S.Context.getObjCObjectType( 7352 objType->getBaseType(), objType->getTypeArgsAsWritten(), 7353 objType->getProtocols(), 7354 /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true); 7355 7356 // If we started with an object pointer type, rebuild it. 7357 if (ptrType) { 7358 equivType = S.Context.getObjCObjectPointerType(equivType); 7359 if (auto nullability = type->getNullability(S.Context)) { 7360 // We create a nullability attribute from the __kindof attribute. 7361 // Make sure that will make sense. 7362 assert(attr.getAttributeSpellingListIndex() == 0 && 7363 "multiple spellings for __kindof?"); 7364 Attr *A = createNullabilityAttr(S.Context, attr, *nullability); 7365 A->setImplicit(true); 7366 equivType = state.getAttributedType(A, equivType, equivType); 7367 } 7368 } 7369 7370 // Build the attributed type to record where __kindof occurred. 7371 type = state.getAttributedType( 7372 createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, equivType); 7373 return false; 7374 } 7375 7376 /// Distribute a nullability type attribute that cannot be applied to 7377 /// the type specifier to a pointer, block pointer, or member pointer 7378 /// declarator, complaining if necessary. 7379 /// 7380 /// \returns true if the nullability annotation was distributed, false 7381 /// otherwise. 7382 static bool distributeNullabilityTypeAttr(TypeProcessingState &state, 7383 QualType type, ParsedAttr &attr) { 7384 Declarator &declarator = state.getDeclarator(); 7385 7386 /// Attempt to move the attribute to the specified chunk. 7387 auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool { 7388 // If there is already a nullability attribute there, don't add 7389 // one. 7390 if (hasNullabilityAttr(chunk.getAttrs())) 7391 return false; 7392 7393 // Complain about the nullability qualifier being in the wrong 7394 // place. 7395 enum { 7396 PK_Pointer, 7397 PK_BlockPointer, 7398 PK_MemberPointer, 7399 PK_FunctionPointer, 7400 PK_MemberFunctionPointer, 7401 } pointerKind 7402 = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer 7403 : PK_Pointer) 7404 : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer 7405 : inFunction? PK_MemberFunctionPointer : PK_MemberPointer; 7406 7407 auto diag = state.getSema().Diag(attr.getLoc(), 7408 diag::warn_nullability_declspec) 7409 << DiagNullabilityKind(mapNullabilityAttrKind(attr.getKind()), 7410 attr.isContextSensitiveKeywordAttribute()) 7411 << type 7412 << static_cast<unsigned>(pointerKind); 7413 7414 // FIXME: MemberPointer chunks don't carry the location of the *. 7415 if (chunk.Kind != DeclaratorChunk::MemberPointer) { 7416 diag << FixItHint::CreateRemoval(attr.getLoc()) 7417 << FixItHint::CreateInsertion( 7418 state.getSema().getPreprocessor().getLocForEndOfToken( 7419 chunk.Loc), 7420 " " + attr.getAttrName()->getName().str() + " "); 7421 } 7422 7423 moveAttrFromListToList(attr, state.getCurrentAttributes(), 7424 chunk.getAttrs()); 7425 return true; 7426 }; 7427 7428 // Move it to the outermost pointer, member pointer, or block 7429 // pointer declarator. 7430 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { 7431 DeclaratorChunk &chunk = declarator.getTypeObject(i-1); 7432 switch (chunk.Kind) { 7433 case DeclaratorChunk::Pointer: 7434 case DeclaratorChunk::BlockPointer: 7435 case DeclaratorChunk::MemberPointer: 7436 return moveToChunk(chunk, false); 7437 7438 case DeclaratorChunk::Paren: 7439 case DeclaratorChunk::Array: 7440 continue; 7441 7442 case DeclaratorChunk::Function: 7443 // Try to move past the return type to a function/block/member 7444 // function pointer. 7445 if (DeclaratorChunk *dest = maybeMovePastReturnType( 7446 declarator, i, 7447 /*onlyBlockPointers=*/false)) { 7448 return moveToChunk(*dest, true); 7449 } 7450 7451 return false; 7452 7453 // Don't walk through these. 7454 case DeclaratorChunk::Reference: 7455 case DeclaratorChunk::Pipe: 7456 return false; 7457 } 7458 } 7459 7460 return false; 7461 } 7462 7463 static Attr *getCCTypeAttr(ASTContext &Ctx, ParsedAttr &Attr) { 7464 assert(!Attr.isInvalid()); 7465 switch (Attr.getKind()) { 7466 default: 7467 llvm_unreachable("not a calling convention attribute"); 7468 case ParsedAttr::AT_CDecl: 7469 return createSimpleAttr<CDeclAttr>(Ctx, Attr); 7470 case ParsedAttr::AT_FastCall: 7471 return createSimpleAttr<FastCallAttr>(Ctx, Attr); 7472 case ParsedAttr::AT_StdCall: 7473 return createSimpleAttr<StdCallAttr>(Ctx, Attr); 7474 case ParsedAttr::AT_ThisCall: 7475 return createSimpleAttr<ThisCallAttr>(Ctx, Attr); 7476 case ParsedAttr::AT_RegCall: 7477 return createSimpleAttr<RegCallAttr>(Ctx, Attr); 7478 case ParsedAttr::AT_Pascal: 7479 return createSimpleAttr<PascalAttr>(Ctx, Attr); 7480 case ParsedAttr::AT_SwiftCall: 7481 return createSimpleAttr<SwiftCallAttr>(Ctx, Attr); 7482 case ParsedAttr::AT_SwiftAsyncCall: 7483 return createSimpleAttr<SwiftAsyncCallAttr>(Ctx, Attr); 7484 case ParsedAttr::AT_VectorCall: 7485 return createSimpleAttr<VectorCallAttr>(Ctx, Attr); 7486 case ParsedAttr::AT_AArch64VectorPcs: 7487 return createSimpleAttr<AArch64VectorPcsAttr>(Ctx, Attr); 7488 case ParsedAttr::AT_AArch64SVEPcs: 7489 return createSimpleAttr<AArch64SVEPcsAttr>(Ctx, Attr); 7490 case ParsedAttr::AT_AMDGPUKernelCall: 7491 return createSimpleAttr<AMDGPUKernelCallAttr>(Ctx, Attr); 7492 case ParsedAttr::AT_Pcs: { 7493 // The attribute may have had a fixit applied where we treated an 7494 // identifier as a string literal. The contents of the string are valid, 7495 // but the form may not be. 7496 StringRef Str; 7497 if (Attr.isArgExpr(0)) 7498 Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString(); 7499 else 7500 Str = Attr.getArgAsIdent(0)->Ident->getName(); 7501 PcsAttr::PCSType Type; 7502 if (!PcsAttr::ConvertStrToPCSType(Str, Type)) 7503 llvm_unreachable("already validated the attribute"); 7504 return ::new (Ctx) PcsAttr(Ctx, Attr, Type); 7505 } 7506 case ParsedAttr::AT_IntelOclBicc: 7507 return createSimpleAttr<IntelOclBiccAttr>(Ctx, Attr); 7508 case ParsedAttr::AT_MSABI: 7509 return createSimpleAttr<MSABIAttr>(Ctx, Attr); 7510 case ParsedAttr::AT_SysVABI: 7511 return createSimpleAttr<SysVABIAttr>(Ctx, Attr); 7512 case ParsedAttr::AT_PreserveMost: 7513 return createSimpleAttr<PreserveMostAttr>(Ctx, Attr); 7514 case ParsedAttr::AT_PreserveAll: 7515 return createSimpleAttr<PreserveAllAttr>(Ctx, Attr); 7516 } 7517 llvm_unreachable("unexpected attribute kind!"); 7518 } 7519 7520 /// Process an individual function attribute. Returns true to 7521 /// indicate that the attribute was handled, false if it wasn't. 7522 static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr, 7523 QualType &type) { 7524 Sema &S = state.getSema(); 7525 7526 FunctionTypeUnwrapper unwrapped(S, type); 7527 7528 if (attr.getKind() == ParsedAttr::AT_NoReturn) { 7529 if (S.CheckAttrNoArgs(attr)) 7530 return true; 7531 7532 // Delay if this is not a function type. 7533 if (!unwrapped.isFunctionType()) 7534 return false; 7535 7536 // Otherwise we can process right away. 7537 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true); 7538 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 7539 return true; 7540 } 7541 7542 if (attr.getKind() == ParsedAttr::AT_CmseNSCall) { 7543 // Delay if this is not a function type. 7544 if (!unwrapped.isFunctionType()) 7545 return false; 7546 7547 // Ignore if we don't have CMSE enabled. 7548 if (!S.getLangOpts().Cmse) { 7549 S.Diag(attr.getLoc(), diag::warn_attribute_ignored) << attr; 7550 attr.setInvalid(); 7551 return true; 7552 } 7553 7554 // Otherwise we can process right away. 7555 FunctionType::ExtInfo EI = 7556 unwrapped.get()->getExtInfo().withCmseNSCall(true); 7557 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 7558 return true; 7559 } 7560 7561 // ns_returns_retained is not always a type attribute, but if we got 7562 // here, we're treating it as one right now. 7563 if (attr.getKind() == ParsedAttr::AT_NSReturnsRetained) { 7564 if (attr.getNumArgs()) return true; 7565 7566 // Delay if this is not a function type. 7567 if (!unwrapped.isFunctionType()) 7568 return false; 7569 7570 // Check whether the return type is reasonable. 7571 if (S.checkNSReturnsRetainedReturnType(attr.getLoc(), 7572 unwrapped.get()->getReturnType())) 7573 return true; 7574 7575 // Only actually change the underlying type in ARC builds. 7576 QualType origType = type; 7577 if (state.getSema().getLangOpts().ObjCAutoRefCount) { 7578 FunctionType::ExtInfo EI 7579 = unwrapped.get()->getExtInfo().withProducesResult(true); 7580 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 7581 } 7582 type = state.getAttributedType( 7583 createSimpleAttr<NSReturnsRetainedAttr>(S.Context, attr), 7584 origType, type); 7585 return true; 7586 } 7587 7588 if (attr.getKind() == ParsedAttr::AT_AnyX86NoCallerSavedRegisters) { 7589 if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr)) 7590 return true; 7591 7592 // Delay if this is not a function type. 7593 if (!unwrapped.isFunctionType()) 7594 return false; 7595 7596 FunctionType::ExtInfo EI = 7597 unwrapped.get()->getExtInfo().withNoCallerSavedRegs(true); 7598 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 7599 return true; 7600 } 7601 7602 if (attr.getKind() == ParsedAttr::AT_AnyX86NoCfCheck) { 7603 if (!S.getLangOpts().CFProtectionBranch) { 7604 S.Diag(attr.getLoc(), diag::warn_nocf_check_attribute_ignored); 7605 attr.setInvalid(); 7606 return true; 7607 } 7608 7609 if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr)) 7610 return true; 7611 7612 // If this is not a function type, warning will be asserted by subject 7613 // check. 7614 if (!unwrapped.isFunctionType()) 7615 return true; 7616 7617 FunctionType::ExtInfo EI = 7618 unwrapped.get()->getExtInfo().withNoCfCheck(true); 7619 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 7620 return true; 7621 } 7622 7623 if (attr.getKind() == ParsedAttr::AT_Regparm) { 7624 unsigned value; 7625 if (S.CheckRegparmAttr(attr, value)) 7626 return true; 7627 7628 // Delay if this is not a function type. 7629 if (!unwrapped.isFunctionType()) 7630 return false; 7631 7632 // Diagnose regparm with fastcall. 7633 const FunctionType *fn = unwrapped.get(); 7634 CallingConv CC = fn->getCallConv(); 7635 if (CC == CC_X86FastCall) { 7636 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 7637 << FunctionType::getNameForCallConv(CC) 7638 << "regparm"; 7639 attr.setInvalid(); 7640 return true; 7641 } 7642 7643 FunctionType::ExtInfo EI = 7644 unwrapped.get()->getExtInfo().withRegParm(value); 7645 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 7646 return true; 7647 } 7648 7649 if (attr.getKind() == ParsedAttr::AT_NoThrow) { 7650 // Delay if this is not a function type. 7651 if (!unwrapped.isFunctionType()) 7652 return false; 7653 7654 if (S.CheckAttrNoArgs(attr)) { 7655 attr.setInvalid(); 7656 return true; 7657 } 7658 7659 // Otherwise we can process right away. 7660 auto *Proto = unwrapped.get()->castAs<FunctionProtoType>(); 7661 7662 // MSVC ignores nothrow if it is in conflict with an explicit exception 7663 // specification. 7664 if (Proto->hasExceptionSpec()) { 7665 switch (Proto->getExceptionSpecType()) { 7666 case EST_None: 7667 llvm_unreachable("This doesn't have an exception spec!"); 7668 7669 case EST_DynamicNone: 7670 case EST_BasicNoexcept: 7671 case EST_NoexceptTrue: 7672 case EST_NoThrow: 7673 // Exception spec doesn't conflict with nothrow, so don't warn. 7674 LLVM_FALLTHROUGH; 7675 case EST_Unparsed: 7676 case EST_Uninstantiated: 7677 case EST_DependentNoexcept: 7678 case EST_Unevaluated: 7679 // We don't have enough information to properly determine if there is a 7680 // conflict, so suppress the warning. 7681 break; 7682 case EST_Dynamic: 7683 case EST_MSAny: 7684 case EST_NoexceptFalse: 7685 S.Diag(attr.getLoc(), diag::warn_nothrow_attribute_ignored); 7686 break; 7687 } 7688 return true; 7689 } 7690 7691 type = unwrapped.wrap( 7692 S, S.Context 7693 .getFunctionTypeWithExceptionSpec( 7694 QualType{Proto, 0}, 7695 FunctionProtoType::ExceptionSpecInfo{EST_NoThrow}) 7696 ->getAs<FunctionType>()); 7697 return true; 7698 } 7699 7700 // Delay if the type didn't work out to a function. 7701 if (!unwrapped.isFunctionType()) return false; 7702 7703 // Otherwise, a calling convention. 7704 CallingConv CC; 7705 if (S.CheckCallingConvAttr(attr, CC)) 7706 return true; 7707 7708 const FunctionType *fn = unwrapped.get(); 7709 CallingConv CCOld = fn->getCallConv(); 7710 Attr *CCAttr = getCCTypeAttr(S.Context, attr); 7711 7712 if (CCOld != CC) { 7713 // Error out on when there's already an attribute on the type 7714 // and the CCs don't match. 7715 if (S.getCallingConvAttributedType(type)) { 7716 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 7717 << FunctionType::getNameForCallConv(CC) 7718 << FunctionType::getNameForCallConv(CCOld); 7719 attr.setInvalid(); 7720 return true; 7721 } 7722 } 7723 7724 // Diagnose use of variadic functions with calling conventions that 7725 // don't support them (e.g. because they're callee-cleanup). 7726 // We delay warning about this on unprototyped function declarations 7727 // until after redeclaration checking, just in case we pick up a 7728 // prototype that way. And apparently we also "delay" warning about 7729 // unprototyped function types in general, despite not necessarily having 7730 // much ability to diagnose it later. 7731 if (!supportsVariadicCall(CC)) { 7732 const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn); 7733 if (FnP && FnP->isVariadic()) { 7734 // stdcall and fastcall are ignored with a warning for GCC and MS 7735 // compatibility. 7736 if (CC == CC_X86StdCall || CC == CC_X86FastCall) 7737 return S.Diag(attr.getLoc(), diag::warn_cconv_unsupported) 7738 << FunctionType::getNameForCallConv(CC) 7739 << (int)Sema::CallingConventionIgnoredReason::VariadicFunction; 7740 7741 attr.setInvalid(); 7742 return S.Diag(attr.getLoc(), diag::err_cconv_varargs) 7743 << FunctionType::getNameForCallConv(CC); 7744 } 7745 } 7746 7747 // Also diagnose fastcall with regparm. 7748 if (CC == CC_X86FastCall && fn->getHasRegParm()) { 7749 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 7750 << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall); 7751 attr.setInvalid(); 7752 return true; 7753 } 7754 7755 // Modify the CC from the wrapped function type, wrap it all back, and then 7756 // wrap the whole thing in an AttributedType as written. The modified type 7757 // might have a different CC if we ignored the attribute. 7758 QualType Equivalent; 7759 if (CCOld == CC) { 7760 Equivalent = type; 7761 } else { 7762 auto EI = unwrapped.get()->getExtInfo().withCallingConv(CC); 7763 Equivalent = 7764 unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 7765 } 7766 type = state.getAttributedType(CCAttr, type, Equivalent); 7767 return true; 7768 } 7769 7770 bool Sema::hasExplicitCallingConv(QualType T) { 7771 const AttributedType *AT; 7772 7773 // Stop if we'd be stripping off a typedef sugar node to reach the 7774 // AttributedType. 7775 while ((AT = T->getAs<AttributedType>()) && 7776 AT->getAs<TypedefType>() == T->getAs<TypedefType>()) { 7777 if (AT->isCallingConv()) 7778 return true; 7779 T = AT->getModifiedType(); 7780 } 7781 return false; 7782 } 7783 7784 void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor, 7785 SourceLocation Loc) { 7786 FunctionTypeUnwrapper Unwrapped(*this, T); 7787 const FunctionType *FT = Unwrapped.get(); 7788 bool IsVariadic = (isa<FunctionProtoType>(FT) && 7789 cast<FunctionProtoType>(FT)->isVariadic()); 7790 CallingConv CurCC = FT->getCallConv(); 7791 CallingConv ToCC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic); 7792 7793 if (CurCC == ToCC) 7794 return; 7795 7796 // MS compiler ignores explicit calling convention attributes on structors. We 7797 // should do the same. 7798 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) { 7799 // Issue a warning on ignored calling convention -- except of __stdcall. 7800 // Again, this is what MS compiler does. 7801 if (CurCC != CC_X86StdCall) 7802 Diag(Loc, diag::warn_cconv_unsupported) 7803 << FunctionType::getNameForCallConv(CurCC) 7804 << (int)Sema::CallingConventionIgnoredReason::ConstructorDestructor; 7805 // Default adjustment. 7806 } else { 7807 // Only adjust types with the default convention. For example, on Windows 7808 // we should adjust a __cdecl type to __thiscall for instance methods, and a 7809 // __thiscall type to __cdecl for static methods. 7810 CallingConv DefaultCC = 7811 Context.getDefaultCallingConvention(IsVariadic, IsStatic); 7812 7813 if (CurCC != DefaultCC || DefaultCC == ToCC) 7814 return; 7815 7816 if (hasExplicitCallingConv(T)) 7817 return; 7818 } 7819 7820 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC)); 7821 QualType Wrapped = Unwrapped.wrap(*this, FT); 7822 T = Context.getAdjustedType(T, Wrapped); 7823 } 7824 7825 /// HandleVectorSizeAttribute - this attribute is only applicable to integral 7826 /// and float scalars, although arrays, pointers, and function return values are 7827 /// allowed in conjunction with this construct. Aggregates with this attribute 7828 /// are invalid, even if they are of the same size as a corresponding scalar. 7829 /// The raw attribute should contain precisely 1 argument, the vector size for 7830 /// the variable, measured in bytes. If curType and rawAttr are well formed, 7831 /// this routine will return a new vector type. 7832 static void HandleVectorSizeAttr(QualType &CurType, const ParsedAttr &Attr, 7833 Sema &S) { 7834 // Check the attribute arguments. 7835 if (Attr.getNumArgs() != 1) { 7836 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr 7837 << 1; 7838 Attr.setInvalid(); 7839 return; 7840 } 7841 7842 Expr *SizeExpr = Attr.getArgAsExpr(0); 7843 QualType T = S.BuildVectorType(CurType, SizeExpr, Attr.getLoc()); 7844 if (!T.isNull()) 7845 CurType = T; 7846 else 7847 Attr.setInvalid(); 7848 } 7849 7850 /// Process the OpenCL-like ext_vector_type attribute when it occurs on 7851 /// a type. 7852 static void HandleExtVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr, 7853 Sema &S) { 7854 // check the attribute arguments. 7855 if (Attr.getNumArgs() != 1) { 7856 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr 7857 << 1; 7858 return; 7859 } 7860 7861 Expr *SizeExpr = Attr.getArgAsExpr(0); 7862 QualType T = S.BuildExtVectorType(CurType, SizeExpr, Attr.getLoc()); 7863 if (!T.isNull()) 7864 CurType = T; 7865 } 7866 7867 static bool isPermittedNeonBaseType(QualType &Ty, 7868 VectorType::VectorKind VecKind, Sema &S) { 7869 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 7870 if (!BTy) 7871 return false; 7872 7873 llvm::Triple Triple = S.Context.getTargetInfo().getTriple(); 7874 7875 // Signed poly is mathematically wrong, but has been baked into some ABIs by 7876 // now. 7877 bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 || 7878 Triple.getArch() == llvm::Triple::aarch64_32 || 7879 Triple.getArch() == llvm::Triple::aarch64_be; 7880 if (VecKind == VectorType::NeonPolyVector) { 7881 if (IsPolyUnsigned) { 7882 // AArch64 polynomial vectors are unsigned. 7883 return BTy->getKind() == BuiltinType::UChar || 7884 BTy->getKind() == BuiltinType::UShort || 7885 BTy->getKind() == BuiltinType::ULong || 7886 BTy->getKind() == BuiltinType::ULongLong; 7887 } else { 7888 // AArch32 polynomial vectors are signed. 7889 return BTy->getKind() == BuiltinType::SChar || 7890 BTy->getKind() == BuiltinType::Short || 7891 BTy->getKind() == BuiltinType::LongLong; 7892 } 7893 } 7894 7895 // Non-polynomial vector types: the usual suspects are allowed, as well as 7896 // float64_t on AArch64. 7897 if ((Triple.isArch64Bit() || Triple.getArch() == llvm::Triple::aarch64_32) && 7898 BTy->getKind() == BuiltinType::Double) 7899 return true; 7900 7901 return BTy->getKind() == BuiltinType::SChar || 7902 BTy->getKind() == BuiltinType::UChar || 7903 BTy->getKind() == BuiltinType::Short || 7904 BTy->getKind() == BuiltinType::UShort || 7905 BTy->getKind() == BuiltinType::Int || 7906 BTy->getKind() == BuiltinType::UInt || 7907 BTy->getKind() == BuiltinType::Long || 7908 BTy->getKind() == BuiltinType::ULong || 7909 BTy->getKind() == BuiltinType::LongLong || 7910 BTy->getKind() == BuiltinType::ULongLong || 7911 BTy->getKind() == BuiltinType::Float || 7912 BTy->getKind() == BuiltinType::Half || 7913 BTy->getKind() == BuiltinType::BFloat16; 7914 } 7915 7916 static bool verifyValidIntegerConstantExpr(Sema &S, const ParsedAttr &Attr, 7917 llvm::APSInt &Result) { 7918 const auto *AttrExpr = Attr.getArgAsExpr(0); 7919 if (!AttrExpr->isTypeDependent()) { 7920 if (Optional<llvm::APSInt> Res = 7921 AttrExpr->getIntegerConstantExpr(S.Context)) { 7922 Result = *Res; 7923 return true; 7924 } 7925 } 7926 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) 7927 << Attr << AANT_ArgumentIntegerConstant << AttrExpr->getSourceRange(); 7928 Attr.setInvalid(); 7929 return false; 7930 } 7931 7932 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and 7933 /// "neon_polyvector_type" attributes are used to create vector types that 7934 /// are mangled according to ARM's ABI. Otherwise, these types are identical 7935 /// to those created with the "vector_size" attribute. Unlike "vector_size" 7936 /// the argument to these Neon attributes is the number of vector elements, 7937 /// not the vector size in bytes. The vector width and element type must 7938 /// match one of the standard Neon vector types. 7939 static void HandleNeonVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr, 7940 Sema &S, VectorType::VectorKind VecKind) { 7941 // Target must have NEON (or MVE, whose vectors are similar enough 7942 // not to need a separate attribute) 7943 if (!S.Context.getTargetInfo().hasFeature("neon") && 7944 !S.Context.getTargetInfo().hasFeature("mve")) { 7945 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) 7946 << Attr << "'neon' or 'mve'"; 7947 Attr.setInvalid(); 7948 return; 7949 } 7950 // Check the attribute arguments. 7951 if (Attr.getNumArgs() != 1) { 7952 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr 7953 << 1; 7954 Attr.setInvalid(); 7955 return; 7956 } 7957 // The number of elements must be an ICE. 7958 llvm::APSInt numEltsInt(32); 7959 if (!verifyValidIntegerConstantExpr(S, Attr, numEltsInt)) 7960 return; 7961 7962 // Only certain element types are supported for Neon vectors. 7963 if (!isPermittedNeonBaseType(CurType, VecKind, S)) { 7964 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType; 7965 Attr.setInvalid(); 7966 return; 7967 } 7968 7969 // The total size of the vector must be 64 or 128 bits. 7970 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType)); 7971 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue()); 7972 unsigned vecSize = typeSize * numElts; 7973 if (vecSize != 64 && vecSize != 128) { 7974 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType; 7975 Attr.setInvalid(); 7976 return; 7977 } 7978 7979 CurType = S.Context.getVectorType(CurType, numElts, VecKind); 7980 } 7981 7982 /// HandleArmSveVectorBitsTypeAttr - The "arm_sve_vector_bits" attribute is 7983 /// used to create fixed-length versions of sizeless SVE types defined by 7984 /// the ACLE, such as svint32_t and svbool_t. 7985 static void HandleArmSveVectorBitsTypeAttr(QualType &CurType, ParsedAttr &Attr, 7986 Sema &S) { 7987 // Target must have SVE. 7988 if (!S.Context.getTargetInfo().hasFeature("sve")) { 7989 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr << "'sve'"; 7990 Attr.setInvalid(); 7991 return; 7992 } 7993 7994 // Attribute is unsupported if '-msve-vector-bits=<bits>' isn't specified, or 7995 // if <bits>+ syntax is used. 7996 if (!S.getLangOpts().VScaleMin || 7997 S.getLangOpts().VScaleMin != S.getLangOpts().VScaleMax) { 7998 S.Diag(Attr.getLoc(), diag::err_attribute_arm_feature_sve_bits_unsupported) 7999 << Attr; 8000 Attr.setInvalid(); 8001 return; 8002 } 8003 8004 // Check the attribute arguments. 8005 if (Attr.getNumArgs() != 1) { 8006 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 8007 << Attr << 1; 8008 Attr.setInvalid(); 8009 return; 8010 } 8011 8012 // The vector size must be an integer constant expression. 8013 llvm::APSInt SveVectorSizeInBits(32); 8014 if (!verifyValidIntegerConstantExpr(S, Attr, SveVectorSizeInBits)) 8015 return; 8016 8017 unsigned VecSize = static_cast<unsigned>(SveVectorSizeInBits.getZExtValue()); 8018 8019 // The attribute vector size must match -msve-vector-bits. 8020 if (VecSize != S.getLangOpts().VScaleMin * 128) { 8021 S.Diag(Attr.getLoc(), diag::err_attribute_bad_sve_vector_size) 8022 << VecSize << S.getLangOpts().VScaleMin * 128; 8023 Attr.setInvalid(); 8024 return; 8025 } 8026 8027 // Attribute can only be attached to a single SVE vector or predicate type. 8028 if (!CurType->isVLSTBuiltinType()) { 8029 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_sve_type) 8030 << Attr << CurType; 8031 Attr.setInvalid(); 8032 return; 8033 } 8034 8035 const auto *BT = CurType->castAs<BuiltinType>(); 8036 8037 QualType EltType = CurType->getSveEltType(S.Context); 8038 unsigned TypeSize = S.Context.getTypeSize(EltType); 8039 VectorType::VectorKind VecKind = VectorType::SveFixedLengthDataVector; 8040 if (BT->getKind() == BuiltinType::SveBool) { 8041 // Predicates are represented as i8. 8042 VecSize /= S.Context.getCharWidth() * S.Context.getCharWidth(); 8043 VecKind = VectorType::SveFixedLengthPredicateVector; 8044 } else 8045 VecSize /= TypeSize; 8046 CurType = S.Context.getVectorType(EltType, VecSize, VecKind); 8047 } 8048 8049 static void HandleArmMveStrictPolymorphismAttr(TypeProcessingState &State, 8050 QualType &CurType, 8051 ParsedAttr &Attr) { 8052 const VectorType *VT = dyn_cast<VectorType>(CurType); 8053 if (!VT || VT->getVectorKind() != VectorType::NeonVector) { 8054 State.getSema().Diag(Attr.getLoc(), 8055 diag::err_attribute_arm_mve_polymorphism); 8056 Attr.setInvalid(); 8057 return; 8058 } 8059 8060 CurType = 8061 State.getAttributedType(createSimpleAttr<ArmMveStrictPolymorphismAttr>( 8062 State.getSema().Context, Attr), 8063 CurType, CurType); 8064 } 8065 8066 /// Handle OpenCL Access Qualifier Attribute. 8067 static void HandleOpenCLAccessAttr(QualType &CurType, const ParsedAttr &Attr, 8068 Sema &S) { 8069 // OpenCL v2.0 s6.6 - Access qualifier can be used only for image and pipe type. 8070 if (!(CurType->isImageType() || CurType->isPipeType())) { 8071 S.Diag(Attr.getLoc(), diag::err_opencl_invalid_access_qualifier); 8072 Attr.setInvalid(); 8073 return; 8074 } 8075 8076 if (const TypedefType* TypedefTy = CurType->getAs<TypedefType>()) { 8077 QualType BaseTy = TypedefTy->desugar(); 8078 8079 std::string PrevAccessQual; 8080 if (BaseTy->isPipeType()) { 8081 if (TypedefTy->getDecl()->hasAttr<OpenCLAccessAttr>()) { 8082 OpenCLAccessAttr *Attr = 8083 TypedefTy->getDecl()->getAttr<OpenCLAccessAttr>(); 8084 PrevAccessQual = Attr->getSpelling(); 8085 } else { 8086 PrevAccessQual = "read_only"; 8087 } 8088 } else if (const BuiltinType* ImgType = BaseTy->getAs<BuiltinType>()) { 8089 8090 switch (ImgType->getKind()) { 8091 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 8092 case BuiltinType::Id: \ 8093 PrevAccessQual = #Access; \ 8094 break; 8095 #include "clang/Basic/OpenCLImageTypes.def" 8096 default: 8097 llvm_unreachable("Unable to find corresponding image type."); 8098 } 8099 } else { 8100 llvm_unreachable("unexpected type"); 8101 } 8102 StringRef AttrName = Attr.getAttrName()->getName(); 8103 if (PrevAccessQual == AttrName.ltrim("_")) { 8104 // Duplicated qualifiers 8105 S.Diag(Attr.getLoc(), diag::warn_duplicate_declspec) 8106 << AttrName << Attr.getRange(); 8107 } else { 8108 // Contradicting qualifiers 8109 S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers); 8110 } 8111 8112 S.Diag(TypedefTy->getDecl()->getBeginLoc(), 8113 diag::note_opencl_typedef_access_qualifier) << PrevAccessQual; 8114 } else if (CurType->isPipeType()) { 8115 if (Attr.getSemanticSpelling() == OpenCLAccessAttr::Keyword_write_only) { 8116 QualType ElemType = CurType->castAs<PipeType>()->getElementType(); 8117 CurType = S.Context.getWritePipeType(ElemType); 8118 } 8119 } 8120 } 8121 8122 /// HandleMatrixTypeAttr - "matrix_type" attribute, like ext_vector_type 8123 static void HandleMatrixTypeAttr(QualType &CurType, const ParsedAttr &Attr, 8124 Sema &S) { 8125 if (!S.getLangOpts().MatrixTypes) { 8126 S.Diag(Attr.getLoc(), diag::err_builtin_matrix_disabled); 8127 return; 8128 } 8129 8130 if (Attr.getNumArgs() != 2) { 8131 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 8132 << Attr << 2; 8133 return; 8134 } 8135 8136 Expr *RowsExpr = Attr.getArgAsExpr(0); 8137 Expr *ColsExpr = Attr.getArgAsExpr(1); 8138 QualType T = S.BuildMatrixType(CurType, RowsExpr, ColsExpr, Attr.getLoc()); 8139 if (!T.isNull()) 8140 CurType = T; 8141 } 8142 8143 static void HandleLifetimeBoundAttr(TypeProcessingState &State, 8144 QualType &CurType, 8145 ParsedAttr &Attr) { 8146 if (State.getDeclarator().isDeclarationOfFunction()) { 8147 CurType = State.getAttributedType( 8148 createSimpleAttr<LifetimeBoundAttr>(State.getSema().Context, Attr), 8149 CurType, CurType); 8150 } 8151 } 8152 8153 static bool isAddressSpaceKind(const ParsedAttr &attr) { 8154 auto attrKind = attr.getKind(); 8155 8156 return attrKind == ParsedAttr::AT_AddressSpace || 8157 attrKind == ParsedAttr::AT_OpenCLPrivateAddressSpace || 8158 attrKind == ParsedAttr::AT_OpenCLGlobalAddressSpace || 8159 attrKind == ParsedAttr::AT_OpenCLGlobalDeviceAddressSpace || 8160 attrKind == ParsedAttr::AT_OpenCLGlobalHostAddressSpace || 8161 attrKind == ParsedAttr::AT_OpenCLLocalAddressSpace || 8162 attrKind == ParsedAttr::AT_OpenCLConstantAddressSpace || 8163 attrKind == ParsedAttr::AT_OpenCLGenericAddressSpace; 8164 } 8165 8166 static void processTypeAttrs(TypeProcessingState &state, QualType &type, 8167 TypeAttrLocation TAL, 8168 const ParsedAttributesView &attrs) { 8169 8170 state.setParsedNoDeref(false); 8171 if (attrs.empty()) 8172 return; 8173 8174 // Scan through and apply attributes to this type where it makes sense. Some 8175 // attributes (such as __address_space__, __vector_size__, etc) apply to the 8176 // type, but others can be present in the type specifiers even though they 8177 // apply to the decl. Here we apply type attributes and ignore the rest. 8178 8179 // This loop modifies the list pretty frequently, but we still need to make 8180 // sure we visit every element once. Copy the attributes list, and iterate 8181 // over that. 8182 ParsedAttributesView AttrsCopy{attrs}; 8183 for (ParsedAttr &attr : AttrsCopy) { 8184 8185 // Skip attributes that were marked to be invalid. 8186 if (attr.isInvalid()) 8187 continue; 8188 8189 if (attr.isStandardAttributeSyntax()) { 8190 // [[gnu::...]] attributes are treated as declaration attributes, so may 8191 // not appertain to a DeclaratorChunk. If we handle them as type 8192 // attributes, accept them in that position and diagnose the GCC 8193 // incompatibility. 8194 if (attr.isGNUScope()) { 8195 bool IsTypeAttr = attr.isTypeAttr(); 8196 if (TAL == TAL_DeclChunk) { 8197 state.getSema().Diag(attr.getLoc(), 8198 IsTypeAttr 8199 ? diag::warn_gcc_ignores_type_attr 8200 : diag::warn_cxx11_gnu_attribute_on_type) 8201 << attr; 8202 if (!IsTypeAttr) 8203 continue; 8204 } 8205 } else if (TAL != TAL_DeclChunk && !isAddressSpaceKind(attr)) { 8206 // Otherwise, only consider type processing for a C++11 attribute if 8207 // it's actually been applied to a type. 8208 // We also allow C++11 address_space and 8209 // OpenCL language address space attributes to pass through. 8210 continue; 8211 } 8212 } 8213 8214 // If this is an attribute we can handle, do so now, 8215 // otherwise, add it to the FnAttrs list for rechaining. 8216 switch (attr.getKind()) { 8217 default: 8218 // A [[]] attribute on a declarator chunk must appertain to a type. 8219 if (attr.isStandardAttributeSyntax() && TAL == TAL_DeclChunk) { 8220 state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr) 8221 << attr; 8222 attr.setUsedAsTypeAttr(); 8223 } 8224 break; 8225 8226 case ParsedAttr::UnknownAttribute: 8227 if (attr.isStandardAttributeSyntax() && TAL == TAL_DeclChunk) 8228 state.getSema().Diag(attr.getLoc(), 8229 diag::warn_unknown_attribute_ignored) 8230 << attr << attr.getRange(); 8231 break; 8232 8233 case ParsedAttr::IgnoredAttribute: 8234 break; 8235 8236 case ParsedAttr::AT_BTFTypeTag: 8237 HandleBTFTypeTagAttribute(type, attr, state); 8238 attr.setUsedAsTypeAttr(); 8239 break; 8240 8241 case ParsedAttr::AT_MayAlias: 8242 // FIXME: This attribute needs to actually be handled, but if we ignore 8243 // it it breaks large amounts of Linux software. 8244 attr.setUsedAsTypeAttr(); 8245 break; 8246 case ParsedAttr::AT_OpenCLPrivateAddressSpace: 8247 case ParsedAttr::AT_OpenCLGlobalAddressSpace: 8248 case ParsedAttr::AT_OpenCLGlobalDeviceAddressSpace: 8249 case ParsedAttr::AT_OpenCLGlobalHostAddressSpace: 8250 case ParsedAttr::AT_OpenCLLocalAddressSpace: 8251 case ParsedAttr::AT_OpenCLConstantAddressSpace: 8252 case ParsedAttr::AT_OpenCLGenericAddressSpace: 8253 case ParsedAttr::AT_AddressSpace: 8254 HandleAddressSpaceTypeAttribute(type, attr, state); 8255 attr.setUsedAsTypeAttr(); 8256 break; 8257 OBJC_POINTER_TYPE_ATTRS_CASELIST: 8258 if (!handleObjCPointerTypeAttr(state, attr, type)) 8259 distributeObjCPointerTypeAttr(state, attr, type); 8260 attr.setUsedAsTypeAttr(); 8261 break; 8262 case ParsedAttr::AT_VectorSize: 8263 HandleVectorSizeAttr(type, attr, state.getSema()); 8264 attr.setUsedAsTypeAttr(); 8265 break; 8266 case ParsedAttr::AT_ExtVectorType: 8267 HandleExtVectorTypeAttr(type, attr, state.getSema()); 8268 attr.setUsedAsTypeAttr(); 8269 break; 8270 case ParsedAttr::AT_NeonVectorType: 8271 HandleNeonVectorTypeAttr(type, attr, state.getSema(), 8272 VectorType::NeonVector); 8273 attr.setUsedAsTypeAttr(); 8274 break; 8275 case ParsedAttr::AT_NeonPolyVectorType: 8276 HandleNeonVectorTypeAttr(type, attr, state.getSema(), 8277 VectorType::NeonPolyVector); 8278 attr.setUsedAsTypeAttr(); 8279 break; 8280 case ParsedAttr::AT_ArmSveVectorBits: 8281 HandleArmSveVectorBitsTypeAttr(type, attr, state.getSema()); 8282 attr.setUsedAsTypeAttr(); 8283 break; 8284 case ParsedAttr::AT_ArmMveStrictPolymorphism: { 8285 HandleArmMveStrictPolymorphismAttr(state, type, attr); 8286 attr.setUsedAsTypeAttr(); 8287 break; 8288 } 8289 case ParsedAttr::AT_OpenCLAccess: 8290 HandleOpenCLAccessAttr(type, attr, state.getSema()); 8291 attr.setUsedAsTypeAttr(); 8292 break; 8293 case ParsedAttr::AT_LifetimeBound: 8294 if (TAL == TAL_DeclChunk) 8295 HandleLifetimeBoundAttr(state, type, attr); 8296 break; 8297 8298 case ParsedAttr::AT_NoDeref: { 8299 ASTContext &Ctx = state.getSema().Context; 8300 type = state.getAttributedType(createSimpleAttr<NoDerefAttr>(Ctx, attr), 8301 type, type); 8302 attr.setUsedAsTypeAttr(); 8303 state.setParsedNoDeref(true); 8304 break; 8305 } 8306 8307 case ParsedAttr::AT_MatrixType: 8308 HandleMatrixTypeAttr(type, attr, state.getSema()); 8309 attr.setUsedAsTypeAttr(); 8310 break; 8311 8312 MS_TYPE_ATTRS_CASELIST: 8313 if (!handleMSPointerTypeQualifierAttr(state, attr, type)) 8314 attr.setUsedAsTypeAttr(); 8315 break; 8316 8317 8318 NULLABILITY_TYPE_ATTRS_CASELIST: 8319 // Either add nullability here or try to distribute it. We 8320 // don't want to distribute the nullability specifier past any 8321 // dependent type, because that complicates the user model. 8322 if (type->canHaveNullability() || type->isDependentType() || 8323 type->isArrayType() || 8324 !distributeNullabilityTypeAttr(state, type, attr)) { 8325 unsigned endIndex; 8326 if (TAL == TAL_DeclChunk) 8327 endIndex = state.getCurrentChunkIndex(); 8328 else 8329 endIndex = state.getDeclarator().getNumTypeObjects(); 8330 bool allowOnArrayType = 8331 state.getDeclarator().isPrototypeContext() && 8332 !hasOuterPointerLikeChunk(state.getDeclarator(), endIndex); 8333 if (checkNullabilityTypeSpecifier( 8334 state, 8335 type, 8336 attr, 8337 allowOnArrayType)) { 8338 attr.setInvalid(); 8339 } 8340 8341 attr.setUsedAsTypeAttr(); 8342 } 8343 break; 8344 8345 case ParsedAttr::AT_ObjCKindOf: 8346 // '__kindof' must be part of the decl-specifiers. 8347 switch (TAL) { 8348 case TAL_DeclSpec: 8349 break; 8350 8351 case TAL_DeclChunk: 8352 case TAL_DeclName: 8353 state.getSema().Diag(attr.getLoc(), 8354 diag::err_objc_kindof_wrong_position) 8355 << FixItHint::CreateRemoval(attr.getLoc()) 8356 << FixItHint::CreateInsertion( 8357 state.getDeclarator().getDeclSpec().getBeginLoc(), 8358 "__kindof "); 8359 break; 8360 } 8361 8362 // Apply it regardless. 8363 if (checkObjCKindOfType(state, type, attr)) 8364 attr.setInvalid(); 8365 break; 8366 8367 case ParsedAttr::AT_NoThrow: 8368 // Exception Specifications aren't generally supported in C mode throughout 8369 // clang, so revert to attribute-based handling for C. 8370 if (!state.getSema().getLangOpts().CPlusPlus) 8371 break; 8372 LLVM_FALLTHROUGH; 8373 FUNCTION_TYPE_ATTRS_CASELIST: 8374 attr.setUsedAsTypeAttr(); 8375 8376 // Never process function type attributes as part of the 8377 // declaration-specifiers. 8378 if (TAL == TAL_DeclSpec) 8379 distributeFunctionTypeAttrFromDeclSpec(state, attr, type); 8380 8381 // Otherwise, handle the possible delays. 8382 else if (!handleFunctionTypeAttr(state, attr, type)) 8383 distributeFunctionTypeAttr(state, attr, type); 8384 break; 8385 case ParsedAttr::AT_AcquireHandle: { 8386 if (!type->isFunctionType()) 8387 return; 8388 8389 if (attr.getNumArgs() != 1) { 8390 state.getSema().Diag(attr.getLoc(), 8391 diag::err_attribute_wrong_number_arguments) 8392 << attr << 1; 8393 attr.setInvalid(); 8394 return; 8395 } 8396 8397 StringRef HandleType; 8398 if (!state.getSema().checkStringLiteralArgumentAttr(attr, 0, HandleType)) 8399 return; 8400 type = state.getAttributedType( 8401 AcquireHandleAttr::Create(state.getSema().Context, HandleType, attr), 8402 type, type); 8403 attr.setUsedAsTypeAttr(); 8404 break; 8405 } 8406 } 8407 8408 // Handle attributes that are defined in a macro. We do not want this to be 8409 // applied to ObjC builtin attributes. 8410 if (isa<AttributedType>(type) && attr.hasMacroIdentifier() && 8411 !type.getQualifiers().hasObjCLifetime() && 8412 !type.getQualifiers().hasObjCGCAttr() && 8413 attr.getKind() != ParsedAttr::AT_ObjCGC && 8414 attr.getKind() != ParsedAttr::AT_ObjCOwnership) { 8415 const IdentifierInfo *MacroII = attr.getMacroIdentifier(); 8416 type = state.getSema().Context.getMacroQualifiedType(type, MacroII); 8417 state.setExpansionLocForMacroQualifiedType( 8418 cast<MacroQualifiedType>(type.getTypePtr()), 8419 attr.getMacroExpansionLoc()); 8420 } 8421 } 8422 } 8423 8424 void Sema::completeExprArrayBound(Expr *E) { 8425 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 8426 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 8427 if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) { 8428 auto *Def = Var->getDefinition(); 8429 if (!Def) { 8430 SourceLocation PointOfInstantiation = E->getExprLoc(); 8431 runWithSufficientStackSpace(PointOfInstantiation, [&] { 8432 InstantiateVariableDefinition(PointOfInstantiation, Var); 8433 }); 8434 Def = Var->getDefinition(); 8435 8436 // If we don't already have a point of instantiation, and we managed 8437 // to instantiate a definition, this is the point of instantiation. 8438 // Otherwise, we don't request an end-of-TU instantiation, so this is 8439 // not a point of instantiation. 8440 // FIXME: Is this really the right behavior? 8441 if (Var->getPointOfInstantiation().isInvalid() && Def) { 8442 assert(Var->getTemplateSpecializationKind() == 8443 TSK_ImplicitInstantiation && 8444 "explicit instantiation with no point of instantiation"); 8445 Var->setTemplateSpecializationKind( 8446 Var->getTemplateSpecializationKind(), PointOfInstantiation); 8447 } 8448 } 8449 8450 // Update the type to the definition's type both here and within the 8451 // expression. 8452 if (Def) { 8453 DRE->setDecl(Def); 8454 QualType T = Def->getType(); 8455 DRE->setType(T); 8456 // FIXME: Update the type on all intervening expressions. 8457 E->setType(T); 8458 } 8459 8460 // We still go on to try to complete the type independently, as it 8461 // may also require instantiations or diagnostics if it remains 8462 // incomplete. 8463 } 8464 } 8465 } 8466 } 8467 8468 QualType Sema::getCompletedType(Expr *E) { 8469 // Incomplete array types may be completed by the initializer attached to 8470 // their definitions. For static data members of class templates and for 8471 // variable templates, we need to instantiate the definition to get this 8472 // initializer and complete the type. 8473 if (E->getType()->isIncompleteArrayType()) 8474 completeExprArrayBound(E); 8475 8476 // FIXME: Are there other cases which require instantiating something other 8477 // than the type to complete the type of an expression? 8478 8479 return E->getType(); 8480 } 8481 8482 /// Ensure that the type of the given expression is complete. 8483 /// 8484 /// This routine checks whether the expression \p E has a complete type. If the 8485 /// expression refers to an instantiable construct, that instantiation is 8486 /// performed as needed to complete its type. Furthermore 8487 /// Sema::RequireCompleteType is called for the expression's type (or in the 8488 /// case of a reference type, the referred-to type). 8489 /// 8490 /// \param E The expression whose type is required to be complete. 8491 /// \param Kind Selects which completeness rules should be applied. 8492 /// \param Diagnoser The object that will emit a diagnostic if the type is 8493 /// incomplete. 8494 /// 8495 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false 8496 /// otherwise. 8497 bool Sema::RequireCompleteExprType(Expr *E, CompleteTypeKind Kind, 8498 TypeDiagnoser &Diagnoser) { 8499 return RequireCompleteType(E->getExprLoc(), getCompletedType(E), Kind, 8500 Diagnoser); 8501 } 8502 8503 bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) { 8504 BoundTypeDiagnoser<> Diagnoser(DiagID); 8505 return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser); 8506 } 8507 8508 /// Ensure that the type T is a complete type. 8509 /// 8510 /// This routine checks whether the type @p T is complete in any 8511 /// context where a complete type is required. If @p T is a complete 8512 /// type, returns false. If @p T is a class template specialization, 8513 /// this routine then attempts to perform class template 8514 /// instantiation. If instantiation fails, or if @p T is incomplete 8515 /// and cannot be completed, issues the diagnostic @p diag (giving it 8516 /// the type @p T) and returns true. 8517 /// 8518 /// @param Loc The location in the source that the incomplete type 8519 /// diagnostic should refer to. 8520 /// 8521 /// @param T The type that this routine is examining for completeness. 8522 /// 8523 /// @param Kind Selects which completeness rules should be applied. 8524 /// 8525 /// @returns @c true if @p T is incomplete and a diagnostic was emitted, 8526 /// @c false otherwise. 8527 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, 8528 CompleteTypeKind Kind, 8529 TypeDiagnoser &Diagnoser) { 8530 if (RequireCompleteTypeImpl(Loc, T, Kind, &Diagnoser)) 8531 return true; 8532 if (const TagType *Tag = T->getAs<TagType>()) { 8533 if (!Tag->getDecl()->isCompleteDefinitionRequired()) { 8534 Tag->getDecl()->setCompleteDefinitionRequired(); 8535 Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl()); 8536 } 8537 } 8538 return false; 8539 } 8540 8541 bool Sema::hasStructuralCompatLayout(Decl *D, Decl *Suggested) { 8542 llvm::DenseSet<std::pair<Decl *, Decl *>> NonEquivalentDecls; 8543 if (!Suggested) 8544 return false; 8545 8546 // FIXME: Add a specific mode for C11 6.2.7/1 in StructuralEquivalenceContext 8547 // and isolate from other C++ specific checks. 8548 StructuralEquivalenceContext Ctx( 8549 D->getASTContext(), Suggested->getASTContext(), NonEquivalentDecls, 8550 StructuralEquivalenceKind::Default, 8551 false /*StrictTypeSpelling*/, true /*Complain*/, 8552 true /*ErrorOnTagTypeMismatch*/); 8553 return Ctx.IsEquivalent(D, Suggested); 8554 } 8555 8556 /// Determine whether there is any declaration of \p D that was ever a 8557 /// definition (perhaps before module merging) and is currently visible. 8558 /// \param D The definition of the entity. 8559 /// \param Suggested Filled in with the declaration that should be made visible 8560 /// in order to provide a definition of this entity. 8561 /// \param OnlyNeedComplete If \c true, we only need the type to be complete, 8562 /// not defined. This only matters for enums with a fixed underlying 8563 /// type, since in all other cases, a type is complete if and only if it 8564 /// is defined. 8565 bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, 8566 bool OnlyNeedComplete) { 8567 // Easy case: if we don't have modules, all declarations are visible. 8568 if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility) 8569 return true; 8570 8571 // If this definition was instantiated from a template, map back to the 8572 // pattern from which it was instantiated. 8573 if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined()) { 8574 // We're in the middle of defining it; this definition should be treated 8575 // as visible. 8576 return true; 8577 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 8578 if (auto *Pattern = RD->getTemplateInstantiationPattern()) 8579 RD = Pattern; 8580 D = RD->getDefinition(); 8581 } else if (auto *ED = dyn_cast<EnumDecl>(D)) { 8582 if (auto *Pattern = ED->getTemplateInstantiationPattern()) 8583 ED = Pattern; 8584 if (OnlyNeedComplete && (ED->isFixed() || getLangOpts().MSVCCompat)) { 8585 // If the enum has a fixed underlying type, it may have been forward 8586 // declared. In -fms-compatibility, `enum Foo;` will also forward declare 8587 // the enum and assign it the underlying type of `int`. Since we're only 8588 // looking for a complete type (not a definition), any visible declaration 8589 // of it will do. 8590 *Suggested = nullptr; 8591 for (auto *Redecl : ED->redecls()) { 8592 if (isVisible(Redecl)) 8593 return true; 8594 if (Redecl->isThisDeclarationADefinition() || 8595 (Redecl->isCanonicalDecl() && !*Suggested)) 8596 *Suggested = Redecl; 8597 } 8598 return false; 8599 } 8600 D = ED->getDefinition(); 8601 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) { 8602 if (auto *Pattern = FD->getTemplateInstantiationPattern()) 8603 FD = Pattern; 8604 D = FD->getDefinition(); 8605 } else if (auto *VD = dyn_cast<VarDecl>(D)) { 8606 if (auto *Pattern = VD->getTemplateInstantiationPattern()) 8607 VD = Pattern; 8608 D = VD->getDefinition(); 8609 } 8610 assert(D && "missing definition for pattern of instantiated definition"); 8611 8612 *Suggested = D; 8613 8614 auto DefinitionIsVisible = [&] { 8615 // The (primary) definition might be in a visible module. 8616 if (isVisible(D)) 8617 return true; 8618 8619 // A visible module might have a merged definition instead. 8620 if (D->isModulePrivate() ? hasMergedDefinitionInCurrentModule(D) 8621 : hasVisibleMergedDefinition(D)) { 8622 if (CodeSynthesisContexts.empty() && 8623 !getLangOpts().ModulesLocalVisibility) { 8624 // Cache the fact that this definition is implicitly visible because 8625 // there is a visible merged definition. 8626 D->setVisibleDespiteOwningModule(); 8627 } 8628 return true; 8629 } 8630 8631 return false; 8632 }; 8633 8634 if (DefinitionIsVisible()) 8635 return true; 8636 8637 // The external source may have additional definitions of this entity that are 8638 // visible, so complete the redeclaration chain now and ask again. 8639 if (auto *Source = Context.getExternalSource()) { 8640 Source->CompleteRedeclChain(D); 8641 return DefinitionIsVisible(); 8642 } 8643 8644 return false; 8645 } 8646 8647 /// Locks in the inheritance model for the given class and all of its bases. 8648 static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) { 8649 RD = RD->getMostRecentNonInjectedDecl(); 8650 if (!RD->hasAttr<MSInheritanceAttr>()) { 8651 MSInheritanceModel IM; 8652 bool BestCase = false; 8653 switch (S.MSPointerToMemberRepresentationMethod) { 8654 case LangOptions::PPTMK_BestCase: 8655 BestCase = true; 8656 IM = RD->calculateInheritanceModel(); 8657 break; 8658 case LangOptions::PPTMK_FullGeneralitySingleInheritance: 8659 IM = MSInheritanceModel::Single; 8660 break; 8661 case LangOptions::PPTMK_FullGeneralityMultipleInheritance: 8662 IM = MSInheritanceModel::Multiple; 8663 break; 8664 case LangOptions::PPTMK_FullGeneralityVirtualInheritance: 8665 IM = MSInheritanceModel::Unspecified; 8666 break; 8667 } 8668 8669 SourceRange Loc = S.ImplicitMSInheritanceAttrLoc.isValid() 8670 ? S.ImplicitMSInheritanceAttrLoc 8671 : RD->getSourceRange(); 8672 RD->addAttr(MSInheritanceAttr::CreateImplicit( 8673 S.getASTContext(), BestCase, Loc, AttributeCommonInfo::AS_Microsoft, 8674 MSInheritanceAttr::Spelling(IM))); 8675 S.Consumer.AssignInheritanceModel(RD); 8676 } 8677 } 8678 8679 /// The implementation of RequireCompleteType 8680 bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T, 8681 CompleteTypeKind Kind, 8682 TypeDiagnoser *Diagnoser) { 8683 // FIXME: Add this assertion to make sure we always get instantiation points. 8684 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType"); 8685 // FIXME: Add this assertion to help us flush out problems with 8686 // checking for dependent types and type-dependent expressions. 8687 // 8688 // assert(!T->isDependentType() && 8689 // "Can't ask whether a dependent type is complete"); 8690 8691 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) { 8692 if (!MPTy->getClass()->isDependentType()) { 8693 if (getLangOpts().CompleteMemberPointers && 8694 !MPTy->getClass()->getAsCXXRecordDecl()->isBeingDefined() && 8695 RequireCompleteType(Loc, QualType(MPTy->getClass(), 0), Kind, 8696 diag::err_memptr_incomplete)) 8697 return true; 8698 8699 // We lock in the inheritance model once somebody has asked us to ensure 8700 // that a pointer-to-member type is complete. 8701 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 8702 (void)isCompleteType(Loc, QualType(MPTy->getClass(), 0)); 8703 assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl()); 8704 } 8705 } 8706 } 8707 8708 NamedDecl *Def = nullptr; 8709 bool AcceptSizeless = (Kind == CompleteTypeKind::AcceptSizeless); 8710 bool Incomplete = (T->isIncompleteType(&Def) || 8711 (!AcceptSizeless && T->isSizelessBuiltinType())); 8712 8713 // Check that any necessary explicit specializations are visible. For an 8714 // enum, we just need the declaration, so don't check this. 8715 if (Def && !isa<EnumDecl>(Def)) 8716 checkSpecializationVisibility(Loc, Def); 8717 8718 // If we have a complete type, we're done. 8719 if (!Incomplete) { 8720 // If we know about the definition but it is not visible, complain. 8721 NamedDecl *SuggestedDef = nullptr; 8722 if (Def && 8723 !hasVisibleDefinition(Def, &SuggestedDef, /*OnlyNeedComplete*/true)) { 8724 // If the user is going to see an error here, recover by making the 8725 // definition visible. 8726 bool TreatAsComplete = Diagnoser && !isSFINAEContext(); 8727 if (Diagnoser && SuggestedDef) 8728 diagnoseMissingImport(Loc, SuggestedDef, MissingImportKind::Definition, 8729 /*Recover*/TreatAsComplete); 8730 return !TreatAsComplete; 8731 } else if (Def && !TemplateInstCallbacks.empty()) { 8732 CodeSynthesisContext TempInst; 8733 TempInst.Kind = CodeSynthesisContext::Memoization; 8734 TempInst.Template = Def; 8735 TempInst.Entity = Def; 8736 TempInst.PointOfInstantiation = Loc; 8737 atTemplateBegin(TemplateInstCallbacks, *this, TempInst); 8738 atTemplateEnd(TemplateInstCallbacks, *this, TempInst); 8739 } 8740 8741 return false; 8742 } 8743 8744 TagDecl *Tag = dyn_cast_or_null<TagDecl>(Def); 8745 ObjCInterfaceDecl *IFace = dyn_cast_or_null<ObjCInterfaceDecl>(Def); 8746 8747 // Give the external source a chance to provide a definition of the type. 8748 // This is kept separate from completing the redeclaration chain so that 8749 // external sources such as LLDB can avoid synthesizing a type definition 8750 // unless it's actually needed. 8751 if (Tag || IFace) { 8752 // Avoid diagnosing invalid decls as incomplete. 8753 if (Def->isInvalidDecl()) 8754 return true; 8755 8756 // Give the external AST source a chance to complete the type. 8757 if (auto *Source = Context.getExternalSource()) { 8758 if (Tag && Tag->hasExternalLexicalStorage()) 8759 Source->CompleteType(Tag); 8760 if (IFace && IFace->hasExternalLexicalStorage()) 8761 Source->CompleteType(IFace); 8762 // If the external source completed the type, go through the motions 8763 // again to ensure we're allowed to use the completed type. 8764 if (!T->isIncompleteType()) 8765 return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser); 8766 } 8767 } 8768 8769 // If we have a class template specialization or a class member of a 8770 // class template specialization, or an array with known size of such, 8771 // try to instantiate it. 8772 if (auto *RD = dyn_cast_or_null<CXXRecordDecl>(Tag)) { 8773 bool Instantiated = false; 8774 bool Diagnosed = false; 8775 if (RD->isDependentContext()) { 8776 // Don't try to instantiate a dependent class (eg, a member template of 8777 // an instantiated class template specialization). 8778 // FIXME: Can this ever happen? 8779 } else if (auto *ClassTemplateSpec = 8780 dyn_cast<ClassTemplateSpecializationDecl>(RD)) { 8781 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) { 8782 runWithSufficientStackSpace(Loc, [&] { 8783 Diagnosed = InstantiateClassTemplateSpecialization( 8784 Loc, ClassTemplateSpec, TSK_ImplicitInstantiation, 8785 /*Complain=*/Diagnoser); 8786 }); 8787 Instantiated = true; 8788 } 8789 } else { 8790 CXXRecordDecl *Pattern = RD->getInstantiatedFromMemberClass(); 8791 if (!RD->isBeingDefined() && Pattern) { 8792 MemberSpecializationInfo *MSI = RD->getMemberSpecializationInfo(); 8793 assert(MSI && "Missing member specialization information?"); 8794 // This record was instantiated from a class within a template. 8795 if (MSI->getTemplateSpecializationKind() != 8796 TSK_ExplicitSpecialization) { 8797 runWithSufficientStackSpace(Loc, [&] { 8798 Diagnosed = InstantiateClass(Loc, RD, Pattern, 8799 getTemplateInstantiationArgs(RD), 8800 TSK_ImplicitInstantiation, 8801 /*Complain=*/Diagnoser); 8802 }); 8803 Instantiated = true; 8804 } 8805 } 8806 } 8807 8808 if (Instantiated) { 8809 // Instantiate* might have already complained that the template is not 8810 // defined, if we asked it to. 8811 if (Diagnoser && Diagnosed) 8812 return true; 8813 // If we instantiated a definition, check that it's usable, even if 8814 // instantiation produced an error, so that repeated calls to this 8815 // function give consistent answers. 8816 if (!T->isIncompleteType()) 8817 return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser); 8818 } 8819 } 8820 8821 // FIXME: If we didn't instantiate a definition because of an explicit 8822 // specialization declaration, check that it's visible. 8823 8824 if (!Diagnoser) 8825 return true; 8826 8827 Diagnoser->diagnose(*this, Loc, T); 8828 8829 // If the type was a forward declaration of a class/struct/union 8830 // type, produce a note. 8831 if (Tag && !Tag->isInvalidDecl() && !Tag->getLocation().isInvalid()) 8832 Diag(Tag->getLocation(), 8833 Tag->isBeingDefined() ? diag::note_type_being_defined 8834 : diag::note_forward_declaration) 8835 << Context.getTagDeclType(Tag); 8836 8837 // If the Objective-C class was a forward declaration, produce a note. 8838 if (IFace && !IFace->isInvalidDecl() && !IFace->getLocation().isInvalid()) 8839 Diag(IFace->getLocation(), diag::note_forward_class); 8840 8841 // If we have external information that we can use to suggest a fix, 8842 // produce a note. 8843 if (ExternalSource) 8844 ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T); 8845 8846 return true; 8847 } 8848 8849 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, 8850 CompleteTypeKind Kind, unsigned DiagID) { 8851 BoundTypeDiagnoser<> Diagnoser(DiagID); 8852 return RequireCompleteType(Loc, T, Kind, Diagnoser); 8853 } 8854 8855 /// Get diagnostic %select index for tag kind for 8856 /// literal type diagnostic message. 8857 /// WARNING: Indexes apply to particular diagnostics only! 8858 /// 8859 /// \returns diagnostic %select index. 8860 static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) { 8861 switch (Tag) { 8862 case TTK_Struct: return 0; 8863 case TTK_Interface: return 1; 8864 case TTK_Class: return 2; 8865 default: llvm_unreachable("Invalid tag kind for literal type diagnostic!"); 8866 } 8867 } 8868 8869 /// Ensure that the type T is a literal type. 8870 /// 8871 /// This routine checks whether the type @p T is a literal type. If @p T is an 8872 /// incomplete type, an attempt is made to complete it. If @p T is a literal 8873 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type, 8874 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving 8875 /// it the type @p T), along with notes explaining why the type is not a 8876 /// literal type, and returns true. 8877 /// 8878 /// @param Loc The location in the source that the non-literal type 8879 /// diagnostic should refer to. 8880 /// 8881 /// @param T The type that this routine is examining for literalness. 8882 /// 8883 /// @param Diagnoser Emits a diagnostic if T is not a literal type. 8884 /// 8885 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted, 8886 /// @c false otherwise. 8887 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, 8888 TypeDiagnoser &Diagnoser) { 8889 assert(!T->isDependentType() && "type should not be dependent"); 8890 8891 QualType ElemType = Context.getBaseElementType(T); 8892 if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) && 8893 T->isLiteralType(Context)) 8894 return false; 8895 8896 Diagnoser.diagnose(*this, Loc, T); 8897 8898 if (T->isVariableArrayType()) 8899 return true; 8900 8901 const RecordType *RT = ElemType->getAs<RecordType>(); 8902 if (!RT) 8903 return true; 8904 8905 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 8906 8907 // A partially-defined class type can't be a literal type, because a literal 8908 // class type must have a trivial destructor (which can't be checked until 8909 // the class definition is complete). 8910 if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T)) 8911 return true; 8912 8913 // [expr.prim.lambda]p3: 8914 // This class type is [not] a literal type. 8915 if (RD->isLambda() && !getLangOpts().CPlusPlus17) { 8916 Diag(RD->getLocation(), diag::note_non_literal_lambda); 8917 return true; 8918 } 8919 8920 // If the class has virtual base classes, then it's not an aggregate, and 8921 // cannot have any constexpr constructors or a trivial default constructor, 8922 // so is non-literal. This is better to diagnose than the resulting absence 8923 // of constexpr constructors. 8924 if (RD->getNumVBases()) { 8925 Diag(RD->getLocation(), diag::note_non_literal_virtual_base) 8926 << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 8927 for (const auto &I : RD->vbases()) 8928 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here) 8929 << I.getSourceRange(); 8930 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() && 8931 !RD->hasTrivialDefaultConstructor()) { 8932 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD; 8933 } else if (RD->hasNonLiteralTypeFieldsOrBases()) { 8934 for (const auto &I : RD->bases()) { 8935 if (!I.getType()->isLiteralType(Context)) { 8936 Diag(I.getBeginLoc(), diag::note_non_literal_base_class) 8937 << RD << I.getType() << I.getSourceRange(); 8938 return true; 8939 } 8940 } 8941 for (const auto *I : RD->fields()) { 8942 if (!I->getType()->isLiteralType(Context) || 8943 I->getType().isVolatileQualified()) { 8944 Diag(I->getLocation(), diag::note_non_literal_field) 8945 << RD << I << I->getType() 8946 << I->getType().isVolatileQualified(); 8947 return true; 8948 } 8949 } 8950 } else if (getLangOpts().CPlusPlus20 ? !RD->hasConstexprDestructor() 8951 : !RD->hasTrivialDestructor()) { 8952 // All fields and bases are of literal types, so have trivial or constexpr 8953 // destructors. If this class's destructor is non-trivial / non-constexpr, 8954 // it must be user-declared. 8955 CXXDestructorDecl *Dtor = RD->getDestructor(); 8956 assert(Dtor && "class has literal fields and bases but no dtor?"); 8957 if (!Dtor) 8958 return true; 8959 8960 if (getLangOpts().CPlusPlus20) { 8961 Diag(Dtor->getLocation(), diag::note_non_literal_non_constexpr_dtor) 8962 << RD; 8963 } else { 8964 Diag(Dtor->getLocation(), Dtor->isUserProvided() 8965 ? diag::note_non_literal_user_provided_dtor 8966 : diag::note_non_literal_nontrivial_dtor) 8967 << RD; 8968 if (!Dtor->isUserProvided()) 8969 SpecialMemberIsTrivial(Dtor, CXXDestructor, TAH_IgnoreTrivialABI, 8970 /*Diagnose*/ true); 8971 } 8972 } 8973 8974 return true; 8975 } 8976 8977 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) { 8978 BoundTypeDiagnoser<> Diagnoser(DiagID); 8979 return RequireLiteralType(Loc, T, Diagnoser); 8980 } 8981 8982 /// Retrieve a version of the type 'T' that is elaborated by Keyword, qualified 8983 /// by the nested-name-specifier contained in SS, and that is (re)declared by 8984 /// OwnedTagDecl, which is nullptr if this is not a (re)declaration. 8985 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword, 8986 const CXXScopeSpec &SS, QualType T, 8987 TagDecl *OwnedTagDecl) { 8988 if (T.isNull()) 8989 return T; 8990 NestedNameSpecifier *NNS; 8991 if (SS.isValid()) 8992 NNS = SS.getScopeRep(); 8993 else { 8994 if (Keyword == ETK_None) 8995 return T; 8996 NNS = nullptr; 8997 } 8998 return Context.getElaboratedType(Keyword, NNS, T, OwnedTagDecl); 8999 } 9000 9001 QualType Sema::BuildTypeofExprType(Expr *E) { 9002 assert(!E->hasPlaceholderType() && "unexpected placeholder"); 9003 9004 if (!getLangOpts().CPlusPlus && E->refersToBitField()) 9005 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 2; 9006 9007 if (!E->isTypeDependent()) { 9008 QualType T = E->getType(); 9009 if (const TagType *TT = T->getAs<TagType>()) 9010 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc()); 9011 } 9012 return Context.getTypeOfExprType(E); 9013 } 9014 9015 /// getDecltypeForExpr - Given an expr, will return the decltype for 9016 /// that expression, according to the rules in C++11 9017 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18. 9018 QualType Sema::getDecltypeForExpr(Expr *E) { 9019 if (E->isTypeDependent()) 9020 return Context.DependentTy; 9021 9022 Expr *IDExpr = E; 9023 if (auto *ImplCastExpr = dyn_cast<ImplicitCastExpr>(E)) 9024 IDExpr = ImplCastExpr->getSubExpr(); 9025 9026 // C++11 [dcl.type.simple]p4: 9027 // The type denoted by decltype(e) is defined as follows: 9028 9029 // C++20: 9030 // - if E is an unparenthesized id-expression naming a non-type 9031 // template-parameter (13.2), decltype(E) is the type of the 9032 // template-parameter after performing any necessary type deduction 9033 // Note that this does not pick up the implicit 'const' for a template 9034 // parameter object. This rule makes no difference before C++20 so we apply 9035 // it unconditionally. 9036 if (const auto *SNTTPE = dyn_cast<SubstNonTypeTemplateParmExpr>(IDExpr)) 9037 return SNTTPE->getParameterType(Context); 9038 9039 // - if e is an unparenthesized id-expression or an unparenthesized class 9040 // member access (5.2.5), decltype(e) is the type of the entity named 9041 // by e. If there is no such entity, or if e names a set of overloaded 9042 // functions, the program is ill-formed; 9043 // 9044 // We apply the same rules for Objective-C ivar and property references. 9045 if (const auto *DRE = dyn_cast<DeclRefExpr>(IDExpr)) { 9046 const ValueDecl *VD = DRE->getDecl(); 9047 QualType T = VD->getType(); 9048 return isa<TemplateParamObjectDecl>(VD) ? T.getUnqualifiedType() : T; 9049 } 9050 if (const auto *ME = dyn_cast<MemberExpr>(IDExpr)) { 9051 if (const auto *VD = ME->getMemberDecl()) 9052 if (isa<FieldDecl>(VD) || isa<VarDecl>(VD)) 9053 return VD->getType(); 9054 } else if (const auto *IR = dyn_cast<ObjCIvarRefExpr>(IDExpr)) { 9055 return IR->getDecl()->getType(); 9056 } else if (const auto *PR = dyn_cast<ObjCPropertyRefExpr>(IDExpr)) { 9057 if (PR->isExplicitProperty()) 9058 return PR->getExplicitProperty()->getType(); 9059 } else if (const auto *PE = dyn_cast<PredefinedExpr>(IDExpr)) { 9060 return PE->getType(); 9061 } 9062 9063 // C++11 [expr.lambda.prim]p18: 9064 // Every occurrence of decltype((x)) where x is a possibly 9065 // parenthesized id-expression that names an entity of automatic 9066 // storage duration is treated as if x were transformed into an 9067 // access to a corresponding data member of the closure type that 9068 // would have been declared if x were an odr-use of the denoted 9069 // entity. 9070 if (getCurLambda() && isa<ParenExpr>(IDExpr)) { 9071 if (auto *DRE = dyn_cast<DeclRefExpr>(IDExpr->IgnoreParens())) { 9072 if (auto *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 9073 QualType T = getCapturedDeclRefType(Var, DRE->getLocation()); 9074 if (!T.isNull()) 9075 return Context.getLValueReferenceType(T); 9076 } 9077 } 9078 } 9079 9080 return Context.getReferenceQualifiedType(E); 9081 } 9082 9083 QualType Sema::BuildDecltypeType(Expr *E, bool AsUnevaluated) { 9084 assert(!E->hasPlaceholderType() && "unexpected placeholder"); 9085 9086 if (AsUnevaluated && CodeSynthesisContexts.empty() && 9087 !E->isInstantiationDependent() && E->HasSideEffects(Context, false)) { 9088 // The expression operand for decltype is in an unevaluated expression 9089 // context, so side effects could result in unintended consequences. 9090 // Exclude instantiation-dependent expressions, because 'decltype' is often 9091 // used to build SFINAE gadgets. 9092 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 9093 } 9094 return Context.getDecltypeType(E, getDecltypeForExpr(E)); 9095 } 9096 9097 QualType Sema::BuildUnaryTransformType(QualType BaseType, 9098 UnaryTransformType::UTTKind UKind, 9099 SourceLocation Loc) { 9100 switch (UKind) { 9101 case UnaryTransformType::EnumUnderlyingType: 9102 if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) { 9103 Diag(Loc, diag::err_only_enums_have_underlying_types); 9104 return QualType(); 9105 } else { 9106 QualType Underlying = BaseType; 9107 if (!BaseType->isDependentType()) { 9108 // The enum could be incomplete if we're parsing its definition or 9109 // recovering from an error. 9110 NamedDecl *FwdDecl = nullptr; 9111 if (BaseType->isIncompleteType(&FwdDecl)) { 9112 Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType; 9113 Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl; 9114 return QualType(); 9115 } 9116 9117 EnumDecl *ED = BaseType->castAs<EnumType>()->getDecl(); 9118 assert(ED && "EnumType has no EnumDecl"); 9119 9120 DiagnoseUseOfDecl(ED, Loc); 9121 9122 Underlying = ED->getIntegerType(); 9123 assert(!Underlying.isNull()); 9124 } 9125 return Context.getUnaryTransformType(BaseType, Underlying, 9126 UnaryTransformType::EnumUnderlyingType); 9127 } 9128 } 9129 llvm_unreachable("unknown unary transform type"); 9130 } 9131 9132 QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) { 9133 if (!isDependentOrGNUAutoType(T)) { 9134 // FIXME: It isn't entirely clear whether incomplete atomic types 9135 // are allowed or not; for simplicity, ban them for the moment. 9136 if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0)) 9137 return QualType(); 9138 9139 int DisallowedKind = -1; 9140 if (T->isArrayType()) 9141 DisallowedKind = 1; 9142 else if (T->isFunctionType()) 9143 DisallowedKind = 2; 9144 else if (T->isReferenceType()) 9145 DisallowedKind = 3; 9146 else if (T->isAtomicType()) 9147 DisallowedKind = 4; 9148 else if (T.hasQualifiers()) 9149 DisallowedKind = 5; 9150 else if (T->isSizelessType()) 9151 DisallowedKind = 6; 9152 else if (!T.isTriviallyCopyableType(Context)) 9153 // Some other non-trivially-copyable type (probably a C++ class) 9154 DisallowedKind = 7; 9155 else if (T->isBitIntType()) 9156 DisallowedKind = 8; 9157 9158 if (DisallowedKind != -1) { 9159 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T; 9160 return QualType(); 9161 } 9162 9163 // FIXME: Do we need any handling for ARC here? 9164 } 9165 9166 // Build the pointer type. 9167 return Context.getAtomicType(T); 9168 } 9169