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