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 // WG14 DR 423 updated 6.7.6.3p4 to have the function declarator drop 5186 // all qualifiers from the return type. 5187 diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex); 5188 if (!S.getLangOpts().CPlusPlus) 5189 T = T.getAtomicUnqualifiedType(); 5190 5191 // C++2a [dcl.fct]p12: 5192 // A volatile-qualified return type is deprecated 5193 if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20) 5194 S.Diag(DeclType.Loc, diag::warn_deprecated_volatile_return) << T; 5195 } 5196 5197 // Objective-C ARC ownership qualifiers are ignored on the function 5198 // return type (by type canonicalization). Complain if this attribute 5199 // was written here. 5200 if (T.getQualifiers().hasObjCLifetime()) { 5201 SourceLocation AttrLoc; 5202 if (chunkIndex + 1 < D.getNumTypeObjects()) { 5203 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1); 5204 for (const ParsedAttr &AL : ReturnTypeChunk.getAttrs()) { 5205 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) { 5206 AttrLoc = AL.getLoc(); 5207 break; 5208 } 5209 } 5210 } 5211 if (AttrLoc.isInvalid()) { 5212 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) { 5213 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) { 5214 AttrLoc = AL.getLoc(); 5215 break; 5216 } 5217 } 5218 } 5219 5220 if (AttrLoc.isValid()) { 5221 // The ownership attributes are almost always written via 5222 // the predefined 5223 // __strong/__weak/__autoreleasing/__unsafe_unretained. 5224 if (AttrLoc.isMacroID()) 5225 AttrLoc = 5226 S.SourceMgr.getImmediateExpansionRange(AttrLoc).getBegin(); 5227 5228 S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type) 5229 << T.getQualifiers().getObjCLifetime(); 5230 } 5231 } 5232 5233 if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) { 5234 // C++ [dcl.fct]p6: 5235 // Types shall not be defined in return or parameter types. 5236 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 5237 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type) 5238 << Context.getTypeDeclType(Tag); 5239 } 5240 5241 // Exception specs are not allowed in typedefs. Complain, but add it 5242 // anyway. 5243 if (IsTypedefName && FTI.getExceptionSpecType() && !LangOpts.CPlusPlus17) 5244 S.Diag(FTI.getExceptionSpecLocBeg(), 5245 diag::err_exception_spec_in_typedef) 5246 << (D.getContext() == DeclaratorContext::AliasDecl || 5247 D.getContext() == DeclaratorContext::AliasTemplate); 5248 5249 // If we see "T var();" or "T var(T());" at block scope, it is probably 5250 // an attempt to initialize a variable, not a function declaration. 5251 if (FTI.isAmbiguous) 5252 warnAboutAmbiguousFunction(S, D, DeclType, T); 5253 5254 FunctionType::ExtInfo EI( 5255 getCCForDeclaratorChunk(S, D, DeclType.getAttrs(), FTI, chunkIndex)); 5256 5257 // OpenCL disallows functions without a prototype, but it doesn't enforce 5258 // strict prototypes as in C2x because it allows a function definition to 5259 // have an identifier list. See OpenCL 3.0 6.11/g for more details. 5260 if (!FTI.NumParams && !FTI.isVariadic && 5261 !LangOpts.requiresStrictPrototypes() && !LangOpts.OpenCL) { 5262 // Simple void foo(), where the incoming T is the result type. 5263 T = Context.getFunctionNoProtoType(T, EI); 5264 } else { 5265 // We allow a zero-parameter variadic function in C if the 5266 // function is marked with the "overloadable" attribute. Scan 5267 // for this attribute now. 5268 if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) 5269 if (!D.getAttributes().hasAttribute(ParsedAttr::AT_Overloadable) && 5270 !D.getDeclSpec().getAttributes().hasAttribute( 5271 ParsedAttr::AT_Overloadable)) 5272 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param); 5273 5274 if (FTI.NumParams && FTI.Params[0].Param == nullptr) { 5275 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function 5276 // definition. 5277 S.Diag(FTI.Params[0].IdentLoc, 5278 diag::err_ident_list_in_fn_declaration); 5279 D.setInvalidType(true); 5280 // Recover by creating a K&R-style function type, if possible. 5281 T = (!LangOpts.requiresStrictPrototypes() && !LangOpts.OpenCL) 5282 ? Context.getFunctionNoProtoType(T, EI) 5283 : Context.IntTy; 5284 break; 5285 } 5286 5287 FunctionProtoType::ExtProtoInfo EPI; 5288 EPI.ExtInfo = EI; 5289 EPI.Variadic = FTI.isVariadic; 5290 EPI.EllipsisLoc = FTI.getEllipsisLoc(); 5291 EPI.HasTrailingReturn = FTI.hasTrailingReturnType(); 5292 EPI.TypeQuals.addCVRUQualifiers( 5293 FTI.MethodQualifiers ? FTI.MethodQualifiers->getTypeQualifiers() 5294 : 0); 5295 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None 5296 : FTI.RefQualifierIsLValueRef? RQ_LValue 5297 : RQ_RValue; 5298 5299 // Otherwise, we have a function with a parameter list that is 5300 // potentially variadic. 5301 SmallVector<QualType, 16> ParamTys; 5302 ParamTys.reserve(FTI.NumParams); 5303 5304 SmallVector<FunctionProtoType::ExtParameterInfo, 16> 5305 ExtParameterInfos(FTI.NumParams); 5306 bool HasAnyInterestingExtParameterInfos = false; 5307 5308 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 5309 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 5310 QualType ParamTy = Param->getType(); 5311 assert(!ParamTy.isNull() && "Couldn't parse type?"); 5312 5313 // Look for 'void'. void is allowed only as a single parameter to a 5314 // function with no other parameters (C99 6.7.5.3p10). We record 5315 // int(void) as a FunctionProtoType with an empty parameter list. 5316 if (ParamTy->isVoidType()) { 5317 // If this is something like 'float(int, void)', reject it. 'void' 5318 // is an incomplete type (C99 6.2.5p19) and function decls cannot 5319 // have parameters of incomplete type. 5320 if (FTI.NumParams != 1 || FTI.isVariadic) { 5321 S.Diag(FTI.Params[i].IdentLoc, diag::err_void_only_param); 5322 ParamTy = Context.IntTy; 5323 Param->setType(ParamTy); 5324 } else if (FTI.Params[i].Ident) { 5325 // Reject, but continue to parse 'int(void abc)'. 5326 S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type); 5327 ParamTy = Context.IntTy; 5328 Param->setType(ParamTy); 5329 } else { 5330 // Reject, but continue to parse 'float(const void)'. 5331 if (ParamTy.hasQualifiers()) 5332 S.Diag(DeclType.Loc, diag::err_void_param_qualified); 5333 5334 // Do not add 'void' to the list. 5335 break; 5336 } 5337 } else if (ParamTy->isHalfType()) { 5338 // Disallow half FP parameters. 5339 // FIXME: This really should be in BuildFunctionType. 5340 if (S.getLangOpts().OpenCL) { 5341 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", 5342 S.getLangOpts())) { 5343 S.Diag(Param->getLocation(), diag::err_opencl_invalid_param) 5344 << ParamTy << 0; 5345 D.setInvalidType(); 5346 Param->setInvalidDecl(); 5347 } 5348 } else if (!S.getLangOpts().HalfArgsAndReturns) { 5349 S.Diag(Param->getLocation(), 5350 diag::err_parameters_retval_cannot_have_fp16_type) << 0; 5351 D.setInvalidType(); 5352 } 5353 } else if (!FTI.hasPrototype) { 5354 if (ParamTy->isPromotableIntegerType()) { 5355 ParamTy = Context.getPromotedIntegerType(ParamTy); 5356 Param->setKNRPromoted(true); 5357 } else if (const BuiltinType* BTy = ParamTy->getAs<BuiltinType>()) { 5358 if (BTy->getKind() == BuiltinType::Float) { 5359 ParamTy = Context.DoubleTy; 5360 Param->setKNRPromoted(true); 5361 } 5362 } 5363 } else if (S.getLangOpts().OpenCL && ParamTy->isBlockPointerType()) { 5364 // OpenCL 2.0 s6.12.5: A block cannot be a parameter of a function. 5365 S.Diag(Param->getLocation(), diag::err_opencl_invalid_param) 5366 << ParamTy << 1 /*hint off*/; 5367 D.setInvalidType(); 5368 } 5369 5370 if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) { 5371 ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(true); 5372 HasAnyInterestingExtParameterInfos = true; 5373 } 5374 5375 if (auto attr = Param->getAttr<ParameterABIAttr>()) { 5376 ExtParameterInfos[i] = 5377 ExtParameterInfos[i].withABI(attr->getABI()); 5378 HasAnyInterestingExtParameterInfos = true; 5379 } 5380 5381 if (Param->hasAttr<PassObjectSizeAttr>()) { 5382 ExtParameterInfos[i] = ExtParameterInfos[i].withHasPassObjectSize(); 5383 HasAnyInterestingExtParameterInfos = true; 5384 } 5385 5386 if (Param->hasAttr<NoEscapeAttr>()) { 5387 ExtParameterInfos[i] = ExtParameterInfos[i].withIsNoEscape(true); 5388 HasAnyInterestingExtParameterInfos = true; 5389 } 5390 5391 ParamTys.push_back(ParamTy); 5392 } 5393 5394 if (HasAnyInterestingExtParameterInfos) { 5395 EPI.ExtParameterInfos = ExtParameterInfos.data(); 5396 checkExtParameterInfos(S, ParamTys, EPI, 5397 [&](unsigned i) { return FTI.Params[i].Param->getLocation(); }); 5398 } 5399 5400 SmallVector<QualType, 4> Exceptions; 5401 SmallVector<ParsedType, 2> DynamicExceptions; 5402 SmallVector<SourceRange, 2> DynamicExceptionRanges; 5403 Expr *NoexceptExpr = nullptr; 5404 5405 if (FTI.getExceptionSpecType() == EST_Dynamic) { 5406 // FIXME: It's rather inefficient to have to split into two vectors 5407 // here. 5408 unsigned N = FTI.getNumExceptions(); 5409 DynamicExceptions.reserve(N); 5410 DynamicExceptionRanges.reserve(N); 5411 for (unsigned I = 0; I != N; ++I) { 5412 DynamicExceptions.push_back(FTI.Exceptions[I].Ty); 5413 DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range); 5414 } 5415 } else if (isComputedNoexcept(FTI.getExceptionSpecType())) { 5416 NoexceptExpr = FTI.NoexceptExpr; 5417 } 5418 5419 S.checkExceptionSpecification(D.isFunctionDeclarationContext(), 5420 FTI.getExceptionSpecType(), 5421 DynamicExceptions, 5422 DynamicExceptionRanges, 5423 NoexceptExpr, 5424 Exceptions, 5425 EPI.ExceptionSpec); 5426 5427 // FIXME: Set address space from attrs for C++ mode here. 5428 // OpenCLCPlusPlus: A class member function has an address space. 5429 auto IsClassMember = [&]() { 5430 return (!state.getDeclarator().getCXXScopeSpec().isEmpty() && 5431 state.getDeclarator() 5432 .getCXXScopeSpec() 5433 .getScopeRep() 5434 ->getKind() == NestedNameSpecifier::TypeSpec) || 5435 state.getDeclarator().getContext() == 5436 DeclaratorContext::Member || 5437 state.getDeclarator().getContext() == 5438 DeclaratorContext::LambdaExpr; 5439 }; 5440 5441 if (state.getSema().getLangOpts().OpenCLCPlusPlus && IsClassMember()) { 5442 LangAS ASIdx = LangAS::Default; 5443 // Take address space attr if any and mark as invalid to avoid adding 5444 // them later while creating QualType. 5445 if (FTI.MethodQualifiers) 5446 for (ParsedAttr &attr : FTI.MethodQualifiers->getAttributes()) { 5447 LangAS ASIdxNew = attr.asOpenCLLangAS(); 5448 if (DiagnoseMultipleAddrSpaceAttributes(S, ASIdx, ASIdxNew, 5449 attr.getLoc())) 5450 D.setInvalidType(true); 5451 else 5452 ASIdx = ASIdxNew; 5453 } 5454 // If a class member function's address space is not set, set it to 5455 // __generic. 5456 LangAS AS = 5457 (ASIdx == LangAS::Default ? S.getDefaultCXXMethodAddrSpace() 5458 : ASIdx); 5459 EPI.TypeQuals.addAddressSpace(AS); 5460 } 5461 T = Context.getFunctionType(T, ParamTys, EPI); 5462 } 5463 break; 5464 } 5465 case DeclaratorChunk::MemberPointer: { 5466 // The scope spec must refer to a class, or be dependent. 5467 CXXScopeSpec &SS = DeclType.Mem.Scope(); 5468 QualType ClsType; 5469 5470 // Handle pointer nullability. 5471 inferPointerNullability(SimplePointerKind::MemberPointer, DeclType.Loc, 5472 DeclType.EndLoc, DeclType.getAttrs(), 5473 state.getDeclarator().getAttributePool()); 5474 5475 if (SS.isInvalid()) { 5476 // Avoid emitting extra errors if we already errored on the scope. 5477 D.setInvalidType(true); 5478 } else if (S.isDependentScopeSpecifier(SS) || 5479 isa_and_nonnull<CXXRecordDecl>(S.computeDeclContext(SS))) { 5480 NestedNameSpecifier *NNS = SS.getScopeRep(); 5481 NestedNameSpecifier *NNSPrefix = NNS->getPrefix(); 5482 switch (NNS->getKind()) { 5483 case NestedNameSpecifier::Identifier: 5484 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix, 5485 NNS->getAsIdentifier()); 5486 break; 5487 5488 case NestedNameSpecifier::Namespace: 5489 case NestedNameSpecifier::NamespaceAlias: 5490 case NestedNameSpecifier::Global: 5491 case NestedNameSpecifier::Super: 5492 llvm_unreachable("Nested-name-specifier must name a type"); 5493 5494 case NestedNameSpecifier::TypeSpec: 5495 case NestedNameSpecifier::TypeSpecWithTemplate: 5496 ClsType = QualType(NNS->getAsType(), 0); 5497 // Note: if the NNS has a prefix and ClsType is a nondependent 5498 // TemplateSpecializationType, then the NNS prefix is NOT included 5499 // in ClsType; hence we wrap ClsType into an ElaboratedType. 5500 // NOTE: in particular, no wrap occurs if ClsType already is an 5501 // Elaborated, DependentName, or DependentTemplateSpecialization. 5502 if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType())) 5503 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType); 5504 break; 5505 } 5506 } else { 5507 S.Diag(DeclType.Mem.Scope().getBeginLoc(), 5508 diag::err_illegal_decl_mempointer_in_nonclass) 5509 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name") 5510 << DeclType.Mem.Scope().getRange(); 5511 D.setInvalidType(true); 5512 } 5513 5514 if (!ClsType.isNull()) 5515 T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc, 5516 D.getIdentifier()); 5517 if (T.isNull()) { 5518 T = Context.IntTy; 5519 D.setInvalidType(true); 5520 } else if (DeclType.Mem.TypeQuals) { 5521 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals); 5522 } 5523 break; 5524 } 5525 5526 case DeclaratorChunk::Pipe: { 5527 T = S.BuildReadPipeType(T, DeclType.Loc); 5528 processTypeAttrs(state, T, TAL_DeclSpec, 5529 D.getMutableDeclSpec().getAttributes()); 5530 break; 5531 } 5532 } 5533 5534 if (T.isNull()) { 5535 D.setInvalidType(true); 5536 T = Context.IntTy; 5537 } 5538 5539 // See if there are any attributes on this declarator chunk. 5540 processTypeAttrs(state, T, TAL_DeclChunk, DeclType.getAttrs()); 5541 5542 if (DeclType.Kind != DeclaratorChunk::Paren) { 5543 if (ExpectNoDerefChunk && !IsNoDerefableChunk(DeclType)) 5544 S.Diag(DeclType.Loc, diag::warn_noderef_on_non_pointer_or_array); 5545 5546 ExpectNoDerefChunk = state.didParseNoDeref(); 5547 } 5548 } 5549 5550 if (ExpectNoDerefChunk) 5551 S.Diag(state.getDeclarator().getBeginLoc(), 5552 diag::warn_noderef_on_non_pointer_or_array); 5553 5554 // GNU warning -Wstrict-prototypes 5555 // Warn if a function declaration or definition is without a prototype. 5556 // This warning is issued for all kinds of unprototyped function 5557 // declarations (i.e. function type typedef, function pointer etc.) 5558 // C99 6.7.5.3p14: 5559 // The empty list in a function declarator that is not part of a definition 5560 // of that function specifies that no information about the number or types 5561 // of the parameters is supplied. 5562 // See ActOnFinishFunctionBody() and MergeFunctionDecl() for handling of 5563 // function declarations whose behavior changes in C2x. 5564 if (!LangOpts.requiresStrictPrototypes()) { 5565 bool IsBlock = false; 5566 for (const DeclaratorChunk &DeclType : D.type_objects()) { 5567 switch (DeclType.Kind) { 5568 case DeclaratorChunk::BlockPointer: 5569 IsBlock = true; 5570 break; 5571 case DeclaratorChunk::Function: { 5572 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 5573 // We suppress the warning when there's no LParen location, as this 5574 // indicates the declaration was an implicit declaration, which gets 5575 // warned about separately via -Wimplicit-function-declaration. We also 5576 // suppress the warning when we know the function has a prototype. 5577 if (!FTI.hasPrototype && FTI.NumParams == 0 && !FTI.isVariadic && 5578 FTI.getLParenLoc().isValid()) 5579 S.Diag(DeclType.Loc, diag::warn_strict_prototypes) 5580 << IsBlock 5581 << FixItHint::CreateInsertion(FTI.getRParenLoc(), "void"); 5582 IsBlock = false; 5583 break; 5584 } 5585 default: 5586 break; 5587 } 5588 } 5589 } 5590 5591 assert(!T.isNull() && "T must not be null after this point"); 5592 5593 if (LangOpts.CPlusPlus && T->isFunctionType()) { 5594 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>(); 5595 assert(FnTy && "Why oh why is there not a FunctionProtoType here?"); 5596 5597 // C++ 8.3.5p4: 5598 // A cv-qualifier-seq shall only be part of the function type 5599 // for a nonstatic member function, the function type to which a pointer 5600 // to member refers, or the top-level function type of a function typedef 5601 // declaration. 5602 // 5603 // Core issue 547 also allows cv-qualifiers on function types that are 5604 // top-level template type arguments. 5605 enum { NonMember, Member, DeductionGuide } Kind = NonMember; 5606 if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName) 5607 Kind = DeductionGuide; 5608 else if (!D.getCXXScopeSpec().isSet()) { 5609 if ((D.getContext() == DeclaratorContext::Member || 5610 D.getContext() == DeclaratorContext::LambdaExpr) && 5611 !D.getDeclSpec().isFriendSpecified()) 5612 Kind = Member; 5613 } else { 5614 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec()); 5615 if (!DC || DC->isRecord()) 5616 Kind = Member; 5617 } 5618 5619 // C++11 [dcl.fct]p6 (w/DR1417): 5620 // An attempt to specify a function type with a cv-qualifier-seq or a 5621 // ref-qualifier (including by typedef-name) is ill-formed unless it is: 5622 // - the function type for a non-static member function, 5623 // - the function type to which a pointer to member refers, 5624 // - the top-level function type of a function typedef declaration or 5625 // alias-declaration, 5626 // - the type-id in the default argument of a type-parameter, or 5627 // - the type-id of a template-argument for a type-parameter 5628 // 5629 // FIXME: Checking this here is insufficient. We accept-invalid on: 5630 // 5631 // template<typename T> struct S { void f(T); }; 5632 // S<int() const> s; 5633 // 5634 // ... for instance. 5635 if (IsQualifiedFunction && 5636 !(Kind == Member && 5637 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) && 5638 !IsTypedefName && D.getContext() != DeclaratorContext::TemplateArg && 5639 D.getContext() != DeclaratorContext::TemplateTypeArg) { 5640 SourceLocation Loc = D.getBeginLoc(); 5641 SourceRange RemovalRange; 5642 unsigned I; 5643 if (D.isFunctionDeclarator(I)) { 5644 SmallVector<SourceLocation, 4> RemovalLocs; 5645 const DeclaratorChunk &Chunk = D.getTypeObject(I); 5646 assert(Chunk.Kind == DeclaratorChunk::Function); 5647 5648 if (Chunk.Fun.hasRefQualifier()) 5649 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc()); 5650 5651 if (Chunk.Fun.hasMethodTypeQualifiers()) 5652 Chunk.Fun.MethodQualifiers->forEachQualifier( 5653 [&](DeclSpec::TQ TypeQual, StringRef QualName, 5654 SourceLocation SL) { RemovalLocs.push_back(SL); }); 5655 5656 if (!RemovalLocs.empty()) { 5657 llvm::sort(RemovalLocs, 5658 BeforeThanCompare<SourceLocation>(S.getSourceManager())); 5659 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back()); 5660 Loc = RemovalLocs.front(); 5661 } 5662 } 5663 5664 S.Diag(Loc, diag::err_invalid_qualified_function_type) 5665 << Kind << D.isFunctionDeclarator() << T 5666 << getFunctionQualifiersAsString(FnTy) 5667 << FixItHint::CreateRemoval(RemovalRange); 5668 5669 // Strip the cv-qualifiers and ref-qualifiers from the type. 5670 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo(); 5671 EPI.TypeQuals.removeCVRQualifiers(); 5672 EPI.RefQualifier = RQ_None; 5673 5674 T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(), 5675 EPI); 5676 // Rebuild any parens around the identifier in the function type. 5677 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 5678 if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren) 5679 break; 5680 T = S.BuildParenType(T); 5681 } 5682 } 5683 } 5684 5685 // Apply any undistributed attributes from the declarator. 5686 processTypeAttrs(state, T, TAL_DeclName, D.getAttributes()); 5687 5688 // Diagnose any ignored type attributes. 5689 state.diagnoseIgnoredTypeAttrs(T); 5690 5691 // C++0x [dcl.constexpr]p9: 5692 // A constexpr specifier used in an object declaration declares the object 5693 // as const. 5694 if (D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Constexpr && 5695 T->isObjectType()) 5696 T.addConst(); 5697 5698 // C++2a [dcl.fct]p4: 5699 // A parameter with volatile-qualified type is deprecated 5700 if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20 && 5701 (D.getContext() == DeclaratorContext::Prototype || 5702 D.getContext() == DeclaratorContext::LambdaExprParameter)) 5703 S.Diag(D.getIdentifierLoc(), diag::warn_deprecated_volatile_param) << T; 5704 5705 // If there was an ellipsis in the declarator, the declaration declares a 5706 // parameter pack whose type may be a pack expansion type. 5707 if (D.hasEllipsis()) { 5708 // C++0x [dcl.fct]p13: 5709 // A declarator-id or abstract-declarator containing an ellipsis shall 5710 // only be used in a parameter-declaration. Such a parameter-declaration 5711 // is a parameter pack (14.5.3). [...] 5712 switch (D.getContext()) { 5713 case DeclaratorContext::Prototype: 5714 case DeclaratorContext::LambdaExprParameter: 5715 case DeclaratorContext::RequiresExpr: 5716 // C++0x [dcl.fct]p13: 5717 // [...] When it is part of a parameter-declaration-clause, the 5718 // parameter pack is a function parameter pack (14.5.3). The type T 5719 // of the declarator-id of the function parameter pack shall contain 5720 // a template parameter pack; each template parameter pack in T is 5721 // expanded by the function parameter pack. 5722 // 5723 // We represent function parameter packs as function parameters whose 5724 // type is a pack expansion. 5725 if (!T->containsUnexpandedParameterPack() && 5726 (!LangOpts.CPlusPlus20 || !T->getContainedAutoType())) { 5727 S.Diag(D.getEllipsisLoc(), 5728 diag::err_function_parameter_pack_without_parameter_packs) 5729 << T << D.getSourceRange(); 5730 D.setEllipsisLoc(SourceLocation()); 5731 } else { 5732 T = Context.getPackExpansionType(T, None, /*ExpectPackInType=*/false); 5733 } 5734 break; 5735 case DeclaratorContext::TemplateParam: 5736 // C++0x [temp.param]p15: 5737 // If a template-parameter is a [...] is a parameter-declaration that 5738 // declares a parameter pack (8.3.5), then the template-parameter is a 5739 // template parameter pack (14.5.3). 5740 // 5741 // Note: core issue 778 clarifies that, if there are any unexpanded 5742 // parameter packs in the type of the non-type template parameter, then 5743 // it expands those parameter packs. 5744 if (T->containsUnexpandedParameterPack()) 5745 T = Context.getPackExpansionType(T, None); 5746 else 5747 S.Diag(D.getEllipsisLoc(), 5748 LangOpts.CPlusPlus11 5749 ? diag::warn_cxx98_compat_variadic_templates 5750 : diag::ext_variadic_templates); 5751 break; 5752 5753 case DeclaratorContext::File: 5754 case DeclaratorContext::KNRTypeList: 5755 case DeclaratorContext::ObjCParameter: // FIXME: special diagnostic here? 5756 case DeclaratorContext::ObjCResult: // FIXME: special diagnostic here? 5757 case DeclaratorContext::TypeName: 5758 case DeclaratorContext::FunctionalCast: 5759 case DeclaratorContext::CXXNew: 5760 case DeclaratorContext::AliasDecl: 5761 case DeclaratorContext::AliasTemplate: 5762 case DeclaratorContext::Member: 5763 case DeclaratorContext::Block: 5764 case DeclaratorContext::ForInit: 5765 case DeclaratorContext::SelectionInit: 5766 case DeclaratorContext::Condition: 5767 case DeclaratorContext::CXXCatch: 5768 case DeclaratorContext::ObjCCatch: 5769 case DeclaratorContext::BlockLiteral: 5770 case DeclaratorContext::LambdaExpr: 5771 case DeclaratorContext::ConversionId: 5772 case DeclaratorContext::TrailingReturn: 5773 case DeclaratorContext::TrailingReturnVar: 5774 case DeclaratorContext::TemplateArg: 5775 case DeclaratorContext::TemplateTypeArg: 5776 // FIXME: We may want to allow parameter packs in block-literal contexts 5777 // in the future. 5778 S.Diag(D.getEllipsisLoc(), 5779 diag::err_ellipsis_in_declarator_not_parameter); 5780 D.setEllipsisLoc(SourceLocation()); 5781 break; 5782 } 5783 } 5784 5785 assert(!T.isNull() && "T must not be null at the end of this function"); 5786 if (D.isInvalidType()) 5787 return Context.getTrivialTypeSourceInfo(T); 5788 5789 return GetTypeSourceInfoForDeclarator(state, T, TInfo); 5790 } 5791 5792 /// GetTypeForDeclarator - Convert the type for the specified 5793 /// declarator to Type instances. 5794 /// 5795 /// The result of this call will never be null, but the associated 5796 /// type may be a null type if there's an unrecoverable error. 5797 TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) { 5798 // Determine the type of the declarator. Not all forms of declarator 5799 // have a type. 5800 5801 TypeProcessingState state(*this, D); 5802 5803 TypeSourceInfo *ReturnTypeInfo = nullptr; 5804 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); 5805 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount) 5806 inferARCWriteback(state, T); 5807 5808 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo); 5809 } 5810 5811 static void transferARCOwnershipToDeclSpec(Sema &S, 5812 QualType &declSpecTy, 5813 Qualifiers::ObjCLifetime ownership) { 5814 if (declSpecTy->isObjCRetainableType() && 5815 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) { 5816 Qualifiers qs; 5817 qs.addObjCLifetime(ownership); 5818 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs); 5819 } 5820 } 5821 5822 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, 5823 Qualifiers::ObjCLifetime ownership, 5824 unsigned chunkIndex) { 5825 Sema &S = state.getSema(); 5826 Declarator &D = state.getDeclarator(); 5827 5828 // Look for an explicit lifetime attribute. 5829 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex); 5830 if (chunk.getAttrs().hasAttribute(ParsedAttr::AT_ObjCOwnership)) 5831 return; 5832 5833 const char *attrStr = nullptr; 5834 switch (ownership) { 5835 case Qualifiers::OCL_None: llvm_unreachable("no ownership!"); 5836 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break; 5837 case Qualifiers::OCL_Strong: attrStr = "strong"; break; 5838 case Qualifiers::OCL_Weak: attrStr = "weak"; break; 5839 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break; 5840 } 5841 5842 IdentifierLoc *Arg = new (S.Context) IdentifierLoc; 5843 Arg->Ident = &S.Context.Idents.get(attrStr); 5844 Arg->Loc = SourceLocation(); 5845 5846 ArgsUnion Args(Arg); 5847 5848 // If there wasn't one, add one (with an invalid source location 5849 // so that we don't make an AttributedType for it). 5850 ParsedAttr *attr = D.getAttributePool().create( 5851 &S.Context.Idents.get("objc_ownership"), SourceLocation(), 5852 /*scope*/ nullptr, SourceLocation(), 5853 /*args*/ &Args, 1, ParsedAttr::AS_GNU); 5854 chunk.getAttrs().addAtEnd(attr); 5855 // TODO: mark whether we did this inference? 5856 } 5857 5858 /// Used for transferring ownership in casts resulting in l-values. 5859 static void transferARCOwnership(TypeProcessingState &state, 5860 QualType &declSpecTy, 5861 Qualifiers::ObjCLifetime ownership) { 5862 Sema &S = state.getSema(); 5863 Declarator &D = state.getDeclarator(); 5864 5865 int inner = -1; 5866 bool hasIndirection = false; 5867 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 5868 DeclaratorChunk &chunk = D.getTypeObject(i); 5869 switch (chunk.Kind) { 5870 case DeclaratorChunk::Paren: 5871 // Ignore parens. 5872 break; 5873 5874 case DeclaratorChunk::Array: 5875 case DeclaratorChunk::Reference: 5876 case DeclaratorChunk::Pointer: 5877 if (inner != -1) 5878 hasIndirection = true; 5879 inner = i; 5880 break; 5881 5882 case DeclaratorChunk::BlockPointer: 5883 if (inner != -1) 5884 transferARCOwnershipToDeclaratorChunk(state, ownership, i); 5885 return; 5886 5887 case DeclaratorChunk::Function: 5888 case DeclaratorChunk::MemberPointer: 5889 case DeclaratorChunk::Pipe: 5890 return; 5891 } 5892 } 5893 5894 if (inner == -1) 5895 return; 5896 5897 DeclaratorChunk &chunk = D.getTypeObject(inner); 5898 if (chunk.Kind == DeclaratorChunk::Pointer) { 5899 if (declSpecTy->isObjCRetainableType()) 5900 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); 5901 if (declSpecTy->isObjCObjectType() && hasIndirection) 5902 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner); 5903 } else { 5904 assert(chunk.Kind == DeclaratorChunk::Array || 5905 chunk.Kind == DeclaratorChunk::Reference); 5906 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); 5907 } 5908 } 5909 5910 TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) { 5911 TypeProcessingState state(*this, D); 5912 5913 TypeSourceInfo *ReturnTypeInfo = nullptr; 5914 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); 5915 5916 if (getLangOpts().ObjC) { 5917 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy); 5918 if (ownership != Qualifiers::OCL_None) 5919 transferARCOwnership(state, declSpecTy, ownership); 5920 } 5921 5922 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo); 5923 } 5924 5925 static void fillAttributedTypeLoc(AttributedTypeLoc TL, 5926 TypeProcessingState &State) { 5927 TL.setAttr(State.takeAttrForAttributedType(TL.getTypePtr())); 5928 } 5929 5930 namespace { 5931 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> { 5932 Sema &SemaRef; 5933 ASTContext &Context; 5934 TypeProcessingState &State; 5935 const DeclSpec &DS; 5936 5937 public: 5938 TypeSpecLocFiller(Sema &S, ASTContext &Context, TypeProcessingState &State, 5939 const DeclSpec &DS) 5940 : SemaRef(S), Context(Context), State(State), DS(DS) {} 5941 5942 void VisitAttributedTypeLoc(AttributedTypeLoc TL) { 5943 Visit(TL.getModifiedLoc()); 5944 fillAttributedTypeLoc(TL, State); 5945 } 5946 void VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) { 5947 Visit(TL.getWrappedLoc()); 5948 } 5949 void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) { 5950 Visit(TL.getInnerLoc()); 5951 TL.setExpansionLoc( 5952 State.getExpansionLocForMacroQualifiedType(TL.getTypePtr())); 5953 } 5954 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 5955 Visit(TL.getUnqualifiedLoc()); 5956 } 5957 // Allow to fill pointee's type locations, e.g., 5958 // int __attr * __attr * __attr *p; 5959 void VisitPointerTypeLoc(PointerTypeLoc TL) { Visit(TL.getNextTypeLoc()); } 5960 void VisitTypedefTypeLoc(TypedefTypeLoc TL) { 5961 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 5962 } 5963 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { 5964 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 5965 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires 5966 // addition field. What we have is good enough for display of location 5967 // of 'fixit' on interface name. 5968 TL.setNameEndLoc(DS.getEndLoc()); 5969 } 5970 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { 5971 TypeSourceInfo *RepTInfo = nullptr; 5972 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo); 5973 TL.copy(RepTInfo->getTypeLoc()); 5974 } 5975 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 5976 TypeSourceInfo *RepTInfo = nullptr; 5977 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo); 5978 TL.copy(RepTInfo->getTypeLoc()); 5979 } 5980 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) { 5981 TypeSourceInfo *TInfo = nullptr; 5982 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 5983 5984 // If we got no declarator info from previous Sema routines, 5985 // just fill with the typespec loc. 5986 if (!TInfo) { 5987 TL.initialize(Context, DS.getTypeSpecTypeNameLoc()); 5988 return; 5989 } 5990 5991 TypeLoc OldTL = TInfo->getTypeLoc(); 5992 if (TInfo->getType()->getAs<ElaboratedType>()) { 5993 ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>(); 5994 TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc() 5995 .castAs<TemplateSpecializationTypeLoc>(); 5996 TL.copy(NamedTL); 5997 } else { 5998 TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>()); 5999 assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc()); 6000 } 6001 6002 } 6003 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { 6004 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr); 6005 TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); 6006 TL.setParensRange(DS.getTypeofParensRange()); 6007 } 6008 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { 6009 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType); 6010 TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); 6011 TL.setParensRange(DS.getTypeofParensRange()); 6012 assert(DS.getRepAsType()); 6013 TypeSourceInfo *TInfo = nullptr; 6014 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 6015 TL.setUnderlyingTInfo(TInfo); 6016 } 6017 void VisitDecltypeTypeLoc(DecltypeTypeLoc TL) { 6018 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype); 6019 TL.setDecltypeLoc(DS.getTypeSpecTypeLoc()); 6020 TL.setRParenLoc(DS.getTypeofParensRange().getEnd()); 6021 } 6022 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) { 6023 // FIXME: This holds only because we only have one unary transform. 6024 assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType); 6025 TL.setKWLoc(DS.getTypeSpecTypeLoc()); 6026 TL.setParensRange(DS.getTypeofParensRange()); 6027 assert(DS.getRepAsType()); 6028 TypeSourceInfo *TInfo = nullptr; 6029 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 6030 TL.setUnderlyingTInfo(TInfo); 6031 } 6032 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { 6033 // By default, use the source location of the type specifier. 6034 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc()); 6035 if (TL.needsExtraLocalData()) { 6036 // Set info for the written builtin specifiers. 6037 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs(); 6038 // Try to have a meaningful source location. 6039 if (TL.getWrittenSignSpec() != TypeSpecifierSign::Unspecified) 6040 TL.expandBuiltinRange(DS.getTypeSpecSignLoc()); 6041 if (TL.getWrittenWidthSpec() != TypeSpecifierWidth::Unspecified) 6042 TL.expandBuiltinRange(DS.getTypeSpecWidthRange()); 6043 } 6044 } 6045 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { 6046 ElaboratedTypeKeyword Keyword 6047 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType()); 6048 if (DS.getTypeSpecType() == TST_typename) { 6049 TypeSourceInfo *TInfo = nullptr; 6050 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 6051 if (TInfo) { 6052 TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>()); 6053 return; 6054 } 6055 } 6056 TL.setElaboratedKeywordLoc(Keyword != ETK_None 6057 ? DS.getTypeSpecTypeLoc() 6058 : SourceLocation()); 6059 const CXXScopeSpec& SS = DS.getTypeSpecScope(); 6060 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 6061 Visit(TL.getNextTypeLoc().getUnqualifiedLoc()); 6062 } 6063 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { 6064 assert(DS.getTypeSpecType() == TST_typename); 6065 TypeSourceInfo *TInfo = nullptr; 6066 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 6067 assert(TInfo); 6068 TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>()); 6069 } 6070 void VisitDependentTemplateSpecializationTypeLoc( 6071 DependentTemplateSpecializationTypeLoc TL) { 6072 assert(DS.getTypeSpecType() == TST_typename); 6073 TypeSourceInfo *TInfo = nullptr; 6074 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 6075 assert(TInfo); 6076 TL.copy( 6077 TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>()); 6078 } 6079 void VisitAutoTypeLoc(AutoTypeLoc TL) { 6080 assert(DS.getTypeSpecType() == TST_auto || 6081 DS.getTypeSpecType() == TST_decltype_auto || 6082 DS.getTypeSpecType() == TST_auto_type || 6083 DS.getTypeSpecType() == TST_unspecified); 6084 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 6085 if (DS.getTypeSpecType() == TST_decltype_auto) 6086 TL.setRParenLoc(DS.getTypeofParensRange().getEnd()); 6087 if (!DS.isConstrainedAuto()) 6088 return; 6089 TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId(); 6090 if (!TemplateId) 6091 return; 6092 if (DS.getTypeSpecScope().isNotEmpty()) 6093 TL.setNestedNameSpecifierLoc( 6094 DS.getTypeSpecScope().getWithLocInContext(Context)); 6095 else 6096 TL.setNestedNameSpecifierLoc(NestedNameSpecifierLoc()); 6097 TL.setTemplateKWLoc(TemplateId->TemplateKWLoc); 6098 TL.setConceptNameLoc(TemplateId->TemplateNameLoc); 6099 TL.setFoundDecl(nullptr); 6100 TL.setLAngleLoc(TemplateId->LAngleLoc); 6101 TL.setRAngleLoc(TemplateId->RAngleLoc); 6102 if (TemplateId->NumArgs == 0) 6103 return; 6104 TemplateArgumentListInfo TemplateArgsInfo; 6105 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 6106 TemplateId->NumArgs); 6107 SemaRef.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo); 6108 for (unsigned I = 0; I < TemplateId->NumArgs; ++I) 6109 TL.setArgLocInfo(I, TemplateArgsInfo.arguments()[I].getLocInfo()); 6110 } 6111 void VisitTagTypeLoc(TagTypeLoc TL) { 6112 TL.setNameLoc(DS.getTypeSpecTypeNameLoc()); 6113 } 6114 void VisitAtomicTypeLoc(AtomicTypeLoc TL) { 6115 // An AtomicTypeLoc can come from either an _Atomic(...) type specifier 6116 // or an _Atomic qualifier. 6117 if (DS.getTypeSpecType() == DeclSpec::TST_atomic) { 6118 TL.setKWLoc(DS.getTypeSpecTypeLoc()); 6119 TL.setParensRange(DS.getTypeofParensRange()); 6120 6121 TypeSourceInfo *TInfo = nullptr; 6122 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 6123 assert(TInfo); 6124 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc()); 6125 } else { 6126 TL.setKWLoc(DS.getAtomicSpecLoc()); 6127 // No parens, to indicate this was spelled as an _Atomic qualifier. 6128 TL.setParensRange(SourceRange()); 6129 Visit(TL.getValueLoc()); 6130 } 6131 } 6132 6133 void VisitPipeTypeLoc(PipeTypeLoc TL) { 6134 TL.setKWLoc(DS.getTypeSpecTypeLoc()); 6135 6136 TypeSourceInfo *TInfo = nullptr; 6137 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 6138 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc()); 6139 } 6140 6141 void VisitExtIntTypeLoc(BitIntTypeLoc TL) { 6142 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 6143 } 6144 6145 void VisitDependentExtIntTypeLoc(DependentBitIntTypeLoc TL) { 6146 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 6147 } 6148 6149 void VisitTypeLoc(TypeLoc TL) { 6150 // FIXME: add other typespec types and change this to an assert. 6151 TL.initialize(Context, DS.getTypeSpecTypeLoc()); 6152 } 6153 }; 6154 6155 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> { 6156 ASTContext &Context; 6157 TypeProcessingState &State; 6158 const DeclaratorChunk &Chunk; 6159 6160 public: 6161 DeclaratorLocFiller(ASTContext &Context, TypeProcessingState &State, 6162 const DeclaratorChunk &Chunk) 6163 : Context(Context), State(State), Chunk(Chunk) {} 6164 6165 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 6166 llvm_unreachable("qualified type locs not expected here!"); 6167 } 6168 void VisitDecayedTypeLoc(DecayedTypeLoc TL) { 6169 llvm_unreachable("decayed type locs not expected here!"); 6170 } 6171 6172 void VisitAttributedTypeLoc(AttributedTypeLoc TL) { 6173 fillAttributedTypeLoc(TL, State); 6174 } 6175 void VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) { 6176 // nothing 6177 } 6178 void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) { 6179 // nothing 6180 } 6181 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { 6182 assert(Chunk.Kind == DeclaratorChunk::BlockPointer); 6183 TL.setCaretLoc(Chunk.Loc); 6184 } 6185 void VisitPointerTypeLoc(PointerTypeLoc TL) { 6186 assert(Chunk.Kind == DeclaratorChunk::Pointer); 6187 TL.setStarLoc(Chunk.Loc); 6188 } 6189 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 6190 assert(Chunk.Kind == DeclaratorChunk::Pointer); 6191 TL.setStarLoc(Chunk.Loc); 6192 } 6193 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { 6194 assert(Chunk.Kind == DeclaratorChunk::MemberPointer); 6195 const CXXScopeSpec& SS = Chunk.Mem.Scope(); 6196 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context); 6197 6198 const Type* ClsTy = TL.getClass(); 6199 QualType ClsQT = QualType(ClsTy, 0); 6200 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0); 6201 // Now copy source location info into the type loc component. 6202 TypeLoc ClsTL = ClsTInfo->getTypeLoc(); 6203 switch (NNSLoc.getNestedNameSpecifier()->getKind()) { 6204 case NestedNameSpecifier::Identifier: 6205 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc"); 6206 { 6207 DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>(); 6208 DNTLoc.setElaboratedKeywordLoc(SourceLocation()); 6209 DNTLoc.setQualifierLoc(NNSLoc.getPrefix()); 6210 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc()); 6211 } 6212 break; 6213 6214 case NestedNameSpecifier::TypeSpec: 6215 case NestedNameSpecifier::TypeSpecWithTemplate: 6216 if (isa<ElaboratedType>(ClsTy)) { 6217 ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>(); 6218 ETLoc.setElaboratedKeywordLoc(SourceLocation()); 6219 ETLoc.setQualifierLoc(NNSLoc.getPrefix()); 6220 TypeLoc NamedTL = ETLoc.getNamedTypeLoc(); 6221 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc()); 6222 } else { 6223 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc()); 6224 } 6225 break; 6226 6227 case NestedNameSpecifier::Namespace: 6228 case NestedNameSpecifier::NamespaceAlias: 6229 case NestedNameSpecifier::Global: 6230 case NestedNameSpecifier::Super: 6231 llvm_unreachable("Nested-name-specifier must name a type"); 6232 } 6233 6234 // Finally fill in MemberPointerLocInfo fields. 6235 TL.setStarLoc(Chunk.Mem.StarLoc); 6236 TL.setClassTInfo(ClsTInfo); 6237 } 6238 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { 6239 assert(Chunk.Kind == DeclaratorChunk::Reference); 6240 // 'Amp' is misleading: this might have been originally 6241 /// spelled with AmpAmp. 6242 TL.setAmpLoc(Chunk.Loc); 6243 } 6244 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { 6245 assert(Chunk.Kind == DeclaratorChunk::Reference); 6246 assert(!Chunk.Ref.LValueRef); 6247 TL.setAmpAmpLoc(Chunk.Loc); 6248 } 6249 void VisitArrayTypeLoc(ArrayTypeLoc TL) { 6250 assert(Chunk.Kind == DeclaratorChunk::Array); 6251 TL.setLBracketLoc(Chunk.Loc); 6252 TL.setRBracketLoc(Chunk.EndLoc); 6253 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts)); 6254 } 6255 void VisitFunctionTypeLoc(FunctionTypeLoc TL) { 6256 assert(Chunk.Kind == DeclaratorChunk::Function); 6257 TL.setLocalRangeBegin(Chunk.Loc); 6258 TL.setLocalRangeEnd(Chunk.EndLoc); 6259 6260 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun; 6261 TL.setLParenLoc(FTI.getLParenLoc()); 6262 TL.setRParenLoc(FTI.getRParenLoc()); 6263 for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) { 6264 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 6265 TL.setParam(tpi++, Param); 6266 } 6267 TL.setExceptionSpecRange(FTI.getExceptionSpecRange()); 6268 } 6269 void VisitParenTypeLoc(ParenTypeLoc TL) { 6270 assert(Chunk.Kind == DeclaratorChunk::Paren); 6271 TL.setLParenLoc(Chunk.Loc); 6272 TL.setRParenLoc(Chunk.EndLoc); 6273 } 6274 void VisitPipeTypeLoc(PipeTypeLoc TL) { 6275 assert(Chunk.Kind == DeclaratorChunk::Pipe); 6276 TL.setKWLoc(Chunk.Loc); 6277 } 6278 void VisitBitIntTypeLoc(BitIntTypeLoc TL) { 6279 TL.setNameLoc(Chunk.Loc); 6280 } 6281 void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) { 6282 TL.setExpansionLoc(Chunk.Loc); 6283 } 6284 void VisitVectorTypeLoc(VectorTypeLoc TL) { TL.setNameLoc(Chunk.Loc); } 6285 void VisitDependentVectorTypeLoc(DependentVectorTypeLoc TL) { 6286 TL.setNameLoc(Chunk.Loc); 6287 } 6288 void VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) { 6289 TL.setNameLoc(Chunk.Loc); 6290 } 6291 void 6292 VisitDependentSizedExtVectorTypeLoc(DependentSizedExtVectorTypeLoc TL) { 6293 TL.setNameLoc(Chunk.Loc); 6294 } 6295 6296 void VisitTypeLoc(TypeLoc TL) { 6297 llvm_unreachable("unsupported TypeLoc kind in declarator!"); 6298 } 6299 }; 6300 } // end anonymous namespace 6301 6302 static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) { 6303 SourceLocation Loc; 6304 switch (Chunk.Kind) { 6305 case DeclaratorChunk::Function: 6306 case DeclaratorChunk::Array: 6307 case DeclaratorChunk::Paren: 6308 case DeclaratorChunk::Pipe: 6309 llvm_unreachable("cannot be _Atomic qualified"); 6310 6311 case DeclaratorChunk::Pointer: 6312 Loc = Chunk.Ptr.AtomicQualLoc; 6313 break; 6314 6315 case DeclaratorChunk::BlockPointer: 6316 case DeclaratorChunk::Reference: 6317 case DeclaratorChunk::MemberPointer: 6318 // FIXME: Provide a source location for the _Atomic keyword. 6319 break; 6320 } 6321 6322 ATL.setKWLoc(Loc); 6323 ATL.setParensRange(SourceRange()); 6324 } 6325 6326 static void 6327 fillDependentAddressSpaceTypeLoc(DependentAddressSpaceTypeLoc DASTL, 6328 const ParsedAttributesView &Attrs) { 6329 for (const ParsedAttr &AL : Attrs) { 6330 if (AL.getKind() == ParsedAttr::AT_AddressSpace) { 6331 DASTL.setAttrNameLoc(AL.getLoc()); 6332 DASTL.setAttrExprOperand(AL.getArgAsExpr(0)); 6333 DASTL.setAttrOperandParensRange(SourceRange()); 6334 return; 6335 } 6336 } 6337 6338 llvm_unreachable( 6339 "no address_space attribute found at the expected location!"); 6340 } 6341 6342 static void fillMatrixTypeLoc(MatrixTypeLoc MTL, 6343 const ParsedAttributesView &Attrs) { 6344 for (const ParsedAttr &AL : Attrs) { 6345 if (AL.getKind() == ParsedAttr::AT_MatrixType) { 6346 MTL.setAttrNameLoc(AL.getLoc()); 6347 MTL.setAttrRowOperand(AL.getArgAsExpr(0)); 6348 MTL.setAttrColumnOperand(AL.getArgAsExpr(1)); 6349 MTL.setAttrOperandParensRange(SourceRange()); 6350 return; 6351 } 6352 } 6353 6354 llvm_unreachable("no matrix_type attribute found at the expected location!"); 6355 } 6356 6357 /// Create and instantiate a TypeSourceInfo with type source information. 6358 /// 6359 /// \param T QualType referring to the type as written in source code. 6360 /// 6361 /// \param ReturnTypeInfo For declarators whose return type does not show 6362 /// up in the normal place in the declaration specifiers (such as a C++ 6363 /// conversion function), this pointer will refer to a type source information 6364 /// for that return type. 6365 static TypeSourceInfo * 6366 GetTypeSourceInfoForDeclarator(TypeProcessingState &State, 6367 QualType T, TypeSourceInfo *ReturnTypeInfo) { 6368 Sema &S = State.getSema(); 6369 Declarator &D = State.getDeclarator(); 6370 6371 TypeSourceInfo *TInfo = S.Context.CreateTypeSourceInfo(T); 6372 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc(); 6373 6374 // Handle parameter packs whose type is a pack expansion. 6375 if (isa<PackExpansionType>(T)) { 6376 CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc()); 6377 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); 6378 } 6379 6380 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 6381 // An AtomicTypeLoc might be produced by an atomic qualifier in this 6382 // declarator chunk. 6383 if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) { 6384 fillAtomicQualLoc(ATL, D.getTypeObject(i)); 6385 CurrTL = ATL.getValueLoc().getUnqualifiedLoc(); 6386 } 6387 6388 while (MacroQualifiedTypeLoc TL = CurrTL.getAs<MacroQualifiedTypeLoc>()) { 6389 TL.setExpansionLoc( 6390 State.getExpansionLocForMacroQualifiedType(TL.getTypePtr())); 6391 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); 6392 } 6393 6394 while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) { 6395 fillAttributedTypeLoc(TL, State); 6396 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); 6397 } 6398 6399 while (DependentAddressSpaceTypeLoc TL = 6400 CurrTL.getAs<DependentAddressSpaceTypeLoc>()) { 6401 fillDependentAddressSpaceTypeLoc(TL, D.getTypeObject(i).getAttrs()); 6402 CurrTL = TL.getPointeeTypeLoc().getUnqualifiedLoc(); 6403 } 6404 6405 if (MatrixTypeLoc TL = CurrTL.getAs<MatrixTypeLoc>()) 6406 fillMatrixTypeLoc(TL, D.getTypeObject(i).getAttrs()); 6407 6408 // FIXME: Ordering here? 6409 while (AdjustedTypeLoc TL = CurrTL.getAs<AdjustedTypeLoc>()) 6410 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); 6411 6412 DeclaratorLocFiller(S.Context, State, D.getTypeObject(i)).Visit(CurrTL); 6413 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); 6414 } 6415 6416 // If we have different source information for the return type, use 6417 // that. This really only applies to C++ conversion functions. 6418 if (ReturnTypeInfo) { 6419 TypeLoc TL = ReturnTypeInfo->getTypeLoc(); 6420 assert(TL.getFullDataSize() == CurrTL.getFullDataSize()); 6421 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize()); 6422 } else { 6423 TypeSpecLocFiller(S, S.Context, State, D.getDeclSpec()).Visit(CurrTL); 6424 } 6425 6426 return TInfo; 6427 } 6428 6429 /// Create a LocInfoType to hold the given QualType and TypeSourceInfo. 6430 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) { 6431 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser 6432 // and Sema during declaration parsing. Try deallocating/caching them when 6433 // it's appropriate, instead of allocating them and keeping them around. 6434 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType), 6435 TypeAlignment); 6436 new (LocT) LocInfoType(T, TInfo); 6437 assert(LocT->getTypeClass() != T->getTypeClass() && 6438 "LocInfoType's TypeClass conflicts with an existing Type class"); 6439 return ParsedType::make(QualType(LocT, 0)); 6440 } 6441 6442 void LocInfoType::getAsStringInternal(std::string &Str, 6443 const PrintingPolicy &Policy) const { 6444 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*" 6445 " was used directly instead of getting the QualType through" 6446 " GetTypeFromParser"); 6447 } 6448 6449 TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) { 6450 // C99 6.7.6: Type names have no identifier. This is already validated by 6451 // the parser. 6452 assert(D.getIdentifier() == nullptr && 6453 "Type name should have no identifier!"); 6454 6455 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 6456 QualType T = TInfo->getType(); 6457 if (D.isInvalidType()) 6458 return true; 6459 6460 // Make sure there are no unused decl attributes on the declarator. 6461 // We don't want to do this for ObjC parameters because we're going 6462 // to apply them to the actual parameter declaration. 6463 // Likewise, we don't want to do this for alias declarations, because 6464 // we are actually going to build a declaration from this eventually. 6465 if (D.getContext() != DeclaratorContext::ObjCParameter && 6466 D.getContext() != DeclaratorContext::AliasDecl && 6467 D.getContext() != DeclaratorContext::AliasTemplate) 6468 checkUnusedDeclAttributes(D); 6469 6470 if (getLangOpts().CPlusPlus) { 6471 // Check that there are no default arguments (C++ only). 6472 CheckExtraCXXDefaultArguments(D); 6473 } 6474 6475 return CreateParsedType(T, TInfo); 6476 } 6477 6478 ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) { 6479 QualType T = Context.getObjCInstanceType(); 6480 TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 6481 return CreateParsedType(T, TInfo); 6482 } 6483 6484 //===----------------------------------------------------------------------===// 6485 // Type Attribute Processing 6486 //===----------------------------------------------------------------------===// 6487 6488 /// Build an AddressSpace index from a constant expression and diagnose any 6489 /// errors related to invalid address_spaces. Returns true on successfully 6490 /// building an AddressSpace index. 6491 static bool BuildAddressSpaceIndex(Sema &S, LangAS &ASIdx, 6492 const Expr *AddrSpace, 6493 SourceLocation AttrLoc) { 6494 if (!AddrSpace->isValueDependent()) { 6495 Optional<llvm::APSInt> OptAddrSpace = 6496 AddrSpace->getIntegerConstantExpr(S.Context); 6497 if (!OptAddrSpace) { 6498 S.Diag(AttrLoc, diag::err_attribute_argument_type) 6499 << "'address_space'" << AANT_ArgumentIntegerConstant 6500 << AddrSpace->getSourceRange(); 6501 return false; 6502 } 6503 llvm::APSInt &addrSpace = *OptAddrSpace; 6504 6505 // Bounds checking. 6506 if (addrSpace.isSigned()) { 6507 if (addrSpace.isNegative()) { 6508 S.Diag(AttrLoc, diag::err_attribute_address_space_negative) 6509 << AddrSpace->getSourceRange(); 6510 return false; 6511 } 6512 addrSpace.setIsSigned(false); 6513 } 6514 6515 llvm::APSInt max(addrSpace.getBitWidth()); 6516 max = 6517 Qualifiers::MaxAddressSpace - (unsigned)LangAS::FirstTargetAddressSpace; 6518 6519 if (addrSpace > max) { 6520 S.Diag(AttrLoc, diag::err_attribute_address_space_too_high) 6521 << (unsigned)max.getZExtValue() << AddrSpace->getSourceRange(); 6522 return false; 6523 } 6524 6525 ASIdx = 6526 getLangASFromTargetAS(static_cast<unsigned>(addrSpace.getZExtValue())); 6527 return true; 6528 } 6529 6530 // Default value for DependentAddressSpaceTypes 6531 ASIdx = LangAS::Default; 6532 return true; 6533 } 6534 6535 /// BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an expression 6536 /// is uninstantiated. If instantiated it will apply the appropriate address 6537 /// space to the type. This function allows dependent template variables to be 6538 /// used in conjunction with the address_space attribute 6539 QualType Sema::BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace, 6540 SourceLocation AttrLoc) { 6541 if (!AddrSpace->isValueDependent()) { 6542 if (DiagnoseMultipleAddrSpaceAttributes(*this, T.getAddressSpace(), ASIdx, 6543 AttrLoc)) 6544 return QualType(); 6545 6546 return Context.getAddrSpaceQualType(T, ASIdx); 6547 } 6548 6549 // A check with similar intentions as checking if a type already has an 6550 // address space except for on a dependent types, basically if the 6551 // current type is already a DependentAddressSpaceType then its already 6552 // lined up to have another address space on it and we can't have 6553 // multiple address spaces on the one pointer indirection 6554 if (T->getAs<DependentAddressSpaceType>()) { 6555 Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers); 6556 return QualType(); 6557 } 6558 6559 return Context.getDependentAddressSpaceType(T, AddrSpace, AttrLoc); 6560 } 6561 6562 QualType Sema::BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace, 6563 SourceLocation AttrLoc) { 6564 LangAS ASIdx; 6565 if (!BuildAddressSpaceIndex(*this, ASIdx, AddrSpace, AttrLoc)) 6566 return QualType(); 6567 return BuildAddressSpaceAttr(T, ASIdx, AddrSpace, AttrLoc); 6568 } 6569 6570 static void HandleBTFTypeTagAttribute(QualType &Type, const ParsedAttr &Attr, 6571 TypeProcessingState &State) { 6572 Sema &S = State.getSema(); 6573 6574 // Check the number of attribute arguments. 6575 if (Attr.getNumArgs() != 1) { 6576 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 6577 << Attr << 1; 6578 Attr.setInvalid(); 6579 return; 6580 } 6581 6582 // Ensure the argument is a string. 6583 auto *StrLiteral = dyn_cast<StringLiteral>(Attr.getArgAsExpr(0)); 6584 if (!StrLiteral) { 6585 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) 6586 << Attr << AANT_ArgumentString; 6587 Attr.setInvalid(); 6588 return; 6589 } 6590 6591 ASTContext &Ctx = S.Context; 6592 StringRef BTFTypeTag = StrLiteral->getString(); 6593 Type = State.getBTFTagAttributedType( 6594 ::new (Ctx) BTFTypeTagAttr(Ctx, Attr, BTFTypeTag), Type); 6595 } 6596 6597 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the 6598 /// specified type. The attribute contains 1 argument, the id of the address 6599 /// space for the type. 6600 static void HandleAddressSpaceTypeAttribute(QualType &Type, 6601 const ParsedAttr &Attr, 6602 TypeProcessingState &State) { 6603 Sema &S = State.getSema(); 6604 6605 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be 6606 // qualified by an address-space qualifier." 6607 if (Type->isFunctionType()) { 6608 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type); 6609 Attr.setInvalid(); 6610 return; 6611 } 6612 6613 LangAS ASIdx; 6614 if (Attr.getKind() == ParsedAttr::AT_AddressSpace) { 6615 6616 // Check the attribute arguments. 6617 if (Attr.getNumArgs() != 1) { 6618 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr 6619 << 1; 6620 Attr.setInvalid(); 6621 return; 6622 } 6623 6624 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); 6625 LangAS ASIdx; 6626 if (!BuildAddressSpaceIndex(S, ASIdx, ASArgExpr, Attr.getLoc())) { 6627 Attr.setInvalid(); 6628 return; 6629 } 6630 6631 ASTContext &Ctx = S.Context; 6632 auto *ASAttr = 6633 ::new (Ctx) AddressSpaceAttr(Ctx, Attr, static_cast<unsigned>(ASIdx)); 6634 6635 // If the expression is not value dependent (not templated), then we can 6636 // apply the address space qualifiers just to the equivalent type. 6637 // Otherwise, we make an AttributedType with the modified and equivalent 6638 // type the same, and wrap it in a DependentAddressSpaceType. When this 6639 // dependent type is resolved, the qualifier is added to the equivalent type 6640 // later. 6641 QualType T; 6642 if (!ASArgExpr->isValueDependent()) { 6643 QualType EquivType = 6644 S.BuildAddressSpaceAttr(Type, ASIdx, ASArgExpr, Attr.getLoc()); 6645 if (EquivType.isNull()) { 6646 Attr.setInvalid(); 6647 return; 6648 } 6649 T = State.getAttributedType(ASAttr, Type, EquivType); 6650 } else { 6651 T = State.getAttributedType(ASAttr, Type, Type); 6652 T = S.BuildAddressSpaceAttr(T, ASIdx, ASArgExpr, Attr.getLoc()); 6653 } 6654 6655 if (!T.isNull()) 6656 Type = T; 6657 else 6658 Attr.setInvalid(); 6659 } else { 6660 // The keyword-based type attributes imply which address space to use. 6661 ASIdx = S.getLangOpts().SYCLIsDevice ? Attr.asSYCLLangAS() 6662 : Attr.asOpenCLLangAS(); 6663 6664 if (ASIdx == LangAS::Default) 6665 llvm_unreachable("Invalid address space"); 6666 6667 if (DiagnoseMultipleAddrSpaceAttributes(S, Type.getAddressSpace(), ASIdx, 6668 Attr.getLoc())) { 6669 Attr.setInvalid(); 6670 return; 6671 } 6672 6673 Type = S.Context.getAddrSpaceQualType(Type, ASIdx); 6674 } 6675 } 6676 6677 /// handleObjCOwnershipTypeAttr - Process an objc_ownership 6678 /// attribute on the specified type. 6679 /// 6680 /// Returns 'true' if the attribute was handled. 6681 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state, 6682 ParsedAttr &attr, QualType &type) { 6683 bool NonObjCPointer = false; 6684 6685 if (!type->isDependentType() && !type->isUndeducedType()) { 6686 if (const PointerType *ptr = type->getAs<PointerType>()) { 6687 QualType pointee = ptr->getPointeeType(); 6688 if (pointee->isObjCRetainableType() || pointee->isPointerType()) 6689 return false; 6690 // It is important not to lose the source info that there was an attribute 6691 // applied to non-objc pointer. We will create an attributed type but 6692 // its type will be the same as the original type. 6693 NonObjCPointer = true; 6694 } else if (!type->isObjCRetainableType()) { 6695 return false; 6696 } 6697 6698 // Don't accept an ownership attribute in the declspec if it would 6699 // just be the return type of a block pointer. 6700 if (state.isProcessingDeclSpec()) { 6701 Declarator &D = state.getDeclarator(); 6702 if (maybeMovePastReturnType(D, D.getNumTypeObjects(), 6703 /*onlyBlockPointers=*/true)) 6704 return false; 6705 } 6706 } 6707 6708 Sema &S = state.getSema(); 6709 SourceLocation AttrLoc = attr.getLoc(); 6710 if (AttrLoc.isMacroID()) 6711 AttrLoc = 6712 S.getSourceManager().getImmediateExpansionRange(AttrLoc).getBegin(); 6713 6714 if (!attr.isArgIdent(0)) { 6715 S.Diag(AttrLoc, diag::err_attribute_argument_type) << attr 6716 << AANT_ArgumentString; 6717 attr.setInvalid(); 6718 return true; 6719 } 6720 6721 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident; 6722 Qualifiers::ObjCLifetime lifetime; 6723 if (II->isStr("none")) 6724 lifetime = Qualifiers::OCL_ExplicitNone; 6725 else if (II->isStr("strong")) 6726 lifetime = Qualifiers::OCL_Strong; 6727 else if (II->isStr("weak")) 6728 lifetime = Qualifiers::OCL_Weak; 6729 else if (II->isStr("autoreleasing")) 6730 lifetime = Qualifiers::OCL_Autoreleasing; 6731 else { 6732 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported) << attr << II; 6733 attr.setInvalid(); 6734 return true; 6735 } 6736 6737 // Just ignore lifetime attributes other than __weak and __unsafe_unretained 6738 // outside of ARC mode. 6739 if (!S.getLangOpts().ObjCAutoRefCount && 6740 lifetime != Qualifiers::OCL_Weak && 6741 lifetime != Qualifiers::OCL_ExplicitNone) { 6742 return true; 6743 } 6744 6745 SplitQualType underlyingType = type.split(); 6746 6747 // Check for redundant/conflicting ownership qualifiers. 6748 if (Qualifiers::ObjCLifetime previousLifetime 6749 = type.getQualifiers().getObjCLifetime()) { 6750 // If it's written directly, that's an error. 6751 if (S.Context.hasDirectOwnershipQualifier(type)) { 6752 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant) 6753 << type; 6754 return true; 6755 } 6756 6757 // Otherwise, if the qualifiers actually conflict, pull sugar off 6758 // and remove the ObjCLifetime qualifiers. 6759 if (previousLifetime != lifetime) { 6760 // It's possible to have multiple local ObjCLifetime qualifiers. We 6761 // can't stop after we reach a type that is directly qualified. 6762 const Type *prevTy = nullptr; 6763 while (!prevTy || prevTy != underlyingType.Ty) { 6764 prevTy = underlyingType.Ty; 6765 underlyingType = underlyingType.getSingleStepDesugaredType(); 6766 } 6767 underlyingType.Quals.removeObjCLifetime(); 6768 } 6769 } 6770 6771 underlyingType.Quals.addObjCLifetime(lifetime); 6772 6773 if (NonObjCPointer) { 6774 StringRef name = attr.getAttrName()->getName(); 6775 switch (lifetime) { 6776 case Qualifiers::OCL_None: 6777 case Qualifiers::OCL_ExplicitNone: 6778 break; 6779 case Qualifiers::OCL_Strong: name = "__strong"; break; 6780 case Qualifiers::OCL_Weak: name = "__weak"; break; 6781 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break; 6782 } 6783 S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name 6784 << TDS_ObjCObjOrBlock << type; 6785 } 6786 6787 // Don't actually add the __unsafe_unretained qualifier in non-ARC files, 6788 // because having both 'T' and '__unsafe_unretained T' exist in the type 6789 // system causes unfortunate widespread consistency problems. (For example, 6790 // they're not considered compatible types, and we mangle them identicially 6791 // as template arguments.) These problems are all individually fixable, 6792 // but it's easier to just not add the qualifier and instead sniff it out 6793 // in specific places using isObjCInertUnsafeUnretainedType(). 6794 // 6795 // Doing this does means we miss some trivial consistency checks that 6796 // would've triggered in ARC, but that's better than trying to solve all 6797 // the coexistence problems with __unsafe_unretained. 6798 if (!S.getLangOpts().ObjCAutoRefCount && 6799 lifetime == Qualifiers::OCL_ExplicitNone) { 6800 type = state.getAttributedType( 6801 createSimpleAttr<ObjCInertUnsafeUnretainedAttr>(S.Context, attr), 6802 type, type); 6803 return true; 6804 } 6805 6806 QualType origType = type; 6807 if (!NonObjCPointer) 6808 type = S.Context.getQualifiedType(underlyingType); 6809 6810 // If we have a valid source location for the attribute, use an 6811 // AttributedType instead. 6812 if (AttrLoc.isValid()) { 6813 type = state.getAttributedType(::new (S.Context) 6814 ObjCOwnershipAttr(S.Context, attr, II), 6815 origType, type); 6816 } 6817 6818 auto diagnoseOrDelay = [](Sema &S, SourceLocation loc, 6819 unsigned diagnostic, QualType type) { 6820 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) { 6821 S.DelayedDiagnostics.add( 6822 sema::DelayedDiagnostic::makeForbiddenType( 6823 S.getSourceManager().getExpansionLoc(loc), 6824 diagnostic, type, /*ignored*/ 0)); 6825 } else { 6826 S.Diag(loc, diagnostic); 6827 } 6828 }; 6829 6830 // Sometimes, __weak isn't allowed. 6831 if (lifetime == Qualifiers::OCL_Weak && 6832 !S.getLangOpts().ObjCWeak && !NonObjCPointer) { 6833 6834 // Use a specialized diagnostic if the runtime just doesn't support them. 6835 unsigned diagnostic = 6836 (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled 6837 : diag::err_arc_weak_no_runtime); 6838 6839 // In any case, delay the diagnostic until we know what we're parsing. 6840 diagnoseOrDelay(S, AttrLoc, diagnostic, type); 6841 6842 attr.setInvalid(); 6843 return true; 6844 } 6845 6846 // Forbid __weak for class objects marked as 6847 // objc_arc_weak_reference_unavailable 6848 if (lifetime == Qualifiers::OCL_Weak) { 6849 if (const ObjCObjectPointerType *ObjT = 6850 type->getAs<ObjCObjectPointerType>()) { 6851 if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) { 6852 if (Class->isArcWeakrefUnavailable()) { 6853 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class); 6854 S.Diag(ObjT->getInterfaceDecl()->getLocation(), 6855 diag::note_class_declared); 6856 } 6857 } 6858 } 6859 } 6860 6861 return true; 6862 } 6863 6864 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type 6865 /// attribute on the specified type. Returns true to indicate that 6866 /// the attribute was handled, false to indicate that the type does 6867 /// not permit the attribute. 6868 static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr, 6869 QualType &type) { 6870 Sema &S = state.getSema(); 6871 6872 // Delay if this isn't some kind of pointer. 6873 if (!type->isPointerType() && 6874 !type->isObjCObjectPointerType() && 6875 !type->isBlockPointerType()) 6876 return false; 6877 6878 if (type.getObjCGCAttr() != Qualifiers::GCNone) { 6879 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc); 6880 attr.setInvalid(); 6881 return true; 6882 } 6883 6884 // Check the attribute arguments. 6885 if (!attr.isArgIdent(0)) { 6886 S.Diag(attr.getLoc(), diag::err_attribute_argument_type) 6887 << attr << AANT_ArgumentString; 6888 attr.setInvalid(); 6889 return true; 6890 } 6891 Qualifiers::GC GCAttr; 6892 if (attr.getNumArgs() > 1) { 6893 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << attr 6894 << 1; 6895 attr.setInvalid(); 6896 return true; 6897 } 6898 6899 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident; 6900 if (II->isStr("weak")) 6901 GCAttr = Qualifiers::Weak; 6902 else if (II->isStr("strong")) 6903 GCAttr = Qualifiers::Strong; 6904 else { 6905 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported) 6906 << attr << II; 6907 attr.setInvalid(); 6908 return true; 6909 } 6910 6911 QualType origType = type; 6912 type = S.Context.getObjCGCQualType(origType, GCAttr); 6913 6914 // Make an attributed type to preserve the source information. 6915 if (attr.getLoc().isValid()) 6916 type = state.getAttributedType( 6917 ::new (S.Context) ObjCGCAttr(S.Context, attr, II), origType, type); 6918 6919 return true; 6920 } 6921 6922 namespace { 6923 /// A helper class to unwrap a type down to a function for the 6924 /// purposes of applying attributes there. 6925 /// 6926 /// Use: 6927 /// FunctionTypeUnwrapper unwrapped(SemaRef, T); 6928 /// if (unwrapped.isFunctionType()) { 6929 /// const FunctionType *fn = unwrapped.get(); 6930 /// // change fn somehow 6931 /// T = unwrapped.wrap(fn); 6932 /// } 6933 struct FunctionTypeUnwrapper { 6934 enum WrapKind { 6935 Desugar, 6936 Attributed, 6937 Parens, 6938 Array, 6939 Pointer, 6940 BlockPointer, 6941 Reference, 6942 MemberPointer, 6943 MacroQualified, 6944 }; 6945 6946 QualType Original; 6947 const FunctionType *Fn; 6948 SmallVector<unsigned char /*WrapKind*/, 8> Stack; 6949 6950 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) { 6951 while (true) { 6952 const Type *Ty = T.getTypePtr(); 6953 if (isa<FunctionType>(Ty)) { 6954 Fn = cast<FunctionType>(Ty); 6955 return; 6956 } else if (isa<ParenType>(Ty)) { 6957 T = cast<ParenType>(Ty)->getInnerType(); 6958 Stack.push_back(Parens); 6959 } else if (isa<ConstantArrayType>(Ty) || isa<VariableArrayType>(Ty) || 6960 isa<IncompleteArrayType>(Ty)) { 6961 T = cast<ArrayType>(Ty)->getElementType(); 6962 Stack.push_back(Array); 6963 } else if (isa<PointerType>(Ty)) { 6964 T = cast<PointerType>(Ty)->getPointeeType(); 6965 Stack.push_back(Pointer); 6966 } else if (isa<BlockPointerType>(Ty)) { 6967 T = cast<BlockPointerType>(Ty)->getPointeeType(); 6968 Stack.push_back(BlockPointer); 6969 } else if (isa<MemberPointerType>(Ty)) { 6970 T = cast<MemberPointerType>(Ty)->getPointeeType(); 6971 Stack.push_back(MemberPointer); 6972 } else if (isa<ReferenceType>(Ty)) { 6973 T = cast<ReferenceType>(Ty)->getPointeeType(); 6974 Stack.push_back(Reference); 6975 } else if (isa<AttributedType>(Ty)) { 6976 T = cast<AttributedType>(Ty)->getEquivalentType(); 6977 Stack.push_back(Attributed); 6978 } else if (isa<MacroQualifiedType>(Ty)) { 6979 T = cast<MacroQualifiedType>(Ty)->getUnderlyingType(); 6980 Stack.push_back(MacroQualified); 6981 } else { 6982 const Type *DTy = Ty->getUnqualifiedDesugaredType(); 6983 if (Ty == DTy) { 6984 Fn = nullptr; 6985 return; 6986 } 6987 6988 T = QualType(DTy, 0); 6989 Stack.push_back(Desugar); 6990 } 6991 } 6992 } 6993 6994 bool isFunctionType() const { return (Fn != nullptr); } 6995 const FunctionType *get() const { return Fn; } 6996 6997 QualType wrap(Sema &S, const FunctionType *New) { 6998 // If T wasn't modified from the unwrapped type, do nothing. 6999 if (New == get()) return Original; 7000 7001 Fn = New; 7002 return wrap(S.Context, Original, 0); 7003 } 7004 7005 private: 7006 QualType wrap(ASTContext &C, QualType Old, unsigned I) { 7007 if (I == Stack.size()) 7008 return C.getQualifiedType(Fn, Old.getQualifiers()); 7009 7010 // Build up the inner type, applying the qualifiers from the old 7011 // type to the new type. 7012 SplitQualType SplitOld = Old.split(); 7013 7014 // As a special case, tail-recurse if there are no qualifiers. 7015 if (SplitOld.Quals.empty()) 7016 return wrap(C, SplitOld.Ty, I); 7017 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals); 7018 } 7019 7020 QualType wrap(ASTContext &C, const Type *Old, unsigned I) { 7021 if (I == Stack.size()) return QualType(Fn, 0); 7022 7023 switch (static_cast<WrapKind>(Stack[I++])) { 7024 case Desugar: 7025 // This is the point at which we potentially lose source 7026 // information. 7027 return wrap(C, Old->getUnqualifiedDesugaredType(), I); 7028 7029 case Attributed: 7030 return wrap(C, cast<AttributedType>(Old)->getEquivalentType(), I); 7031 7032 case Parens: { 7033 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I); 7034 return C.getParenType(New); 7035 } 7036 7037 case MacroQualified: 7038 return wrap(C, cast<MacroQualifiedType>(Old)->getUnderlyingType(), I); 7039 7040 case Array: { 7041 if (const auto *CAT = dyn_cast<ConstantArrayType>(Old)) { 7042 QualType New = wrap(C, CAT->getElementType(), I); 7043 return C.getConstantArrayType(New, CAT->getSize(), CAT->getSizeExpr(), 7044 CAT->getSizeModifier(), 7045 CAT->getIndexTypeCVRQualifiers()); 7046 } 7047 7048 if (const auto *VAT = dyn_cast<VariableArrayType>(Old)) { 7049 QualType New = wrap(C, VAT->getElementType(), I); 7050 return C.getVariableArrayType( 7051 New, VAT->getSizeExpr(), VAT->getSizeModifier(), 7052 VAT->getIndexTypeCVRQualifiers(), VAT->getBracketsRange()); 7053 } 7054 7055 const auto *IAT = cast<IncompleteArrayType>(Old); 7056 QualType New = wrap(C, IAT->getElementType(), I); 7057 return C.getIncompleteArrayType(New, IAT->getSizeModifier(), 7058 IAT->getIndexTypeCVRQualifiers()); 7059 } 7060 7061 case Pointer: { 7062 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I); 7063 return C.getPointerType(New); 7064 } 7065 7066 case BlockPointer: { 7067 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I); 7068 return C.getBlockPointerType(New); 7069 } 7070 7071 case MemberPointer: { 7072 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old); 7073 QualType New = wrap(C, OldMPT->getPointeeType(), I); 7074 return C.getMemberPointerType(New, OldMPT->getClass()); 7075 } 7076 7077 case Reference: { 7078 const ReferenceType *OldRef = cast<ReferenceType>(Old); 7079 QualType New = wrap(C, OldRef->getPointeeType(), I); 7080 if (isa<LValueReferenceType>(OldRef)) 7081 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue()); 7082 else 7083 return C.getRValueReferenceType(New); 7084 } 7085 } 7086 7087 llvm_unreachable("unknown wrapping kind"); 7088 } 7089 }; 7090 } // end anonymous namespace 7091 7092 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State, 7093 ParsedAttr &PAttr, QualType &Type) { 7094 Sema &S = State.getSema(); 7095 7096 Attr *A; 7097 switch (PAttr.getKind()) { 7098 default: llvm_unreachable("Unknown attribute kind"); 7099 case ParsedAttr::AT_Ptr32: 7100 A = createSimpleAttr<Ptr32Attr>(S.Context, PAttr); 7101 break; 7102 case ParsedAttr::AT_Ptr64: 7103 A = createSimpleAttr<Ptr64Attr>(S.Context, PAttr); 7104 break; 7105 case ParsedAttr::AT_SPtr: 7106 A = createSimpleAttr<SPtrAttr>(S.Context, PAttr); 7107 break; 7108 case ParsedAttr::AT_UPtr: 7109 A = createSimpleAttr<UPtrAttr>(S.Context, PAttr); 7110 break; 7111 } 7112 7113 std::bitset<attr::LastAttr> Attrs; 7114 attr::Kind NewAttrKind = A->getKind(); 7115 QualType Desugared = Type; 7116 const AttributedType *AT = dyn_cast<AttributedType>(Type); 7117 while (AT) { 7118 Attrs[AT->getAttrKind()] = true; 7119 Desugared = AT->getModifiedType(); 7120 AT = dyn_cast<AttributedType>(Desugared); 7121 } 7122 7123 // You cannot specify duplicate type attributes, so if the attribute has 7124 // already been applied, flag it. 7125 if (Attrs[NewAttrKind]) { 7126 S.Diag(PAttr.getLoc(), diag::warn_duplicate_attribute_exact) << PAttr; 7127 return true; 7128 } 7129 Attrs[NewAttrKind] = true; 7130 7131 // You cannot have both __sptr and __uptr on the same type, nor can you 7132 // have __ptr32 and __ptr64. 7133 if (Attrs[attr::Ptr32] && Attrs[attr::Ptr64]) { 7134 S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible) 7135 << "'__ptr32'" 7136 << "'__ptr64'"; 7137 return true; 7138 } else if (Attrs[attr::SPtr] && Attrs[attr::UPtr]) { 7139 S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible) 7140 << "'__sptr'" 7141 << "'__uptr'"; 7142 return true; 7143 } 7144 7145 // Pointer type qualifiers can only operate on pointer types, but not 7146 // pointer-to-member types. 7147 // 7148 // FIXME: Should we really be disallowing this attribute if there is any 7149 // type sugar between it and the pointer (other than attributes)? Eg, this 7150 // disallows the attribute on a parenthesized pointer. 7151 // And if so, should we really allow *any* type attribute? 7152 if (!isa<PointerType>(Desugared)) { 7153 if (Type->isMemberPointerType()) 7154 S.Diag(PAttr.getLoc(), diag::err_attribute_no_member_pointers) << PAttr; 7155 else 7156 S.Diag(PAttr.getLoc(), diag::err_attribute_pointers_only) << PAttr << 0; 7157 return true; 7158 } 7159 7160 // Add address space to type based on its attributes. 7161 LangAS ASIdx = LangAS::Default; 7162 uint64_t PtrWidth = S.Context.getTargetInfo().getPointerWidth(0); 7163 if (PtrWidth == 32) { 7164 if (Attrs[attr::Ptr64]) 7165 ASIdx = LangAS::ptr64; 7166 else if (Attrs[attr::UPtr]) 7167 ASIdx = LangAS::ptr32_uptr; 7168 } else if (PtrWidth == 64 && Attrs[attr::Ptr32]) { 7169 if (Attrs[attr::UPtr]) 7170 ASIdx = LangAS::ptr32_uptr; 7171 else 7172 ASIdx = LangAS::ptr32_sptr; 7173 } 7174 7175 QualType Pointee = Type->getPointeeType(); 7176 if (ASIdx != LangAS::Default) 7177 Pointee = S.Context.getAddrSpaceQualType( 7178 S.Context.removeAddrSpaceQualType(Pointee), ASIdx); 7179 Type = State.getAttributedType(A, Type, S.Context.getPointerType(Pointee)); 7180 return false; 7181 } 7182 7183 /// Map a nullability attribute kind to a nullability kind. 7184 static NullabilityKind mapNullabilityAttrKind(ParsedAttr::Kind kind) { 7185 switch (kind) { 7186 case ParsedAttr::AT_TypeNonNull: 7187 return NullabilityKind::NonNull; 7188 7189 case ParsedAttr::AT_TypeNullable: 7190 return NullabilityKind::Nullable; 7191 7192 case ParsedAttr::AT_TypeNullableResult: 7193 return NullabilityKind::NullableResult; 7194 7195 case ParsedAttr::AT_TypeNullUnspecified: 7196 return NullabilityKind::Unspecified; 7197 7198 default: 7199 llvm_unreachable("not a nullability attribute kind"); 7200 } 7201 } 7202 7203 /// Applies a nullability type specifier to the given type, if possible. 7204 /// 7205 /// \param state The type processing state. 7206 /// 7207 /// \param type The type to which the nullability specifier will be 7208 /// added. On success, this type will be updated appropriately. 7209 /// 7210 /// \param attr The attribute as written on the type. 7211 /// 7212 /// \param allowOnArrayType Whether to accept nullability specifiers on an 7213 /// array type (e.g., because it will decay to a pointer). 7214 /// 7215 /// \returns true if a problem has been diagnosed, false on success. 7216 static bool checkNullabilityTypeSpecifier(TypeProcessingState &state, 7217 QualType &type, 7218 ParsedAttr &attr, 7219 bool allowOnArrayType) { 7220 Sema &S = state.getSema(); 7221 7222 NullabilityKind nullability = mapNullabilityAttrKind(attr.getKind()); 7223 SourceLocation nullabilityLoc = attr.getLoc(); 7224 bool isContextSensitive = attr.isContextSensitiveKeywordAttribute(); 7225 7226 recordNullabilitySeen(S, nullabilityLoc); 7227 7228 // Check for existing nullability attributes on the type. 7229 QualType desugared = type; 7230 while (auto attributed = dyn_cast<AttributedType>(desugared.getTypePtr())) { 7231 // Check whether there is already a null 7232 if (auto existingNullability = attributed->getImmediateNullability()) { 7233 // Duplicated nullability. 7234 if (nullability == *existingNullability) { 7235 S.Diag(nullabilityLoc, diag::warn_nullability_duplicate) 7236 << DiagNullabilityKind(nullability, isContextSensitive) 7237 << FixItHint::CreateRemoval(nullabilityLoc); 7238 7239 break; 7240 } 7241 7242 // Conflicting nullability. 7243 S.Diag(nullabilityLoc, diag::err_nullability_conflicting) 7244 << DiagNullabilityKind(nullability, isContextSensitive) 7245 << DiagNullabilityKind(*existingNullability, false); 7246 return true; 7247 } 7248 7249 desugared = attributed->getModifiedType(); 7250 } 7251 7252 // If there is already a different nullability specifier, complain. 7253 // This (unlike the code above) looks through typedefs that might 7254 // have nullability specifiers on them, which means we cannot 7255 // provide a useful Fix-It. 7256 if (auto existingNullability = desugared->getNullability(S.Context)) { 7257 if (nullability != *existingNullability) { 7258 S.Diag(nullabilityLoc, diag::err_nullability_conflicting) 7259 << DiagNullabilityKind(nullability, isContextSensitive) 7260 << DiagNullabilityKind(*existingNullability, false); 7261 7262 // Try to find the typedef with the existing nullability specifier. 7263 if (auto typedefType = desugared->getAs<TypedefType>()) { 7264 TypedefNameDecl *typedefDecl = typedefType->getDecl(); 7265 QualType underlyingType = typedefDecl->getUnderlyingType(); 7266 if (auto typedefNullability 7267 = AttributedType::stripOuterNullability(underlyingType)) { 7268 if (*typedefNullability == *existingNullability) { 7269 S.Diag(typedefDecl->getLocation(), diag::note_nullability_here) 7270 << DiagNullabilityKind(*existingNullability, false); 7271 } 7272 } 7273 } 7274 7275 return true; 7276 } 7277 } 7278 7279 // If this definitely isn't a pointer type, reject the specifier. 7280 if (!desugared->canHaveNullability() && 7281 !(allowOnArrayType && desugared->isArrayType())) { 7282 S.Diag(nullabilityLoc, diag::err_nullability_nonpointer) 7283 << DiagNullabilityKind(nullability, isContextSensitive) << type; 7284 return true; 7285 } 7286 7287 // For the context-sensitive keywords/Objective-C property 7288 // attributes, require that the type be a single-level pointer. 7289 if (isContextSensitive) { 7290 // Make sure that the pointee isn't itself a pointer type. 7291 const Type *pointeeType = nullptr; 7292 if (desugared->isArrayType()) 7293 pointeeType = desugared->getArrayElementTypeNoTypeQual(); 7294 else if (desugared->isAnyPointerType()) 7295 pointeeType = desugared->getPointeeType().getTypePtr(); 7296 7297 if (pointeeType && (pointeeType->isAnyPointerType() || 7298 pointeeType->isObjCObjectPointerType() || 7299 pointeeType->isMemberPointerType())) { 7300 S.Diag(nullabilityLoc, diag::err_nullability_cs_multilevel) 7301 << DiagNullabilityKind(nullability, true) 7302 << type; 7303 S.Diag(nullabilityLoc, diag::note_nullability_type_specifier) 7304 << DiagNullabilityKind(nullability, false) 7305 << type 7306 << FixItHint::CreateReplacement(nullabilityLoc, 7307 getNullabilitySpelling(nullability)); 7308 return true; 7309 } 7310 } 7311 7312 // Form the attributed type. 7313 type = state.getAttributedType( 7314 createNullabilityAttr(S.Context, attr, nullability), type, type); 7315 return false; 7316 } 7317 7318 /// Check the application of the Objective-C '__kindof' qualifier to 7319 /// the given type. 7320 static bool checkObjCKindOfType(TypeProcessingState &state, QualType &type, 7321 ParsedAttr &attr) { 7322 Sema &S = state.getSema(); 7323 7324 if (isa<ObjCTypeParamType>(type)) { 7325 // Build the attributed type to record where __kindof occurred. 7326 type = state.getAttributedType( 7327 createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, type); 7328 return false; 7329 } 7330 7331 // Find out if it's an Objective-C object or object pointer type; 7332 const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>(); 7333 const ObjCObjectType *objType = ptrType ? ptrType->getObjectType() 7334 : type->getAs<ObjCObjectType>(); 7335 7336 // If not, we can't apply __kindof. 7337 if (!objType) { 7338 // FIXME: Handle dependent types that aren't yet object types. 7339 S.Diag(attr.getLoc(), diag::err_objc_kindof_nonobject) 7340 << type; 7341 return true; 7342 } 7343 7344 // Rebuild the "equivalent" type, which pushes __kindof down into 7345 // the object type. 7346 // There is no need to apply kindof on an unqualified id type. 7347 QualType equivType = S.Context.getObjCObjectType( 7348 objType->getBaseType(), objType->getTypeArgsAsWritten(), 7349 objType->getProtocols(), 7350 /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true); 7351 7352 // If we started with an object pointer type, rebuild it. 7353 if (ptrType) { 7354 equivType = S.Context.getObjCObjectPointerType(equivType); 7355 if (auto nullability = type->getNullability(S.Context)) { 7356 // We create a nullability attribute from the __kindof attribute. 7357 // Make sure that will make sense. 7358 assert(attr.getAttributeSpellingListIndex() == 0 && 7359 "multiple spellings for __kindof?"); 7360 Attr *A = createNullabilityAttr(S.Context, attr, *nullability); 7361 A->setImplicit(true); 7362 equivType = state.getAttributedType(A, equivType, equivType); 7363 } 7364 } 7365 7366 // Build the attributed type to record where __kindof occurred. 7367 type = state.getAttributedType( 7368 createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, equivType); 7369 return false; 7370 } 7371 7372 /// Distribute a nullability type attribute that cannot be applied to 7373 /// the type specifier to a pointer, block pointer, or member pointer 7374 /// declarator, complaining if necessary. 7375 /// 7376 /// \returns true if the nullability annotation was distributed, false 7377 /// otherwise. 7378 static bool distributeNullabilityTypeAttr(TypeProcessingState &state, 7379 QualType type, ParsedAttr &attr) { 7380 Declarator &declarator = state.getDeclarator(); 7381 7382 /// Attempt to move the attribute to the specified chunk. 7383 auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool { 7384 // If there is already a nullability attribute there, don't add 7385 // one. 7386 if (hasNullabilityAttr(chunk.getAttrs())) 7387 return false; 7388 7389 // Complain about the nullability qualifier being in the wrong 7390 // place. 7391 enum { 7392 PK_Pointer, 7393 PK_BlockPointer, 7394 PK_MemberPointer, 7395 PK_FunctionPointer, 7396 PK_MemberFunctionPointer, 7397 } pointerKind 7398 = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer 7399 : PK_Pointer) 7400 : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer 7401 : inFunction? PK_MemberFunctionPointer : PK_MemberPointer; 7402 7403 auto diag = state.getSema().Diag(attr.getLoc(), 7404 diag::warn_nullability_declspec) 7405 << DiagNullabilityKind(mapNullabilityAttrKind(attr.getKind()), 7406 attr.isContextSensitiveKeywordAttribute()) 7407 << type 7408 << static_cast<unsigned>(pointerKind); 7409 7410 // FIXME: MemberPointer chunks don't carry the location of the *. 7411 if (chunk.Kind != DeclaratorChunk::MemberPointer) { 7412 diag << FixItHint::CreateRemoval(attr.getLoc()) 7413 << FixItHint::CreateInsertion( 7414 state.getSema().getPreprocessor().getLocForEndOfToken( 7415 chunk.Loc), 7416 " " + attr.getAttrName()->getName().str() + " "); 7417 } 7418 7419 moveAttrFromListToList(attr, state.getCurrentAttributes(), 7420 chunk.getAttrs()); 7421 return true; 7422 }; 7423 7424 // Move it to the outermost pointer, member pointer, or block 7425 // pointer declarator. 7426 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { 7427 DeclaratorChunk &chunk = declarator.getTypeObject(i-1); 7428 switch (chunk.Kind) { 7429 case DeclaratorChunk::Pointer: 7430 case DeclaratorChunk::BlockPointer: 7431 case DeclaratorChunk::MemberPointer: 7432 return moveToChunk(chunk, false); 7433 7434 case DeclaratorChunk::Paren: 7435 case DeclaratorChunk::Array: 7436 continue; 7437 7438 case DeclaratorChunk::Function: 7439 // Try to move past the return type to a function/block/member 7440 // function pointer. 7441 if (DeclaratorChunk *dest = maybeMovePastReturnType( 7442 declarator, i, 7443 /*onlyBlockPointers=*/false)) { 7444 return moveToChunk(*dest, true); 7445 } 7446 7447 return false; 7448 7449 // Don't walk through these. 7450 case DeclaratorChunk::Reference: 7451 case DeclaratorChunk::Pipe: 7452 return false; 7453 } 7454 } 7455 7456 return false; 7457 } 7458 7459 static Attr *getCCTypeAttr(ASTContext &Ctx, ParsedAttr &Attr) { 7460 assert(!Attr.isInvalid()); 7461 switch (Attr.getKind()) { 7462 default: 7463 llvm_unreachable("not a calling convention attribute"); 7464 case ParsedAttr::AT_CDecl: 7465 return createSimpleAttr<CDeclAttr>(Ctx, Attr); 7466 case ParsedAttr::AT_FastCall: 7467 return createSimpleAttr<FastCallAttr>(Ctx, Attr); 7468 case ParsedAttr::AT_StdCall: 7469 return createSimpleAttr<StdCallAttr>(Ctx, Attr); 7470 case ParsedAttr::AT_ThisCall: 7471 return createSimpleAttr<ThisCallAttr>(Ctx, Attr); 7472 case ParsedAttr::AT_RegCall: 7473 return createSimpleAttr<RegCallAttr>(Ctx, Attr); 7474 case ParsedAttr::AT_Pascal: 7475 return createSimpleAttr<PascalAttr>(Ctx, Attr); 7476 case ParsedAttr::AT_SwiftCall: 7477 return createSimpleAttr<SwiftCallAttr>(Ctx, Attr); 7478 case ParsedAttr::AT_SwiftAsyncCall: 7479 return createSimpleAttr<SwiftAsyncCallAttr>(Ctx, Attr); 7480 case ParsedAttr::AT_VectorCall: 7481 return createSimpleAttr<VectorCallAttr>(Ctx, Attr); 7482 case ParsedAttr::AT_AArch64VectorPcs: 7483 return createSimpleAttr<AArch64VectorPcsAttr>(Ctx, Attr); 7484 case ParsedAttr::AT_AArch64SVEPcs: 7485 return createSimpleAttr<AArch64SVEPcsAttr>(Ctx, Attr); 7486 case ParsedAttr::AT_AMDGPUKernelCall: 7487 return createSimpleAttr<AMDGPUKernelCallAttr>(Ctx, Attr); 7488 case ParsedAttr::AT_Pcs: { 7489 // The attribute may have had a fixit applied where we treated an 7490 // identifier as a string literal. The contents of the string are valid, 7491 // but the form may not be. 7492 StringRef Str; 7493 if (Attr.isArgExpr(0)) 7494 Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString(); 7495 else 7496 Str = Attr.getArgAsIdent(0)->Ident->getName(); 7497 PcsAttr::PCSType Type; 7498 if (!PcsAttr::ConvertStrToPCSType(Str, Type)) 7499 llvm_unreachable("already validated the attribute"); 7500 return ::new (Ctx) PcsAttr(Ctx, Attr, Type); 7501 } 7502 case ParsedAttr::AT_IntelOclBicc: 7503 return createSimpleAttr<IntelOclBiccAttr>(Ctx, Attr); 7504 case ParsedAttr::AT_MSABI: 7505 return createSimpleAttr<MSABIAttr>(Ctx, Attr); 7506 case ParsedAttr::AT_SysVABI: 7507 return createSimpleAttr<SysVABIAttr>(Ctx, Attr); 7508 case ParsedAttr::AT_PreserveMost: 7509 return createSimpleAttr<PreserveMostAttr>(Ctx, Attr); 7510 case ParsedAttr::AT_PreserveAll: 7511 return createSimpleAttr<PreserveAllAttr>(Ctx, Attr); 7512 } 7513 llvm_unreachable("unexpected attribute kind!"); 7514 } 7515 7516 /// Process an individual function attribute. Returns true to 7517 /// indicate that the attribute was handled, false if it wasn't. 7518 static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr, 7519 QualType &type) { 7520 Sema &S = state.getSema(); 7521 7522 FunctionTypeUnwrapper unwrapped(S, type); 7523 7524 if (attr.getKind() == ParsedAttr::AT_NoReturn) { 7525 if (S.CheckAttrNoArgs(attr)) 7526 return true; 7527 7528 // Delay if this is not a function type. 7529 if (!unwrapped.isFunctionType()) 7530 return false; 7531 7532 // Otherwise we can process right away. 7533 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true); 7534 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 7535 return true; 7536 } 7537 7538 if (attr.getKind() == ParsedAttr::AT_CmseNSCall) { 7539 // Delay if this is not a function type. 7540 if (!unwrapped.isFunctionType()) 7541 return false; 7542 7543 // Ignore if we don't have CMSE enabled. 7544 if (!S.getLangOpts().Cmse) { 7545 S.Diag(attr.getLoc(), diag::warn_attribute_ignored) << attr; 7546 attr.setInvalid(); 7547 return true; 7548 } 7549 7550 // Otherwise we can process right away. 7551 FunctionType::ExtInfo EI = 7552 unwrapped.get()->getExtInfo().withCmseNSCall(true); 7553 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 7554 return true; 7555 } 7556 7557 // ns_returns_retained is not always a type attribute, but if we got 7558 // here, we're treating it as one right now. 7559 if (attr.getKind() == ParsedAttr::AT_NSReturnsRetained) { 7560 if (attr.getNumArgs()) return true; 7561 7562 // Delay if this is not a function type. 7563 if (!unwrapped.isFunctionType()) 7564 return false; 7565 7566 // Check whether the return type is reasonable. 7567 if (S.checkNSReturnsRetainedReturnType(attr.getLoc(), 7568 unwrapped.get()->getReturnType())) 7569 return true; 7570 7571 // Only actually change the underlying type in ARC builds. 7572 QualType origType = type; 7573 if (state.getSema().getLangOpts().ObjCAutoRefCount) { 7574 FunctionType::ExtInfo EI 7575 = unwrapped.get()->getExtInfo().withProducesResult(true); 7576 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 7577 } 7578 type = state.getAttributedType( 7579 createSimpleAttr<NSReturnsRetainedAttr>(S.Context, attr), 7580 origType, type); 7581 return true; 7582 } 7583 7584 if (attr.getKind() == ParsedAttr::AT_AnyX86NoCallerSavedRegisters) { 7585 if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr)) 7586 return true; 7587 7588 // Delay if this is not a function type. 7589 if (!unwrapped.isFunctionType()) 7590 return false; 7591 7592 FunctionType::ExtInfo EI = 7593 unwrapped.get()->getExtInfo().withNoCallerSavedRegs(true); 7594 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 7595 return true; 7596 } 7597 7598 if (attr.getKind() == ParsedAttr::AT_AnyX86NoCfCheck) { 7599 if (!S.getLangOpts().CFProtectionBranch) { 7600 S.Diag(attr.getLoc(), diag::warn_nocf_check_attribute_ignored); 7601 attr.setInvalid(); 7602 return true; 7603 } 7604 7605 if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr)) 7606 return true; 7607 7608 // If this is not a function type, warning will be asserted by subject 7609 // check. 7610 if (!unwrapped.isFunctionType()) 7611 return true; 7612 7613 FunctionType::ExtInfo EI = 7614 unwrapped.get()->getExtInfo().withNoCfCheck(true); 7615 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 7616 return true; 7617 } 7618 7619 if (attr.getKind() == ParsedAttr::AT_Regparm) { 7620 unsigned value; 7621 if (S.CheckRegparmAttr(attr, value)) 7622 return true; 7623 7624 // Delay if this is not a function type. 7625 if (!unwrapped.isFunctionType()) 7626 return false; 7627 7628 // Diagnose regparm with fastcall. 7629 const FunctionType *fn = unwrapped.get(); 7630 CallingConv CC = fn->getCallConv(); 7631 if (CC == CC_X86FastCall) { 7632 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 7633 << FunctionType::getNameForCallConv(CC) 7634 << "regparm"; 7635 attr.setInvalid(); 7636 return true; 7637 } 7638 7639 FunctionType::ExtInfo EI = 7640 unwrapped.get()->getExtInfo().withRegParm(value); 7641 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 7642 return true; 7643 } 7644 7645 if (attr.getKind() == ParsedAttr::AT_NoThrow) { 7646 // Delay if this is not a function type. 7647 if (!unwrapped.isFunctionType()) 7648 return false; 7649 7650 if (S.CheckAttrNoArgs(attr)) { 7651 attr.setInvalid(); 7652 return true; 7653 } 7654 7655 // Otherwise we can process right away. 7656 auto *Proto = unwrapped.get()->castAs<FunctionProtoType>(); 7657 7658 // MSVC ignores nothrow if it is in conflict with an explicit exception 7659 // specification. 7660 if (Proto->hasExceptionSpec()) { 7661 switch (Proto->getExceptionSpecType()) { 7662 case EST_None: 7663 llvm_unreachable("This doesn't have an exception spec!"); 7664 7665 case EST_DynamicNone: 7666 case EST_BasicNoexcept: 7667 case EST_NoexceptTrue: 7668 case EST_NoThrow: 7669 // Exception spec doesn't conflict with nothrow, so don't warn. 7670 LLVM_FALLTHROUGH; 7671 case EST_Unparsed: 7672 case EST_Uninstantiated: 7673 case EST_DependentNoexcept: 7674 case EST_Unevaluated: 7675 // We don't have enough information to properly determine if there is a 7676 // conflict, so suppress the warning. 7677 break; 7678 case EST_Dynamic: 7679 case EST_MSAny: 7680 case EST_NoexceptFalse: 7681 S.Diag(attr.getLoc(), diag::warn_nothrow_attribute_ignored); 7682 break; 7683 } 7684 return true; 7685 } 7686 7687 type = unwrapped.wrap( 7688 S, S.Context 7689 .getFunctionTypeWithExceptionSpec( 7690 QualType{Proto, 0}, 7691 FunctionProtoType::ExceptionSpecInfo{EST_NoThrow}) 7692 ->getAs<FunctionType>()); 7693 return true; 7694 } 7695 7696 // Delay if the type didn't work out to a function. 7697 if (!unwrapped.isFunctionType()) return false; 7698 7699 // Otherwise, a calling convention. 7700 CallingConv CC; 7701 if (S.CheckCallingConvAttr(attr, CC)) 7702 return true; 7703 7704 const FunctionType *fn = unwrapped.get(); 7705 CallingConv CCOld = fn->getCallConv(); 7706 Attr *CCAttr = getCCTypeAttr(S.Context, attr); 7707 7708 if (CCOld != CC) { 7709 // Error out on when there's already an attribute on the type 7710 // and the CCs don't match. 7711 if (S.getCallingConvAttributedType(type)) { 7712 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 7713 << FunctionType::getNameForCallConv(CC) 7714 << FunctionType::getNameForCallConv(CCOld); 7715 attr.setInvalid(); 7716 return true; 7717 } 7718 } 7719 7720 // Diagnose use of variadic functions with calling conventions that 7721 // don't support them (e.g. because they're callee-cleanup). 7722 // We delay warning about this on unprototyped function declarations 7723 // until after redeclaration checking, just in case we pick up a 7724 // prototype that way. And apparently we also "delay" warning about 7725 // unprototyped function types in general, despite not necessarily having 7726 // much ability to diagnose it later. 7727 if (!supportsVariadicCall(CC)) { 7728 const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn); 7729 if (FnP && FnP->isVariadic()) { 7730 // stdcall and fastcall are ignored with a warning for GCC and MS 7731 // compatibility. 7732 if (CC == CC_X86StdCall || CC == CC_X86FastCall) 7733 return S.Diag(attr.getLoc(), diag::warn_cconv_unsupported) 7734 << FunctionType::getNameForCallConv(CC) 7735 << (int)Sema::CallingConventionIgnoredReason::VariadicFunction; 7736 7737 attr.setInvalid(); 7738 return S.Diag(attr.getLoc(), diag::err_cconv_varargs) 7739 << FunctionType::getNameForCallConv(CC); 7740 } 7741 } 7742 7743 // Also diagnose fastcall with regparm. 7744 if (CC == CC_X86FastCall && fn->getHasRegParm()) { 7745 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 7746 << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall); 7747 attr.setInvalid(); 7748 return true; 7749 } 7750 7751 // Modify the CC from the wrapped function type, wrap it all back, and then 7752 // wrap the whole thing in an AttributedType as written. The modified type 7753 // might have a different CC if we ignored the attribute. 7754 QualType Equivalent; 7755 if (CCOld == CC) { 7756 Equivalent = type; 7757 } else { 7758 auto EI = unwrapped.get()->getExtInfo().withCallingConv(CC); 7759 Equivalent = 7760 unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 7761 } 7762 type = state.getAttributedType(CCAttr, type, Equivalent); 7763 return true; 7764 } 7765 7766 bool Sema::hasExplicitCallingConv(QualType T) { 7767 const AttributedType *AT; 7768 7769 // Stop if we'd be stripping off a typedef sugar node to reach the 7770 // AttributedType. 7771 while ((AT = T->getAs<AttributedType>()) && 7772 AT->getAs<TypedefType>() == T->getAs<TypedefType>()) { 7773 if (AT->isCallingConv()) 7774 return true; 7775 T = AT->getModifiedType(); 7776 } 7777 return false; 7778 } 7779 7780 void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor, 7781 SourceLocation Loc) { 7782 FunctionTypeUnwrapper Unwrapped(*this, T); 7783 const FunctionType *FT = Unwrapped.get(); 7784 bool IsVariadic = (isa<FunctionProtoType>(FT) && 7785 cast<FunctionProtoType>(FT)->isVariadic()); 7786 CallingConv CurCC = FT->getCallConv(); 7787 CallingConv ToCC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic); 7788 7789 if (CurCC == ToCC) 7790 return; 7791 7792 // MS compiler ignores explicit calling convention attributes on structors. We 7793 // should do the same. 7794 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) { 7795 // Issue a warning on ignored calling convention -- except of __stdcall. 7796 // Again, this is what MS compiler does. 7797 if (CurCC != CC_X86StdCall) 7798 Diag(Loc, diag::warn_cconv_unsupported) 7799 << FunctionType::getNameForCallConv(CurCC) 7800 << (int)Sema::CallingConventionIgnoredReason::ConstructorDestructor; 7801 // Default adjustment. 7802 } else { 7803 // Only adjust types with the default convention. For example, on Windows 7804 // we should adjust a __cdecl type to __thiscall for instance methods, and a 7805 // __thiscall type to __cdecl for static methods. 7806 CallingConv DefaultCC = 7807 Context.getDefaultCallingConvention(IsVariadic, IsStatic); 7808 7809 if (CurCC != DefaultCC || DefaultCC == ToCC) 7810 return; 7811 7812 if (hasExplicitCallingConv(T)) 7813 return; 7814 } 7815 7816 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC)); 7817 QualType Wrapped = Unwrapped.wrap(*this, FT); 7818 T = Context.getAdjustedType(T, Wrapped); 7819 } 7820 7821 /// HandleVectorSizeAttribute - this attribute is only applicable to integral 7822 /// and float scalars, although arrays, pointers, and function return values are 7823 /// allowed in conjunction with this construct. Aggregates with this attribute 7824 /// are invalid, even if they are of the same size as a corresponding scalar. 7825 /// The raw attribute should contain precisely 1 argument, the vector size for 7826 /// the variable, measured in bytes. If curType and rawAttr are well formed, 7827 /// this routine will return a new vector type. 7828 static void HandleVectorSizeAttr(QualType &CurType, const ParsedAttr &Attr, 7829 Sema &S) { 7830 // Check the attribute arguments. 7831 if (Attr.getNumArgs() != 1) { 7832 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr 7833 << 1; 7834 Attr.setInvalid(); 7835 return; 7836 } 7837 7838 Expr *SizeExpr = Attr.getArgAsExpr(0); 7839 QualType T = S.BuildVectorType(CurType, SizeExpr, Attr.getLoc()); 7840 if (!T.isNull()) 7841 CurType = T; 7842 else 7843 Attr.setInvalid(); 7844 } 7845 7846 /// Process the OpenCL-like ext_vector_type attribute when it occurs on 7847 /// a type. 7848 static void HandleExtVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr, 7849 Sema &S) { 7850 // check the attribute arguments. 7851 if (Attr.getNumArgs() != 1) { 7852 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr 7853 << 1; 7854 return; 7855 } 7856 7857 Expr *SizeExpr = Attr.getArgAsExpr(0); 7858 QualType T = S.BuildExtVectorType(CurType, SizeExpr, Attr.getLoc()); 7859 if (!T.isNull()) 7860 CurType = T; 7861 } 7862 7863 static bool isPermittedNeonBaseType(QualType &Ty, 7864 VectorType::VectorKind VecKind, Sema &S) { 7865 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 7866 if (!BTy) 7867 return false; 7868 7869 llvm::Triple Triple = S.Context.getTargetInfo().getTriple(); 7870 7871 // Signed poly is mathematically wrong, but has been baked into some ABIs by 7872 // now. 7873 bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 || 7874 Triple.getArch() == llvm::Triple::aarch64_32 || 7875 Triple.getArch() == llvm::Triple::aarch64_be; 7876 if (VecKind == VectorType::NeonPolyVector) { 7877 if (IsPolyUnsigned) { 7878 // AArch64 polynomial vectors are unsigned. 7879 return BTy->getKind() == BuiltinType::UChar || 7880 BTy->getKind() == BuiltinType::UShort || 7881 BTy->getKind() == BuiltinType::ULong || 7882 BTy->getKind() == BuiltinType::ULongLong; 7883 } else { 7884 // AArch32 polynomial vectors are signed. 7885 return BTy->getKind() == BuiltinType::SChar || 7886 BTy->getKind() == BuiltinType::Short || 7887 BTy->getKind() == BuiltinType::LongLong; 7888 } 7889 } 7890 7891 // Non-polynomial vector types: the usual suspects are allowed, as well as 7892 // float64_t on AArch64. 7893 if ((Triple.isArch64Bit() || Triple.getArch() == llvm::Triple::aarch64_32) && 7894 BTy->getKind() == BuiltinType::Double) 7895 return true; 7896 7897 return BTy->getKind() == BuiltinType::SChar || 7898 BTy->getKind() == BuiltinType::UChar || 7899 BTy->getKind() == BuiltinType::Short || 7900 BTy->getKind() == BuiltinType::UShort || 7901 BTy->getKind() == BuiltinType::Int || 7902 BTy->getKind() == BuiltinType::UInt || 7903 BTy->getKind() == BuiltinType::Long || 7904 BTy->getKind() == BuiltinType::ULong || 7905 BTy->getKind() == BuiltinType::LongLong || 7906 BTy->getKind() == BuiltinType::ULongLong || 7907 BTy->getKind() == BuiltinType::Float || 7908 BTy->getKind() == BuiltinType::Half || 7909 BTy->getKind() == BuiltinType::BFloat16; 7910 } 7911 7912 static bool verifyValidIntegerConstantExpr(Sema &S, const ParsedAttr &Attr, 7913 llvm::APSInt &Result) { 7914 const auto *AttrExpr = Attr.getArgAsExpr(0); 7915 if (!AttrExpr->isTypeDependent()) { 7916 if (Optional<llvm::APSInt> Res = 7917 AttrExpr->getIntegerConstantExpr(S.Context)) { 7918 Result = *Res; 7919 return true; 7920 } 7921 } 7922 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) 7923 << Attr << AANT_ArgumentIntegerConstant << AttrExpr->getSourceRange(); 7924 Attr.setInvalid(); 7925 return false; 7926 } 7927 7928 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and 7929 /// "neon_polyvector_type" attributes are used to create vector types that 7930 /// are mangled according to ARM's ABI. Otherwise, these types are identical 7931 /// to those created with the "vector_size" attribute. Unlike "vector_size" 7932 /// the argument to these Neon attributes is the number of vector elements, 7933 /// not the vector size in bytes. The vector width and element type must 7934 /// match one of the standard Neon vector types. 7935 static void HandleNeonVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr, 7936 Sema &S, VectorType::VectorKind VecKind) { 7937 // Target must have NEON (or MVE, whose vectors are similar enough 7938 // not to need a separate attribute) 7939 if (!S.Context.getTargetInfo().hasFeature("neon") && 7940 !S.Context.getTargetInfo().hasFeature("mve")) { 7941 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) 7942 << Attr << "'neon' or 'mve'"; 7943 Attr.setInvalid(); 7944 return; 7945 } 7946 // Check the attribute arguments. 7947 if (Attr.getNumArgs() != 1) { 7948 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr 7949 << 1; 7950 Attr.setInvalid(); 7951 return; 7952 } 7953 // The number of elements must be an ICE. 7954 llvm::APSInt numEltsInt(32); 7955 if (!verifyValidIntegerConstantExpr(S, Attr, numEltsInt)) 7956 return; 7957 7958 // Only certain element types are supported for Neon vectors. 7959 if (!isPermittedNeonBaseType(CurType, VecKind, S)) { 7960 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType; 7961 Attr.setInvalid(); 7962 return; 7963 } 7964 7965 // The total size of the vector must be 64 or 128 bits. 7966 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType)); 7967 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue()); 7968 unsigned vecSize = typeSize * numElts; 7969 if (vecSize != 64 && vecSize != 128) { 7970 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType; 7971 Attr.setInvalid(); 7972 return; 7973 } 7974 7975 CurType = S.Context.getVectorType(CurType, numElts, VecKind); 7976 } 7977 7978 /// HandleArmSveVectorBitsTypeAttr - The "arm_sve_vector_bits" attribute is 7979 /// used to create fixed-length versions of sizeless SVE types defined by 7980 /// the ACLE, such as svint32_t and svbool_t. 7981 static void HandleArmSveVectorBitsTypeAttr(QualType &CurType, ParsedAttr &Attr, 7982 Sema &S) { 7983 // Target must have SVE. 7984 if (!S.Context.getTargetInfo().hasFeature("sve")) { 7985 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr << "'sve'"; 7986 Attr.setInvalid(); 7987 return; 7988 } 7989 7990 // Attribute is unsupported if '-msve-vector-bits=<bits>' isn't specified, or 7991 // if <bits>+ syntax is used. 7992 if (!S.getLangOpts().VScaleMin || 7993 S.getLangOpts().VScaleMin != S.getLangOpts().VScaleMax) { 7994 S.Diag(Attr.getLoc(), diag::err_attribute_arm_feature_sve_bits_unsupported) 7995 << Attr; 7996 Attr.setInvalid(); 7997 return; 7998 } 7999 8000 // Check the attribute arguments. 8001 if (Attr.getNumArgs() != 1) { 8002 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 8003 << Attr << 1; 8004 Attr.setInvalid(); 8005 return; 8006 } 8007 8008 // The vector size must be an integer constant expression. 8009 llvm::APSInt SveVectorSizeInBits(32); 8010 if (!verifyValidIntegerConstantExpr(S, Attr, SveVectorSizeInBits)) 8011 return; 8012 8013 unsigned VecSize = static_cast<unsigned>(SveVectorSizeInBits.getZExtValue()); 8014 8015 // The attribute vector size must match -msve-vector-bits. 8016 if (VecSize != S.getLangOpts().VScaleMin * 128) { 8017 S.Diag(Attr.getLoc(), diag::err_attribute_bad_sve_vector_size) 8018 << VecSize << S.getLangOpts().VScaleMin * 128; 8019 Attr.setInvalid(); 8020 return; 8021 } 8022 8023 // Attribute can only be attached to a single SVE vector or predicate type. 8024 if (!CurType->isVLSTBuiltinType()) { 8025 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_sve_type) 8026 << Attr << CurType; 8027 Attr.setInvalid(); 8028 return; 8029 } 8030 8031 const auto *BT = CurType->castAs<BuiltinType>(); 8032 8033 QualType EltType = CurType->getSveEltType(S.Context); 8034 unsigned TypeSize = S.Context.getTypeSize(EltType); 8035 VectorType::VectorKind VecKind = VectorType::SveFixedLengthDataVector; 8036 if (BT->getKind() == BuiltinType::SveBool) { 8037 // Predicates are represented as i8. 8038 VecSize /= S.Context.getCharWidth() * S.Context.getCharWidth(); 8039 VecKind = VectorType::SveFixedLengthPredicateVector; 8040 } else 8041 VecSize /= TypeSize; 8042 CurType = S.Context.getVectorType(EltType, VecSize, VecKind); 8043 } 8044 8045 static void HandleArmMveStrictPolymorphismAttr(TypeProcessingState &State, 8046 QualType &CurType, 8047 ParsedAttr &Attr) { 8048 const VectorType *VT = dyn_cast<VectorType>(CurType); 8049 if (!VT || VT->getVectorKind() != VectorType::NeonVector) { 8050 State.getSema().Diag(Attr.getLoc(), 8051 diag::err_attribute_arm_mve_polymorphism); 8052 Attr.setInvalid(); 8053 return; 8054 } 8055 8056 CurType = 8057 State.getAttributedType(createSimpleAttr<ArmMveStrictPolymorphismAttr>( 8058 State.getSema().Context, Attr), 8059 CurType, CurType); 8060 } 8061 8062 /// Handle OpenCL Access Qualifier Attribute. 8063 static void HandleOpenCLAccessAttr(QualType &CurType, const ParsedAttr &Attr, 8064 Sema &S) { 8065 // OpenCL v2.0 s6.6 - Access qualifier can be used only for image and pipe type. 8066 if (!(CurType->isImageType() || CurType->isPipeType())) { 8067 S.Diag(Attr.getLoc(), diag::err_opencl_invalid_access_qualifier); 8068 Attr.setInvalid(); 8069 return; 8070 } 8071 8072 if (const TypedefType* TypedefTy = CurType->getAs<TypedefType>()) { 8073 QualType BaseTy = TypedefTy->desugar(); 8074 8075 std::string PrevAccessQual; 8076 if (BaseTy->isPipeType()) { 8077 if (TypedefTy->getDecl()->hasAttr<OpenCLAccessAttr>()) { 8078 OpenCLAccessAttr *Attr = 8079 TypedefTy->getDecl()->getAttr<OpenCLAccessAttr>(); 8080 PrevAccessQual = Attr->getSpelling(); 8081 } else { 8082 PrevAccessQual = "read_only"; 8083 } 8084 } else if (const BuiltinType* ImgType = BaseTy->getAs<BuiltinType>()) { 8085 8086 switch (ImgType->getKind()) { 8087 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 8088 case BuiltinType::Id: \ 8089 PrevAccessQual = #Access; \ 8090 break; 8091 #include "clang/Basic/OpenCLImageTypes.def" 8092 default: 8093 llvm_unreachable("Unable to find corresponding image type."); 8094 } 8095 } else { 8096 llvm_unreachable("unexpected type"); 8097 } 8098 StringRef AttrName = Attr.getAttrName()->getName(); 8099 if (PrevAccessQual == AttrName.ltrim("_")) { 8100 // Duplicated qualifiers 8101 S.Diag(Attr.getLoc(), diag::warn_duplicate_declspec) 8102 << AttrName << Attr.getRange(); 8103 } else { 8104 // Contradicting qualifiers 8105 S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers); 8106 } 8107 8108 S.Diag(TypedefTy->getDecl()->getBeginLoc(), 8109 diag::note_opencl_typedef_access_qualifier) << PrevAccessQual; 8110 } else if (CurType->isPipeType()) { 8111 if (Attr.getSemanticSpelling() == OpenCLAccessAttr::Keyword_write_only) { 8112 QualType ElemType = CurType->castAs<PipeType>()->getElementType(); 8113 CurType = S.Context.getWritePipeType(ElemType); 8114 } 8115 } 8116 } 8117 8118 /// HandleMatrixTypeAttr - "matrix_type" attribute, like ext_vector_type 8119 static void HandleMatrixTypeAttr(QualType &CurType, const ParsedAttr &Attr, 8120 Sema &S) { 8121 if (!S.getLangOpts().MatrixTypes) { 8122 S.Diag(Attr.getLoc(), diag::err_builtin_matrix_disabled); 8123 return; 8124 } 8125 8126 if (Attr.getNumArgs() != 2) { 8127 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 8128 << Attr << 2; 8129 return; 8130 } 8131 8132 Expr *RowsExpr = Attr.getArgAsExpr(0); 8133 Expr *ColsExpr = Attr.getArgAsExpr(1); 8134 QualType T = S.BuildMatrixType(CurType, RowsExpr, ColsExpr, Attr.getLoc()); 8135 if (!T.isNull()) 8136 CurType = T; 8137 } 8138 8139 static void HandleLifetimeBoundAttr(TypeProcessingState &State, 8140 QualType &CurType, 8141 ParsedAttr &Attr) { 8142 if (State.getDeclarator().isDeclarationOfFunction()) { 8143 CurType = State.getAttributedType( 8144 createSimpleAttr<LifetimeBoundAttr>(State.getSema().Context, Attr), 8145 CurType, CurType); 8146 } 8147 } 8148 8149 static bool isAddressSpaceKind(const ParsedAttr &attr) { 8150 auto attrKind = attr.getKind(); 8151 8152 return attrKind == ParsedAttr::AT_AddressSpace || 8153 attrKind == ParsedAttr::AT_OpenCLPrivateAddressSpace || 8154 attrKind == ParsedAttr::AT_OpenCLGlobalAddressSpace || 8155 attrKind == ParsedAttr::AT_OpenCLGlobalDeviceAddressSpace || 8156 attrKind == ParsedAttr::AT_OpenCLGlobalHostAddressSpace || 8157 attrKind == ParsedAttr::AT_OpenCLLocalAddressSpace || 8158 attrKind == ParsedAttr::AT_OpenCLConstantAddressSpace || 8159 attrKind == ParsedAttr::AT_OpenCLGenericAddressSpace; 8160 } 8161 8162 static void processTypeAttrs(TypeProcessingState &state, QualType &type, 8163 TypeAttrLocation TAL, 8164 const ParsedAttributesView &attrs) { 8165 8166 state.setParsedNoDeref(false); 8167 if (attrs.empty()) 8168 return; 8169 8170 // Scan through and apply attributes to this type where it makes sense. Some 8171 // attributes (such as __address_space__, __vector_size__, etc) apply to the 8172 // type, but others can be present in the type specifiers even though they 8173 // apply to the decl. Here we apply type attributes and ignore the rest. 8174 8175 // This loop modifies the list pretty frequently, but we still need to make 8176 // sure we visit every element once. Copy the attributes list, and iterate 8177 // over that. 8178 ParsedAttributesView AttrsCopy{attrs}; 8179 for (ParsedAttr &attr : AttrsCopy) { 8180 8181 // Skip attributes that were marked to be invalid. 8182 if (attr.isInvalid()) 8183 continue; 8184 8185 if (attr.isStandardAttributeSyntax()) { 8186 // [[gnu::...]] attributes are treated as declaration attributes, so may 8187 // not appertain to a DeclaratorChunk. If we handle them as type 8188 // attributes, accept them in that position and diagnose the GCC 8189 // incompatibility. 8190 if (attr.isGNUScope()) { 8191 bool IsTypeAttr = attr.isTypeAttr(); 8192 if (TAL == TAL_DeclChunk) { 8193 state.getSema().Diag(attr.getLoc(), 8194 IsTypeAttr 8195 ? diag::warn_gcc_ignores_type_attr 8196 : diag::warn_cxx11_gnu_attribute_on_type) 8197 << attr; 8198 if (!IsTypeAttr) 8199 continue; 8200 } 8201 } else if (TAL != TAL_DeclChunk && !isAddressSpaceKind(attr)) { 8202 // Otherwise, only consider type processing for a C++11 attribute if 8203 // it's actually been applied to a type. 8204 // We also allow C++11 address_space and 8205 // OpenCL language address space attributes to pass through. 8206 continue; 8207 } 8208 } 8209 8210 // If this is an attribute we can handle, do so now, 8211 // otherwise, add it to the FnAttrs list for rechaining. 8212 switch (attr.getKind()) { 8213 default: 8214 // A [[]] attribute on a declarator chunk must appertain to a type. 8215 if (attr.isStandardAttributeSyntax() && TAL == TAL_DeclChunk) { 8216 state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr) 8217 << attr; 8218 attr.setUsedAsTypeAttr(); 8219 } 8220 break; 8221 8222 case ParsedAttr::UnknownAttribute: 8223 if (attr.isStandardAttributeSyntax() && TAL == TAL_DeclChunk) 8224 state.getSema().Diag(attr.getLoc(), 8225 diag::warn_unknown_attribute_ignored) 8226 << attr << attr.getRange(); 8227 break; 8228 8229 case ParsedAttr::IgnoredAttribute: 8230 break; 8231 8232 case ParsedAttr::AT_BTFTypeTag: 8233 HandleBTFTypeTagAttribute(type, attr, state); 8234 attr.setUsedAsTypeAttr(); 8235 break; 8236 8237 case ParsedAttr::AT_MayAlias: 8238 // FIXME: This attribute needs to actually be handled, but if we ignore 8239 // it it breaks large amounts of Linux software. 8240 attr.setUsedAsTypeAttr(); 8241 break; 8242 case ParsedAttr::AT_OpenCLPrivateAddressSpace: 8243 case ParsedAttr::AT_OpenCLGlobalAddressSpace: 8244 case ParsedAttr::AT_OpenCLGlobalDeviceAddressSpace: 8245 case ParsedAttr::AT_OpenCLGlobalHostAddressSpace: 8246 case ParsedAttr::AT_OpenCLLocalAddressSpace: 8247 case ParsedAttr::AT_OpenCLConstantAddressSpace: 8248 case ParsedAttr::AT_OpenCLGenericAddressSpace: 8249 case ParsedAttr::AT_AddressSpace: 8250 HandleAddressSpaceTypeAttribute(type, attr, state); 8251 attr.setUsedAsTypeAttr(); 8252 break; 8253 OBJC_POINTER_TYPE_ATTRS_CASELIST: 8254 if (!handleObjCPointerTypeAttr(state, attr, type)) 8255 distributeObjCPointerTypeAttr(state, attr, type); 8256 attr.setUsedAsTypeAttr(); 8257 break; 8258 case ParsedAttr::AT_VectorSize: 8259 HandleVectorSizeAttr(type, attr, state.getSema()); 8260 attr.setUsedAsTypeAttr(); 8261 break; 8262 case ParsedAttr::AT_ExtVectorType: 8263 HandleExtVectorTypeAttr(type, attr, state.getSema()); 8264 attr.setUsedAsTypeAttr(); 8265 break; 8266 case ParsedAttr::AT_NeonVectorType: 8267 HandleNeonVectorTypeAttr(type, attr, state.getSema(), 8268 VectorType::NeonVector); 8269 attr.setUsedAsTypeAttr(); 8270 break; 8271 case ParsedAttr::AT_NeonPolyVectorType: 8272 HandleNeonVectorTypeAttr(type, attr, state.getSema(), 8273 VectorType::NeonPolyVector); 8274 attr.setUsedAsTypeAttr(); 8275 break; 8276 case ParsedAttr::AT_ArmSveVectorBits: 8277 HandleArmSveVectorBitsTypeAttr(type, attr, state.getSema()); 8278 attr.setUsedAsTypeAttr(); 8279 break; 8280 case ParsedAttr::AT_ArmMveStrictPolymorphism: { 8281 HandleArmMveStrictPolymorphismAttr(state, type, attr); 8282 attr.setUsedAsTypeAttr(); 8283 break; 8284 } 8285 case ParsedAttr::AT_OpenCLAccess: 8286 HandleOpenCLAccessAttr(type, attr, state.getSema()); 8287 attr.setUsedAsTypeAttr(); 8288 break; 8289 case ParsedAttr::AT_LifetimeBound: 8290 if (TAL == TAL_DeclChunk) 8291 HandleLifetimeBoundAttr(state, type, attr); 8292 break; 8293 8294 case ParsedAttr::AT_NoDeref: { 8295 ASTContext &Ctx = state.getSema().Context; 8296 type = state.getAttributedType(createSimpleAttr<NoDerefAttr>(Ctx, attr), 8297 type, type); 8298 attr.setUsedAsTypeAttr(); 8299 state.setParsedNoDeref(true); 8300 break; 8301 } 8302 8303 case ParsedAttr::AT_MatrixType: 8304 HandleMatrixTypeAttr(type, attr, state.getSema()); 8305 attr.setUsedAsTypeAttr(); 8306 break; 8307 8308 MS_TYPE_ATTRS_CASELIST: 8309 if (!handleMSPointerTypeQualifierAttr(state, attr, type)) 8310 attr.setUsedAsTypeAttr(); 8311 break; 8312 8313 8314 NULLABILITY_TYPE_ATTRS_CASELIST: 8315 // Either add nullability here or try to distribute it. We 8316 // don't want to distribute the nullability specifier past any 8317 // dependent type, because that complicates the user model. 8318 if (type->canHaveNullability() || type->isDependentType() || 8319 type->isArrayType() || 8320 !distributeNullabilityTypeAttr(state, type, attr)) { 8321 unsigned endIndex; 8322 if (TAL == TAL_DeclChunk) 8323 endIndex = state.getCurrentChunkIndex(); 8324 else 8325 endIndex = state.getDeclarator().getNumTypeObjects(); 8326 bool allowOnArrayType = 8327 state.getDeclarator().isPrototypeContext() && 8328 !hasOuterPointerLikeChunk(state.getDeclarator(), endIndex); 8329 if (checkNullabilityTypeSpecifier( 8330 state, 8331 type, 8332 attr, 8333 allowOnArrayType)) { 8334 attr.setInvalid(); 8335 } 8336 8337 attr.setUsedAsTypeAttr(); 8338 } 8339 break; 8340 8341 case ParsedAttr::AT_ObjCKindOf: 8342 // '__kindof' must be part of the decl-specifiers. 8343 switch (TAL) { 8344 case TAL_DeclSpec: 8345 break; 8346 8347 case TAL_DeclChunk: 8348 case TAL_DeclName: 8349 state.getSema().Diag(attr.getLoc(), 8350 diag::err_objc_kindof_wrong_position) 8351 << FixItHint::CreateRemoval(attr.getLoc()) 8352 << FixItHint::CreateInsertion( 8353 state.getDeclarator().getDeclSpec().getBeginLoc(), 8354 "__kindof "); 8355 break; 8356 } 8357 8358 // Apply it regardless. 8359 if (checkObjCKindOfType(state, type, attr)) 8360 attr.setInvalid(); 8361 break; 8362 8363 case ParsedAttr::AT_NoThrow: 8364 // Exception Specifications aren't generally supported in C mode throughout 8365 // clang, so revert to attribute-based handling for C. 8366 if (!state.getSema().getLangOpts().CPlusPlus) 8367 break; 8368 LLVM_FALLTHROUGH; 8369 FUNCTION_TYPE_ATTRS_CASELIST: 8370 attr.setUsedAsTypeAttr(); 8371 8372 // Never process function type attributes as part of the 8373 // declaration-specifiers. 8374 if (TAL == TAL_DeclSpec) 8375 distributeFunctionTypeAttrFromDeclSpec(state, attr, type); 8376 8377 // Otherwise, handle the possible delays. 8378 else if (!handleFunctionTypeAttr(state, attr, type)) 8379 distributeFunctionTypeAttr(state, attr, type); 8380 break; 8381 case ParsedAttr::AT_AcquireHandle: { 8382 if (!type->isFunctionType()) 8383 return; 8384 8385 if (attr.getNumArgs() != 1) { 8386 state.getSema().Diag(attr.getLoc(), 8387 diag::err_attribute_wrong_number_arguments) 8388 << attr << 1; 8389 attr.setInvalid(); 8390 return; 8391 } 8392 8393 StringRef HandleType; 8394 if (!state.getSema().checkStringLiteralArgumentAttr(attr, 0, HandleType)) 8395 return; 8396 type = state.getAttributedType( 8397 AcquireHandleAttr::Create(state.getSema().Context, HandleType, attr), 8398 type, type); 8399 attr.setUsedAsTypeAttr(); 8400 break; 8401 } 8402 } 8403 8404 // Handle attributes that are defined in a macro. We do not want this to be 8405 // applied to ObjC builtin attributes. 8406 if (isa<AttributedType>(type) && attr.hasMacroIdentifier() && 8407 !type.getQualifiers().hasObjCLifetime() && 8408 !type.getQualifiers().hasObjCGCAttr() && 8409 attr.getKind() != ParsedAttr::AT_ObjCGC && 8410 attr.getKind() != ParsedAttr::AT_ObjCOwnership) { 8411 const IdentifierInfo *MacroII = attr.getMacroIdentifier(); 8412 type = state.getSema().Context.getMacroQualifiedType(type, MacroII); 8413 state.setExpansionLocForMacroQualifiedType( 8414 cast<MacroQualifiedType>(type.getTypePtr()), 8415 attr.getMacroExpansionLoc()); 8416 } 8417 } 8418 } 8419 8420 void Sema::completeExprArrayBound(Expr *E) { 8421 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 8422 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 8423 if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) { 8424 auto *Def = Var->getDefinition(); 8425 if (!Def) { 8426 SourceLocation PointOfInstantiation = E->getExprLoc(); 8427 runWithSufficientStackSpace(PointOfInstantiation, [&] { 8428 InstantiateVariableDefinition(PointOfInstantiation, Var); 8429 }); 8430 Def = Var->getDefinition(); 8431 8432 // If we don't already have a point of instantiation, and we managed 8433 // to instantiate a definition, this is the point of instantiation. 8434 // Otherwise, we don't request an end-of-TU instantiation, so this is 8435 // not a point of instantiation. 8436 // FIXME: Is this really the right behavior? 8437 if (Var->getPointOfInstantiation().isInvalid() && Def) { 8438 assert(Var->getTemplateSpecializationKind() == 8439 TSK_ImplicitInstantiation && 8440 "explicit instantiation with no point of instantiation"); 8441 Var->setTemplateSpecializationKind( 8442 Var->getTemplateSpecializationKind(), PointOfInstantiation); 8443 } 8444 } 8445 8446 // Update the type to the definition's type both here and within the 8447 // expression. 8448 if (Def) { 8449 DRE->setDecl(Def); 8450 QualType T = Def->getType(); 8451 DRE->setType(T); 8452 // FIXME: Update the type on all intervening expressions. 8453 E->setType(T); 8454 } 8455 8456 // We still go on to try to complete the type independently, as it 8457 // may also require instantiations or diagnostics if it remains 8458 // incomplete. 8459 } 8460 } 8461 } 8462 } 8463 8464 QualType Sema::getCompletedType(Expr *E) { 8465 // Incomplete array types may be completed by the initializer attached to 8466 // their definitions. For static data members of class templates and for 8467 // variable templates, we need to instantiate the definition to get this 8468 // initializer and complete the type. 8469 if (E->getType()->isIncompleteArrayType()) 8470 completeExprArrayBound(E); 8471 8472 // FIXME: Are there other cases which require instantiating something other 8473 // than the type to complete the type of an expression? 8474 8475 return E->getType(); 8476 } 8477 8478 /// Ensure that the type of the given expression is complete. 8479 /// 8480 /// This routine checks whether the expression \p E has a complete type. If the 8481 /// expression refers to an instantiable construct, that instantiation is 8482 /// performed as needed to complete its type. Furthermore 8483 /// Sema::RequireCompleteType is called for the expression's type (or in the 8484 /// case of a reference type, the referred-to type). 8485 /// 8486 /// \param E The expression whose type is required to be complete. 8487 /// \param Kind Selects which completeness rules should be applied. 8488 /// \param Diagnoser The object that will emit a diagnostic if the type is 8489 /// incomplete. 8490 /// 8491 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false 8492 /// otherwise. 8493 bool Sema::RequireCompleteExprType(Expr *E, CompleteTypeKind Kind, 8494 TypeDiagnoser &Diagnoser) { 8495 return RequireCompleteType(E->getExprLoc(), getCompletedType(E), Kind, 8496 Diagnoser); 8497 } 8498 8499 bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) { 8500 BoundTypeDiagnoser<> Diagnoser(DiagID); 8501 return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser); 8502 } 8503 8504 /// Ensure that the type T is a complete type. 8505 /// 8506 /// This routine checks whether the type @p T is complete in any 8507 /// context where a complete type is required. If @p T is a complete 8508 /// type, returns false. If @p T is a class template specialization, 8509 /// this routine then attempts to perform class template 8510 /// instantiation. If instantiation fails, or if @p T is incomplete 8511 /// and cannot be completed, issues the diagnostic @p diag (giving it 8512 /// the type @p T) and returns true. 8513 /// 8514 /// @param Loc The location in the source that the incomplete type 8515 /// diagnostic should refer to. 8516 /// 8517 /// @param T The type that this routine is examining for completeness. 8518 /// 8519 /// @param Kind Selects which completeness rules should be applied. 8520 /// 8521 /// @returns @c true if @p T is incomplete and a diagnostic was emitted, 8522 /// @c false otherwise. 8523 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, 8524 CompleteTypeKind Kind, 8525 TypeDiagnoser &Diagnoser) { 8526 if (RequireCompleteTypeImpl(Loc, T, Kind, &Diagnoser)) 8527 return true; 8528 if (const TagType *Tag = T->getAs<TagType>()) { 8529 if (!Tag->getDecl()->isCompleteDefinitionRequired()) { 8530 Tag->getDecl()->setCompleteDefinitionRequired(); 8531 Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl()); 8532 } 8533 } 8534 return false; 8535 } 8536 8537 bool Sema::hasStructuralCompatLayout(Decl *D, Decl *Suggested) { 8538 llvm::DenseSet<std::pair<Decl *, Decl *>> NonEquivalentDecls; 8539 if (!Suggested) 8540 return false; 8541 8542 // FIXME: Add a specific mode for C11 6.2.7/1 in StructuralEquivalenceContext 8543 // and isolate from other C++ specific checks. 8544 StructuralEquivalenceContext Ctx( 8545 D->getASTContext(), Suggested->getASTContext(), NonEquivalentDecls, 8546 StructuralEquivalenceKind::Default, 8547 false /*StrictTypeSpelling*/, true /*Complain*/, 8548 true /*ErrorOnTagTypeMismatch*/); 8549 return Ctx.IsEquivalent(D, Suggested); 8550 } 8551 8552 /// Determine whether there is any declaration of \p D that was ever a 8553 /// definition (perhaps before module merging) and is currently visible. 8554 /// \param D The definition of the entity. 8555 /// \param Suggested Filled in with the declaration that should be made visible 8556 /// in order to provide a definition of this entity. 8557 /// \param OnlyNeedComplete If \c true, we only need the type to be complete, 8558 /// not defined. This only matters for enums with a fixed underlying 8559 /// type, since in all other cases, a type is complete if and only if it 8560 /// is defined. 8561 bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, 8562 bool OnlyNeedComplete) { 8563 // Easy case: if we don't have modules, all declarations are visible. 8564 if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility) 8565 return true; 8566 8567 // If this definition was instantiated from a template, map back to the 8568 // pattern from which it was instantiated. 8569 if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined()) { 8570 // We're in the middle of defining it; this definition should be treated 8571 // as visible. 8572 return true; 8573 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 8574 if (auto *Pattern = RD->getTemplateInstantiationPattern()) 8575 RD = Pattern; 8576 D = RD->getDefinition(); 8577 } else if (auto *ED = dyn_cast<EnumDecl>(D)) { 8578 if (auto *Pattern = ED->getTemplateInstantiationPattern()) 8579 ED = Pattern; 8580 if (OnlyNeedComplete && (ED->isFixed() || getLangOpts().MSVCCompat)) { 8581 // If the enum has a fixed underlying type, it may have been forward 8582 // declared. In -fms-compatibility, `enum Foo;` will also forward declare 8583 // the enum and assign it the underlying type of `int`. Since we're only 8584 // looking for a complete type (not a definition), any visible declaration 8585 // of it will do. 8586 *Suggested = nullptr; 8587 for (auto *Redecl : ED->redecls()) { 8588 if (isVisible(Redecl)) 8589 return true; 8590 if (Redecl->isThisDeclarationADefinition() || 8591 (Redecl->isCanonicalDecl() && !*Suggested)) 8592 *Suggested = Redecl; 8593 } 8594 return false; 8595 } 8596 D = ED->getDefinition(); 8597 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) { 8598 if (auto *Pattern = FD->getTemplateInstantiationPattern()) 8599 FD = Pattern; 8600 D = FD->getDefinition(); 8601 } else if (auto *VD = dyn_cast<VarDecl>(D)) { 8602 if (auto *Pattern = VD->getTemplateInstantiationPattern()) 8603 VD = Pattern; 8604 D = VD->getDefinition(); 8605 } 8606 assert(D && "missing definition for pattern of instantiated definition"); 8607 8608 *Suggested = D; 8609 8610 auto DefinitionIsVisible = [&] { 8611 // The (primary) definition might be in a visible module. 8612 if (isVisible(D)) 8613 return true; 8614 8615 // A visible module might have a merged definition instead. 8616 if (D->isModulePrivate() ? hasMergedDefinitionInCurrentModule(D) 8617 : hasVisibleMergedDefinition(D)) { 8618 if (CodeSynthesisContexts.empty() && 8619 !getLangOpts().ModulesLocalVisibility) { 8620 // Cache the fact that this definition is implicitly visible because 8621 // there is a visible merged definition. 8622 D->setVisibleDespiteOwningModule(); 8623 } 8624 return true; 8625 } 8626 8627 return false; 8628 }; 8629 8630 if (DefinitionIsVisible()) 8631 return true; 8632 8633 // The external source may have additional definitions of this entity that are 8634 // visible, so complete the redeclaration chain now and ask again. 8635 if (auto *Source = Context.getExternalSource()) { 8636 Source->CompleteRedeclChain(D); 8637 return DefinitionIsVisible(); 8638 } 8639 8640 return false; 8641 } 8642 8643 /// Locks in the inheritance model for the given class and all of its bases. 8644 static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) { 8645 RD = RD->getMostRecentNonInjectedDecl(); 8646 if (!RD->hasAttr<MSInheritanceAttr>()) { 8647 MSInheritanceModel IM; 8648 bool BestCase = false; 8649 switch (S.MSPointerToMemberRepresentationMethod) { 8650 case LangOptions::PPTMK_BestCase: 8651 BestCase = true; 8652 IM = RD->calculateInheritanceModel(); 8653 break; 8654 case LangOptions::PPTMK_FullGeneralitySingleInheritance: 8655 IM = MSInheritanceModel::Single; 8656 break; 8657 case LangOptions::PPTMK_FullGeneralityMultipleInheritance: 8658 IM = MSInheritanceModel::Multiple; 8659 break; 8660 case LangOptions::PPTMK_FullGeneralityVirtualInheritance: 8661 IM = MSInheritanceModel::Unspecified; 8662 break; 8663 } 8664 8665 SourceRange Loc = S.ImplicitMSInheritanceAttrLoc.isValid() 8666 ? S.ImplicitMSInheritanceAttrLoc 8667 : RD->getSourceRange(); 8668 RD->addAttr(MSInheritanceAttr::CreateImplicit( 8669 S.getASTContext(), BestCase, Loc, AttributeCommonInfo::AS_Microsoft, 8670 MSInheritanceAttr::Spelling(IM))); 8671 S.Consumer.AssignInheritanceModel(RD); 8672 } 8673 } 8674 8675 /// The implementation of RequireCompleteType 8676 bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T, 8677 CompleteTypeKind Kind, 8678 TypeDiagnoser *Diagnoser) { 8679 // FIXME: Add this assertion to make sure we always get instantiation points. 8680 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType"); 8681 // FIXME: Add this assertion to help us flush out problems with 8682 // checking for dependent types and type-dependent expressions. 8683 // 8684 // assert(!T->isDependentType() && 8685 // "Can't ask whether a dependent type is complete"); 8686 8687 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) { 8688 if (!MPTy->getClass()->isDependentType()) { 8689 if (getLangOpts().CompleteMemberPointers && 8690 !MPTy->getClass()->getAsCXXRecordDecl()->isBeingDefined() && 8691 RequireCompleteType(Loc, QualType(MPTy->getClass(), 0), Kind, 8692 diag::err_memptr_incomplete)) 8693 return true; 8694 8695 // We lock in the inheritance model once somebody has asked us to ensure 8696 // that a pointer-to-member type is complete. 8697 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 8698 (void)isCompleteType(Loc, QualType(MPTy->getClass(), 0)); 8699 assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl()); 8700 } 8701 } 8702 } 8703 8704 NamedDecl *Def = nullptr; 8705 bool AcceptSizeless = (Kind == CompleteTypeKind::AcceptSizeless); 8706 bool Incomplete = (T->isIncompleteType(&Def) || 8707 (!AcceptSizeless && T->isSizelessBuiltinType())); 8708 8709 // Check that any necessary explicit specializations are visible. For an 8710 // enum, we just need the declaration, so don't check this. 8711 if (Def && !isa<EnumDecl>(Def)) 8712 checkSpecializationVisibility(Loc, Def); 8713 8714 // If we have a complete type, we're done. 8715 if (!Incomplete) { 8716 // If we know about the definition but it is not visible, complain. 8717 NamedDecl *SuggestedDef = nullptr; 8718 if (Def && 8719 !hasVisibleDefinition(Def, &SuggestedDef, /*OnlyNeedComplete*/true)) { 8720 // If the user is going to see an error here, recover by making the 8721 // definition visible. 8722 bool TreatAsComplete = Diagnoser && !isSFINAEContext(); 8723 if (Diagnoser && SuggestedDef) 8724 diagnoseMissingImport(Loc, SuggestedDef, MissingImportKind::Definition, 8725 /*Recover*/TreatAsComplete); 8726 return !TreatAsComplete; 8727 } else if (Def && !TemplateInstCallbacks.empty()) { 8728 CodeSynthesisContext TempInst; 8729 TempInst.Kind = CodeSynthesisContext::Memoization; 8730 TempInst.Template = Def; 8731 TempInst.Entity = Def; 8732 TempInst.PointOfInstantiation = Loc; 8733 atTemplateBegin(TemplateInstCallbacks, *this, TempInst); 8734 atTemplateEnd(TemplateInstCallbacks, *this, TempInst); 8735 } 8736 8737 return false; 8738 } 8739 8740 TagDecl *Tag = dyn_cast_or_null<TagDecl>(Def); 8741 ObjCInterfaceDecl *IFace = dyn_cast_or_null<ObjCInterfaceDecl>(Def); 8742 8743 // Give the external source a chance to provide a definition of the type. 8744 // This is kept separate from completing the redeclaration chain so that 8745 // external sources such as LLDB can avoid synthesizing a type definition 8746 // unless it's actually needed. 8747 if (Tag || IFace) { 8748 // Avoid diagnosing invalid decls as incomplete. 8749 if (Def->isInvalidDecl()) 8750 return true; 8751 8752 // Give the external AST source a chance to complete the type. 8753 if (auto *Source = Context.getExternalSource()) { 8754 if (Tag && Tag->hasExternalLexicalStorage()) 8755 Source->CompleteType(Tag); 8756 if (IFace && IFace->hasExternalLexicalStorage()) 8757 Source->CompleteType(IFace); 8758 // If the external source completed the type, go through the motions 8759 // again to ensure we're allowed to use the completed type. 8760 if (!T->isIncompleteType()) 8761 return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser); 8762 } 8763 } 8764 8765 // If we have a class template specialization or a class member of a 8766 // class template specialization, or an array with known size of such, 8767 // try to instantiate it. 8768 if (auto *RD = dyn_cast_or_null<CXXRecordDecl>(Tag)) { 8769 bool Instantiated = false; 8770 bool Diagnosed = false; 8771 if (RD->isDependentContext()) { 8772 // Don't try to instantiate a dependent class (eg, a member template of 8773 // an instantiated class template specialization). 8774 // FIXME: Can this ever happen? 8775 } else if (auto *ClassTemplateSpec = 8776 dyn_cast<ClassTemplateSpecializationDecl>(RD)) { 8777 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) { 8778 runWithSufficientStackSpace(Loc, [&] { 8779 Diagnosed = InstantiateClassTemplateSpecialization( 8780 Loc, ClassTemplateSpec, TSK_ImplicitInstantiation, 8781 /*Complain=*/Diagnoser); 8782 }); 8783 Instantiated = true; 8784 } 8785 } else { 8786 CXXRecordDecl *Pattern = RD->getInstantiatedFromMemberClass(); 8787 if (!RD->isBeingDefined() && Pattern) { 8788 MemberSpecializationInfo *MSI = RD->getMemberSpecializationInfo(); 8789 assert(MSI && "Missing member specialization information?"); 8790 // This record was instantiated from a class within a template. 8791 if (MSI->getTemplateSpecializationKind() != 8792 TSK_ExplicitSpecialization) { 8793 runWithSufficientStackSpace(Loc, [&] { 8794 Diagnosed = InstantiateClass(Loc, RD, Pattern, 8795 getTemplateInstantiationArgs(RD), 8796 TSK_ImplicitInstantiation, 8797 /*Complain=*/Diagnoser); 8798 }); 8799 Instantiated = true; 8800 } 8801 } 8802 } 8803 8804 if (Instantiated) { 8805 // Instantiate* might have already complained that the template is not 8806 // defined, if we asked it to. 8807 if (Diagnoser && Diagnosed) 8808 return true; 8809 // If we instantiated a definition, check that it's usable, even if 8810 // instantiation produced an error, so that repeated calls to this 8811 // function give consistent answers. 8812 if (!T->isIncompleteType()) 8813 return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser); 8814 } 8815 } 8816 8817 // FIXME: If we didn't instantiate a definition because of an explicit 8818 // specialization declaration, check that it's visible. 8819 8820 if (!Diagnoser) 8821 return true; 8822 8823 Diagnoser->diagnose(*this, Loc, T); 8824 8825 // If the type was a forward declaration of a class/struct/union 8826 // type, produce a note. 8827 if (Tag && !Tag->isInvalidDecl() && !Tag->getLocation().isInvalid()) 8828 Diag(Tag->getLocation(), 8829 Tag->isBeingDefined() ? diag::note_type_being_defined 8830 : diag::note_forward_declaration) 8831 << Context.getTagDeclType(Tag); 8832 8833 // If the Objective-C class was a forward declaration, produce a note. 8834 if (IFace && !IFace->isInvalidDecl() && !IFace->getLocation().isInvalid()) 8835 Diag(IFace->getLocation(), diag::note_forward_class); 8836 8837 // If we have external information that we can use to suggest a fix, 8838 // produce a note. 8839 if (ExternalSource) 8840 ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T); 8841 8842 return true; 8843 } 8844 8845 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, 8846 CompleteTypeKind Kind, unsigned DiagID) { 8847 BoundTypeDiagnoser<> Diagnoser(DiagID); 8848 return RequireCompleteType(Loc, T, Kind, Diagnoser); 8849 } 8850 8851 /// Get diagnostic %select index for tag kind for 8852 /// literal type diagnostic message. 8853 /// WARNING: Indexes apply to particular diagnostics only! 8854 /// 8855 /// \returns diagnostic %select index. 8856 static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) { 8857 switch (Tag) { 8858 case TTK_Struct: return 0; 8859 case TTK_Interface: return 1; 8860 case TTK_Class: return 2; 8861 default: llvm_unreachable("Invalid tag kind for literal type diagnostic!"); 8862 } 8863 } 8864 8865 /// Ensure that the type T is a literal type. 8866 /// 8867 /// This routine checks whether the type @p T is a literal type. If @p T is an 8868 /// incomplete type, an attempt is made to complete it. If @p T is a literal 8869 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type, 8870 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving 8871 /// it the type @p T), along with notes explaining why the type is not a 8872 /// literal type, and returns true. 8873 /// 8874 /// @param Loc The location in the source that the non-literal type 8875 /// diagnostic should refer to. 8876 /// 8877 /// @param T The type that this routine is examining for literalness. 8878 /// 8879 /// @param Diagnoser Emits a diagnostic if T is not a literal type. 8880 /// 8881 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted, 8882 /// @c false otherwise. 8883 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, 8884 TypeDiagnoser &Diagnoser) { 8885 assert(!T->isDependentType() && "type should not be dependent"); 8886 8887 QualType ElemType = Context.getBaseElementType(T); 8888 if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) && 8889 T->isLiteralType(Context)) 8890 return false; 8891 8892 Diagnoser.diagnose(*this, Loc, T); 8893 8894 if (T->isVariableArrayType()) 8895 return true; 8896 8897 const RecordType *RT = ElemType->getAs<RecordType>(); 8898 if (!RT) 8899 return true; 8900 8901 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 8902 8903 // A partially-defined class type can't be a literal type, because a literal 8904 // class type must have a trivial destructor (which can't be checked until 8905 // the class definition is complete). 8906 if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T)) 8907 return true; 8908 8909 // [expr.prim.lambda]p3: 8910 // This class type is [not] a literal type. 8911 if (RD->isLambda() && !getLangOpts().CPlusPlus17) { 8912 Diag(RD->getLocation(), diag::note_non_literal_lambda); 8913 return true; 8914 } 8915 8916 // If the class has virtual base classes, then it's not an aggregate, and 8917 // cannot have any constexpr constructors or a trivial default constructor, 8918 // so is non-literal. This is better to diagnose than the resulting absence 8919 // of constexpr constructors. 8920 if (RD->getNumVBases()) { 8921 Diag(RD->getLocation(), diag::note_non_literal_virtual_base) 8922 << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 8923 for (const auto &I : RD->vbases()) 8924 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here) 8925 << I.getSourceRange(); 8926 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() && 8927 !RD->hasTrivialDefaultConstructor()) { 8928 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD; 8929 } else if (RD->hasNonLiteralTypeFieldsOrBases()) { 8930 for (const auto &I : RD->bases()) { 8931 if (!I.getType()->isLiteralType(Context)) { 8932 Diag(I.getBeginLoc(), diag::note_non_literal_base_class) 8933 << RD << I.getType() << I.getSourceRange(); 8934 return true; 8935 } 8936 } 8937 for (const auto *I : RD->fields()) { 8938 if (!I->getType()->isLiteralType(Context) || 8939 I->getType().isVolatileQualified()) { 8940 Diag(I->getLocation(), diag::note_non_literal_field) 8941 << RD << I << I->getType() 8942 << I->getType().isVolatileQualified(); 8943 return true; 8944 } 8945 } 8946 } else if (getLangOpts().CPlusPlus20 ? !RD->hasConstexprDestructor() 8947 : !RD->hasTrivialDestructor()) { 8948 // All fields and bases are of literal types, so have trivial or constexpr 8949 // destructors. If this class's destructor is non-trivial / non-constexpr, 8950 // it must be user-declared. 8951 CXXDestructorDecl *Dtor = RD->getDestructor(); 8952 assert(Dtor && "class has literal fields and bases but no dtor?"); 8953 if (!Dtor) 8954 return true; 8955 8956 if (getLangOpts().CPlusPlus20) { 8957 Diag(Dtor->getLocation(), diag::note_non_literal_non_constexpr_dtor) 8958 << RD; 8959 } else { 8960 Diag(Dtor->getLocation(), Dtor->isUserProvided() 8961 ? diag::note_non_literal_user_provided_dtor 8962 : diag::note_non_literal_nontrivial_dtor) 8963 << RD; 8964 if (!Dtor->isUserProvided()) 8965 SpecialMemberIsTrivial(Dtor, CXXDestructor, TAH_IgnoreTrivialABI, 8966 /*Diagnose*/ true); 8967 } 8968 } 8969 8970 return true; 8971 } 8972 8973 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) { 8974 BoundTypeDiagnoser<> Diagnoser(DiagID); 8975 return RequireLiteralType(Loc, T, Diagnoser); 8976 } 8977 8978 /// Retrieve a version of the type 'T' that is elaborated by Keyword, qualified 8979 /// by the nested-name-specifier contained in SS, and that is (re)declared by 8980 /// OwnedTagDecl, which is nullptr if this is not a (re)declaration. 8981 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword, 8982 const CXXScopeSpec &SS, QualType T, 8983 TagDecl *OwnedTagDecl) { 8984 if (T.isNull()) 8985 return T; 8986 NestedNameSpecifier *NNS; 8987 if (SS.isValid()) 8988 NNS = SS.getScopeRep(); 8989 else { 8990 if (Keyword == ETK_None) 8991 return T; 8992 NNS = nullptr; 8993 } 8994 return Context.getElaboratedType(Keyword, NNS, T, OwnedTagDecl); 8995 } 8996 8997 QualType Sema::BuildTypeofExprType(Expr *E) { 8998 assert(!E->hasPlaceholderType() && "unexpected placeholder"); 8999 9000 if (!getLangOpts().CPlusPlus && E->refersToBitField()) 9001 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 2; 9002 9003 if (!E->isTypeDependent()) { 9004 QualType T = E->getType(); 9005 if (const TagType *TT = T->getAs<TagType>()) 9006 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc()); 9007 } 9008 return Context.getTypeOfExprType(E); 9009 } 9010 9011 /// getDecltypeForExpr - Given an expr, will return the decltype for 9012 /// that expression, according to the rules in C++11 9013 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18. 9014 QualType Sema::getDecltypeForExpr(Expr *E) { 9015 if (E->isTypeDependent()) 9016 return Context.DependentTy; 9017 9018 Expr *IDExpr = E; 9019 if (auto *ImplCastExpr = dyn_cast<ImplicitCastExpr>(E)) 9020 IDExpr = ImplCastExpr->getSubExpr(); 9021 9022 // C++11 [dcl.type.simple]p4: 9023 // The type denoted by decltype(e) is defined as follows: 9024 9025 // C++20: 9026 // - if E is an unparenthesized id-expression naming a non-type 9027 // template-parameter (13.2), decltype(E) is the type of the 9028 // template-parameter after performing any necessary type deduction 9029 // Note that this does not pick up the implicit 'const' for a template 9030 // parameter object. This rule makes no difference before C++20 so we apply 9031 // it unconditionally. 9032 if (const auto *SNTTPE = dyn_cast<SubstNonTypeTemplateParmExpr>(IDExpr)) 9033 return SNTTPE->getParameterType(Context); 9034 9035 // - if e is an unparenthesized id-expression or an unparenthesized class 9036 // member access (5.2.5), decltype(e) is the type of the entity named 9037 // by e. If there is no such entity, or if e names a set of overloaded 9038 // functions, the program is ill-formed; 9039 // 9040 // We apply the same rules for Objective-C ivar and property references. 9041 if (const auto *DRE = dyn_cast<DeclRefExpr>(IDExpr)) { 9042 const ValueDecl *VD = DRE->getDecl(); 9043 QualType T = VD->getType(); 9044 return isa<TemplateParamObjectDecl>(VD) ? T.getUnqualifiedType() : T; 9045 } 9046 if (const auto *ME = dyn_cast<MemberExpr>(IDExpr)) { 9047 if (const auto *VD = ME->getMemberDecl()) 9048 if (isa<FieldDecl>(VD) || isa<VarDecl>(VD)) 9049 return VD->getType(); 9050 } else if (const auto *IR = dyn_cast<ObjCIvarRefExpr>(IDExpr)) { 9051 return IR->getDecl()->getType(); 9052 } else if (const auto *PR = dyn_cast<ObjCPropertyRefExpr>(IDExpr)) { 9053 if (PR->isExplicitProperty()) 9054 return PR->getExplicitProperty()->getType(); 9055 } else if (const auto *PE = dyn_cast<PredefinedExpr>(IDExpr)) { 9056 return PE->getType(); 9057 } 9058 9059 // C++11 [expr.lambda.prim]p18: 9060 // Every occurrence of decltype((x)) where x is a possibly 9061 // parenthesized id-expression that names an entity of automatic 9062 // storage duration is treated as if x were transformed into an 9063 // access to a corresponding data member of the closure type that 9064 // would have been declared if x were an odr-use of the denoted 9065 // entity. 9066 if (getCurLambda() && isa<ParenExpr>(IDExpr)) { 9067 if (auto *DRE = dyn_cast<DeclRefExpr>(IDExpr->IgnoreParens())) { 9068 if (auto *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 9069 QualType T = getCapturedDeclRefType(Var, DRE->getLocation()); 9070 if (!T.isNull()) 9071 return Context.getLValueReferenceType(T); 9072 } 9073 } 9074 } 9075 9076 return Context.getReferenceQualifiedType(E); 9077 } 9078 9079 QualType Sema::BuildDecltypeType(Expr *E, bool AsUnevaluated) { 9080 assert(!E->hasPlaceholderType() && "unexpected placeholder"); 9081 9082 if (AsUnevaluated && CodeSynthesisContexts.empty() && 9083 !E->isInstantiationDependent() && E->HasSideEffects(Context, false)) { 9084 // The expression operand for decltype is in an unevaluated expression 9085 // context, so side effects could result in unintended consequences. 9086 // Exclude instantiation-dependent expressions, because 'decltype' is often 9087 // used to build SFINAE gadgets. 9088 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 9089 } 9090 return Context.getDecltypeType(E, getDecltypeForExpr(E)); 9091 } 9092 9093 QualType Sema::BuildUnaryTransformType(QualType BaseType, 9094 UnaryTransformType::UTTKind UKind, 9095 SourceLocation Loc) { 9096 switch (UKind) { 9097 case UnaryTransformType::EnumUnderlyingType: 9098 if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) { 9099 Diag(Loc, diag::err_only_enums_have_underlying_types); 9100 return QualType(); 9101 } else { 9102 QualType Underlying = BaseType; 9103 if (!BaseType->isDependentType()) { 9104 // The enum could be incomplete if we're parsing its definition or 9105 // recovering from an error. 9106 NamedDecl *FwdDecl = nullptr; 9107 if (BaseType->isIncompleteType(&FwdDecl)) { 9108 Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType; 9109 Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl; 9110 return QualType(); 9111 } 9112 9113 EnumDecl *ED = BaseType->castAs<EnumType>()->getDecl(); 9114 assert(ED && "EnumType has no EnumDecl"); 9115 9116 DiagnoseUseOfDecl(ED, Loc); 9117 9118 Underlying = ED->getIntegerType(); 9119 assert(!Underlying.isNull()); 9120 } 9121 return Context.getUnaryTransformType(BaseType, Underlying, 9122 UnaryTransformType::EnumUnderlyingType); 9123 } 9124 } 9125 llvm_unreachable("unknown unary transform type"); 9126 } 9127 9128 QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) { 9129 if (!isDependentOrGNUAutoType(T)) { 9130 // FIXME: It isn't entirely clear whether incomplete atomic types 9131 // are allowed or not; for simplicity, ban them for the moment. 9132 if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0)) 9133 return QualType(); 9134 9135 int DisallowedKind = -1; 9136 if (T->isArrayType()) 9137 DisallowedKind = 1; 9138 else if (T->isFunctionType()) 9139 DisallowedKind = 2; 9140 else if (T->isReferenceType()) 9141 DisallowedKind = 3; 9142 else if (T->isAtomicType()) 9143 DisallowedKind = 4; 9144 else if (T.hasQualifiers()) 9145 DisallowedKind = 5; 9146 else if (T->isSizelessType()) 9147 DisallowedKind = 6; 9148 else if (!T.isTriviallyCopyableType(Context)) 9149 // Some other non-trivially-copyable type (probably a C++ class) 9150 DisallowedKind = 7; 9151 else if (T->isBitIntType()) 9152 DisallowedKind = 8; 9153 9154 if (DisallowedKind != -1) { 9155 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T; 9156 return QualType(); 9157 } 9158 9159 // FIXME: Do we need any handling for ARC here? 9160 } 9161 9162 // Build the pointer type. 9163 return Context.getAtomicType(T); 9164 } 9165