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