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