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