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