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