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