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