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