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