SemaType.cpp revision 5cd532ca0bc1cb8110e24586d064f72332d8b767
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 "clang/AST/ASTContext.h" 16#include "clang/AST/ASTMutationListener.h" 17#include "clang/AST/CXXInheritance.h" 18#include "clang/AST/DeclObjC.h" 19#include "clang/AST/DeclTemplate.h" 20#include "clang/AST/Expr.h" 21#include "clang/AST/TypeLoc.h" 22#include "clang/AST/TypeLocVisitor.h" 23#include "clang/Basic/OpenCL.h" 24#include "clang/Basic/PartialDiagnostic.h" 25#include "clang/Basic/TargetInfo.h" 26#include "clang/Lex/Preprocessor.h" 27#include "clang/Parse/ParseDiagnostic.h" 28#include "clang/Sema/DeclSpec.h" 29#include "clang/Sema/DelayedDiagnostic.h" 30#include "clang/Sema/Lookup.h" 31#include "clang/Sema/ScopeInfo.h" 32#include "clang/Sema/Template.h" 33#include "llvm/ADT/SmallPtrSet.h" 34#include "llvm/Support/ErrorHandling.h" 35using namespace clang; 36 37/// isOmittedBlockReturnType - Return true if this declarator is missing a 38/// return type because this is a omitted return type on a block literal. 39static bool isOmittedBlockReturnType(const Declarator &D) { 40 if (D.getContext() != Declarator::BlockLiteralContext || 41 D.getDeclSpec().hasTypeSpecifier()) 42 return false; 43 44 if (D.getNumTypeObjects() == 0) 45 return true; // ^{ ... } 46 47 if (D.getNumTypeObjects() == 1 && 48 D.getTypeObject(0).Kind == DeclaratorChunk::Function) 49 return true; // ^(int X, float Y) { ... } 50 51 return false; 52} 53 54/// diagnoseBadTypeAttribute - Diagnoses a type attribute which 55/// doesn't apply to the given type. 56static void diagnoseBadTypeAttribute(Sema &S, const AttributeList &attr, 57 QualType type) { 58 bool useExpansionLoc = false; 59 60 unsigned diagID = 0; 61 switch (attr.getKind()) { 62 case AttributeList::AT_ObjCGC: 63 diagID = diag::warn_pointer_attribute_wrong_type; 64 useExpansionLoc = true; 65 break; 66 67 case AttributeList::AT_ObjCOwnership: 68 diagID = diag::warn_objc_object_attribute_wrong_type; 69 useExpansionLoc = true; 70 break; 71 72 default: 73 // Assume everything else was a function attribute. 74 diagID = diag::warn_function_attribute_wrong_type; 75 break; 76 } 77 78 SourceLocation loc = attr.getLoc(); 79 StringRef name = attr.getName()->getName(); 80 81 // The GC attributes are usually written with macros; special-case them. 82 if (useExpansionLoc && loc.isMacroID() && attr.getParameterName()) { 83 if (attr.getParameterName()->isStr("strong")) { 84 if (S.findMacroSpelling(loc, "__strong")) name = "__strong"; 85 } else if (attr.getParameterName()->isStr("weak")) { 86 if (S.findMacroSpelling(loc, "__weak")) name = "__weak"; 87 } 88 } 89 90 S.Diag(loc, diagID) << name << type; 91} 92 93// objc_gc applies to Objective-C pointers or, otherwise, to the 94// smallest available pointer type (i.e. 'void*' in 'void**'). 95#define OBJC_POINTER_TYPE_ATTRS_CASELIST \ 96 case AttributeList::AT_ObjCGC: \ 97 case AttributeList::AT_ObjCOwnership 98 99// Function type attributes. 100#define FUNCTION_TYPE_ATTRS_CASELIST \ 101 case AttributeList::AT_NoReturn: \ 102 case AttributeList::AT_CDecl: \ 103 case AttributeList::AT_FastCall: \ 104 case AttributeList::AT_StdCall: \ 105 case AttributeList::AT_ThisCall: \ 106 case AttributeList::AT_Pascal: \ 107 case AttributeList::AT_Regparm: \ 108 case AttributeList::AT_Pcs: \ 109 case AttributeList::AT_PnaclCall: \ 110 case AttributeList::AT_IntelOclBicc \ 111 112namespace { 113 /// An object which stores processing state for the entire 114 /// GetTypeForDeclarator process. 115 class TypeProcessingState { 116 Sema &sema; 117 118 /// The declarator being processed. 119 Declarator &declarator; 120 121 /// The index of the declarator chunk we're currently processing. 122 /// May be the total number of valid chunks, indicating the 123 /// DeclSpec. 124 unsigned chunkIndex; 125 126 /// Whether there are non-trivial modifications to the decl spec. 127 bool trivial; 128 129 /// Whether we saved the attributes in the decl spec. 130 bool hasSavedAttrs; 131 132 /// The original set of attributes on the DeclSpec. 133 SmallVector<AttributeList*, 2> savedAttrs; 134 135 /// A list of attributes to diagnose the uselessness of when the 136 /// processing is complete. 137 SmallVector<AttributeList*, 2> ignoredTypeAttrs; 138 139 public: 140 TypeProcessingState(Sema &sema, Declarator &declarator) 141 : sema(sema), declarator(declarator), 142 chunkIndex(declarator.getNumTypeObjects()), 143 trivial(true), hasSavedAttrs(false) {} 144 145 Sema &getSema() const { 146 return sema; 147 } 148 149 Declarator &getDeclarator() const { 150 return declarator; 151 } 152 153 unsigned getCurrentChunkIndex() const { 154 return chunkIndex; 155 } 156 157 void setCurrentChunkIndex(unsigned idx) { 158 assert(idx <= declarator.getNumTypeObjects()); 159 chunkIndex = idx; 160 } 161 162 AttributeList *&getCurrentAttrListRef() const { 163 assert(chunkIndex <= declarator.getNumTypeObjects()); 164 if (chunkIndex == declarator.getNumTypeObjects()) 165 return getMutableDeclSpec().getAttributes().getListRef(); 166 return declarator.getTypeObject(chunkIndex).getAttrListRef(); 167 } 168 169 /// Save the current set of attributes on the DeclSpec. 170 void saveDeclSpecAttrs() { 171 // Don't try to save them multiple times. 172 if (hasSavedAttrs) return; 173 174 DeclSpec &spec = getMutableDeclSpec(); 175 for (AttributeList *attr = spec.getAttributes().getList(); attr; 176 attr = attr->getNext()) 177 savedAttrs.push_back(attr); 178 trivial &= savedAttrs.empty(); 179 hasSavedAttrs = true; 180 } 181 182 /// Record that we had nowhere to put the given type attribute. 183 /// We will diagnose such attributes later. 184 void addIgnoredTypeAttr(AttributeList &attr) { 185 ignoredTypeAttrs.push_back(&attr); 186 } 187 188 /// Diagnose all the ignored type attributes, given that the 189 /// declarator worked out to the given type. 190 void diagnoseIgnoredTypeAttrs(QualType type) const { 191 for (SmallVectorImpl<AttributeList*>::const_iterator 192 i = ignoredTypeAttrs.begin(), e = ignoredTypeAttrs.end(); 193 i != e; ++i) 194 diagnoseBadTypeAttribute(getSema(), **i, type); 195 } 196 197 ~TypeProcessingState() { 198 if (trivial) return; 199 200 restoreDeclSpecAttrs(); 201 } 202 203 private: 204 DeclSpec &getMutableDeclSpec() const { 205 return const_cast<DeclSpec&>(declarator.getDeclSpec()); 206 } 207 208 void restoreDeclSpecAttrs() { 209 assert(hasSavedAttrs); 210 211 if (savedAttrs.empty()) { 212 getMutableDeclSpec().getAttributes().set(0); 213 return; 214 } 215 216 getMutableDeclSpec().getAttributes().set(savedAttrs[0]); 217 for (unsigned i = 0, e = savedAttrs.size() - 1; i != e; ++i) 218 savedAttrs[i]->setNext(savedAttrs[i+1]); 219 savedAttrs.back()->setNext(0); 220 } 221 }; 222 223 /// Basically std::pair except that we really want to avoid an 224 /// implicit operator= for safety concerns. It's also a minor 225 /// link-time optimization for this to be a private type. 226 struct AttrAndList { 227 /// The attribute. 228 AttributeList &first; 229 230 /// The head of the list the attribute is currently in. 231 AttributeList *&second; 232 233 AttrAndList(AttributeList &attr, AttributeList *&head) 234 : first(attr), second(head) {} 235 }; 236} 237 238namespace llvm { 239 template <> struct isPodLike<AttrAndList> { 240 static const bool value = true; 241 }; 242} 243 244static void spliceAttrIntoList(AttributeList &attr, AttributeList *&head) { 245 attr.setNext(head); 246 head = &attr; 247} 248 249static void spliceAttrOutOfList(AttributeList &attr, AttributeList *&head) { 250 if (head == &attr) { 251 head = attr.getNext(); 252 return; 253 } 254 255 AttributeList *cur = head; 256 while (true) { 257 assert(cur && cur->getNext() && "ran out of attrs?"); 258 if (cur->getNext() == &attr) { 259 cur->setNext(attr.getNext()); 260 return; 261 } 262 cur = cur->getNext(); 263 } 264} 265 266static void moveAttrFromListToList(AttributeList &attr, 267 AttributeList *&fromList, 268 AttributeList *&toList) { 269 spliceAttrOutOfList(attr, fromList); 270 spliceAttrIntoList(attr, toList); 271} 272 273/// The location of a type attribute. 274enum TypeAttrLocation { 275 /// The attribute is in the decl-specifier-seq. 276 TAL_DeclSpec, 277 /// The attribute is part of a DeclaratorChunk. 278 TAL_DeclChunk, 279 /// The attribute is immediately after the declaration's name. 280 TAL_DeclName 281}; 282 283static void processTypeAttrs(TypeProcessingState &state, 284 QualType &type, TypeAttrLocation TAL, 285 AttributeList *attrs); 286 287static bool handleFunctionTypeAttr(TypeProcessingState &state, 288 AttributeList &attr, 289 QualType &type); 290 291static bool handleObjCGCTypeAttr(TypeProcessingState &state, 292 AttributeList &attr, QualType &type); 293 294static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state, 295 AttributeList &attr, QualType &type); 296 297static bool handleObjCPointerTypeAttr(TypeProcessingState &state, 298 AttributeList &attr, QualType &type) { 299 if (attr.getKind() == AttributeList::AT_ObjCGC) 300 return handleObjCGCTypeAttr(state, attr, type); 301 assert(attr.getKind() == AttributeList::AT_ObjCOwnership); 302 return handleObjCOwnershipTypeAttr(state, attr, type); 303} 304 305/// Given that an objc_gc attribute was written somewhere on a 306/// declaration *other* than on the declarator itself (for which, use 307/// distributeObjCPointerTypeAttrFromDeclarator), and given that it 308/// didn't apply in whatever position it was written in, try to move 309/// it to a more appropriate position. 310static void distributeObjCPointerTypeAttr(TypeProcessingState &state, 311 AttributeList &attr, 312 QualType type) { 313 Declarator &declarator = state.getDeclarator(); 314 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { 315 DeclaratorChunk &chunk = declarator.getTypeObject(i-1); 316 switch (chunk.Kind) { 317 case DeclaratorChunk::Pointer: 318 case DeclaratorChunk::BlockPointer: 319 moveAttrFromListToList(attr, state.getCurrentAttrListRef(), 320 chunk.getAttrListRef()); 321 return; 322 323 case DeclaratorChunk::Paren: 324 case DeclaratorChunk::Array: 325 continue; 326 327 // Don't walk through these. 328 case DeclaratorChunk::Reference: 329 case DeclaratorChunk::Function: 330 case DeclaratorChunk::MemberPointer: 331 goto error; 332 } 333 } 334 error: 335 336 diagnoseBadTypeAttribute(state.getSema(), attr, type); 337} 338 339/// Distribute an objc_gc type attribute that was written on the 340/// declarator. 341static void 342distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState &state, 343 AttributeList &attr, 344 QualType &declSpecType) { 345 Declarator &declarator = state.getDeclarator(); 346 347 // objc_gc goes on the innermost pointer to something that's not a 348 // pointer. 349 unsigned innermost = -1U; 350 bool considerDeclSpec = true; 351 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { 352 DeclaratorChunk &chunk = declarator.getTypeObject(i); 353 switch (chunk.Kind) { 354 case DeclaratorChunk::Pointer: 355 case DeclaratorChunk::BlockPointer: 356 innermost = i; 357 continue; 358 359 case DeclaratorChunk::Reference: 360 case DeclaratorChunk::MemberPointer: 361 case DeclaratorChunk::Paren: 362 case DeclaratorChunk::Array: 363 continue; 364 365 case DeclaratorChunk::Function: 366 considerDeclSpec = false; 367 goto done; 368 } 369 } 370 done: 371 372 // That might actually be the decl spec if we weren't blocked by 373 // anything in the declarator. 374 if (considerDeclSpec) { 375 if (handleObjCPointerTypeAttr(state, attr, declSpecType)) { 376 // Splice the attribute into the decl spec. Prevents the 377 // attribute from being applied multiple times and gives 378 // the source-location-filler something to work with. 379 state.saveDeclSpecAttrs(); 380 moveAttrFromListToList(attr, declarator.getAttrListRef(), 381 declarator.getMutableDeclSpec().getAttributes().getListRef()); 382 return; 383 } 384 } 385 386 // Otherwise, if we found an appropriate chunk, splice the attribute 387 // into it. 388 if (innermost != -1U) { 389 moveAttrFromListToList(attr, declarator.getAttrListRef(), 390 declarator.getTypeObject(innermost).getAttrListRef()); 391 return; 392 } 393 394 // Otherwise, diagnose when we're done building the type. 395 spliceAttrOutOfList(attr, declarator.getAttrListRef()); 396 state.addIgnoredTypeAttr(attr); 397} 398 399/// A function type attribute was written somewhere in a declaration 400/// *other* than on the declarator itself or in the decl spec. Given 401/// that it didn't apply in whatever position it was written in, try 402/// to move it to a more appropriate position. 403static void distributeFunctionTypeAttr(TypeProcessingState &state, 404 AttributeList &attr, 405 QualType type) { 406 Declarator &declarator = state.getDeclarator(); 407 408 // Try to push the attribute from the return type of a function to 409 // the function itself. 410 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { 411 DeclaratorChunk &chunk = declarator.getTypeObject(i-1); 412 switch (chunk.Kind) { 413 case DeclaratorChunk::Function: 414 moveAttrFromListToList(attr, state.getCurrentAttrListRef(), 415 chunk.getAttrListRef()); 416 return; 417 418 case DeclaratorChunk::Paren: 419 case DeclaratorChunk::Pointer: 420 case DeclaratorChunk::BlockPointer: 421 case DeclaratorChunk::Array: 422 case DeclaratorChunk::Reference: 423 case DeclaratorChunk::MemberPointer: 424 continue; 425 } 426 } 427 428 diagnoseBadTypeAttribute(state.getSema(), attr, type); 429} 430 431/// Try to distribute a function type attribute to the innermost 432/// function chunk or type. Returns true if the attribute was 433/// distributed, false if no location was found. 434static bool 435distributeFunctionTypeAttrToInnermost(TypeProcessingState &state, 436 AttributeList &attr, 437 AttributeList *&attrList, 438 QualType &declSpecType) { 439 Declarator &declarator = state.getDeclarator(); 440 441 // Put it on the innermost function chunk, if there is one. 442 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { 443 DeclaratorChunk &chunk = declarator.getTypeObject(i); 444 if (chunk.Kind != DeclaratorChunk::Function) continue; 445 446 moveAttrFromListToList(attr, attrList, chunk.getAttrListRef()); 447 return true; 448 } 449 450 if (handleFunctionTypeAttr(state, attr, declSpecType)) { 451 spliceAttrOutOfList(attr, attrList); 452 return true; 453 } 454 455 return false; 456} 457 458/// A function type attribute was written in the decl spec. Try to 459/// apply it somewhere. 460static void 461distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state, 462 AttributeList &attr, 463 QualType &declSpecType) { 464 state.saveDeclSpecAttrs(); 465 466 // C++11 attributes before the decl specifiers actually appertain to 467 // the declarators. Move them straight there. We don't support the 468 // 'put them wherever you like' semantics we allow for GNU attributes. 469 if (attr.isCXX11Attribute()) { 470 moveAttrFromListToList(attr, state.getCurrentAttrListRef(), 471 state.getDeclarator().getAttrListRef()); 472 return; 473 } 474 475 // Try to distribute to the innermost. 476 if (distributeFunctionTypeAttrToInnermost(state, attr, 477 state.getCurrentAttrListRef(), 478 declSpecType)) 479 return; 480 481 // If that failed, diagnose the bad attribute when the declarator is 482 // fully built. 483 state.addIgnoredTypeAttr(attr); 484} 485 486/// A function type attribute was written on the declarator. Try to 487/// apply it somewhere. 488static void 489distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state, 490 AttributeList &attr, 491 QualType &declSpecType) { 492 Declarator &declarator = state.getDeclarator(); 493 494 // Try to distribute to the innermost. 495 if (distributeFunctionTypeAttrToInnermost(state, attr, 496 declarator.getAttrListRef(), 497 declSpecType)) 498 return; 499 500 // If that failed, diagnose the bad attribute when the declarator is 501 // fully built. 502 spliceAttrOutOfList(attr, declarator.getAttrListRef()); 503 state.addIgnoredTypeAttr(attr); 504} 505 506/// \brief Given that there are attributes written on the declarator 507/// itself, try to distribute any type attributes to the appropriate 508/// declarator chunk. 509/// 510/// These are attributes like the following: 511/// int f ATTR; 512/// int (f ATTR)(); 513/// but not necessarily this: 514/// int f() ATTR; 515static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state, 516 QualType &declSpecType) { 517 // Collect all the type attributes from the declarator itself. 518 assert(state.getDeclarator().getAttributes() && "declarator has no attrs!"); 519 AttributeList *attr = state.getDeclarator().getAttributes(); 520 AttributeList *next; 521 do { 522 next = attr->getNext(); 523 524 // Do not distribute C++11 attributes. They have strict rules for what 525 // they appertain to. 526 if (attr->isCXX11Attribute()) 527 continue; 528 529 switch (attr->getKind()) { 530 OBJC_POINTER_TYPE_ATTRS_CASELIST: 531 distributeObjCPointerTypeAttrFromDeclarator(state, *attr, declSpecType); 532 break; 533 534 case AttributeList::AT_NSReturnsRetained: 535 if (!state.getSema().getLangOpts().ObjCAutoRefCount) 536 break; 537 // fallthrough 538 539 FUNCTION_TYPE_ATTRS_CASELIST: 540 distributeFunctionTypeAttrFromDeclarator(state, *attr, declSpecType); 541 break; 542 543 default: 544 break; 545 } 546 } while ((attr = next)); 547} 548 549/// Add a synthetic '()' to a block-literal declarator if it is 550/// required, given the return type. 551static void maybeSynthesizeBlockSignature(TypeProcessingState &state, 552 QualType declSpecType) { 553 Declarator &declarator = state.getDeclarator(); 554 555 // First, check whether the declarator would produce a function, 556 // i.e. whether the innermost semantic chunk is a function. 557 if (declarator.isFunctionDeclarator()) { 558 // If so, make that declarator a prototyped declarator. 559 declarator.getFunctionTypeInfo().hasPrototype = true; 560 return; 561 } 562 563 // If there are any type objects, the type as written won't name a 564 // function, regardless of the decl spec type. This is because a 565 // block signature declarator is always an abstract-declarator, and 566 // abstract-declarators can't just be parentheses chunks. Therefore 567 // we need to build a function chunk unless there are no type 568 // objects and the decl spec type is a function. 569 if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType()) 570 return; 571 572 // Note that there *are* cases with invalid declarators where 573 // declarators consist solely of parentheses. In general, these 574 // occur only in failed efforts to make function declarators, so 575 // faking up the function chunk is still the right thing to do. 576 577 // Otherwise, we need to fake up a function declarator. 578 SourceLocation loc = declarator.getLocStart(); 579 580 // ...and *prepend* it to the declarator. 581 SourceLocation NoLoc; 582 declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction( 583 /*HasProto=*/true, 584 /*IsAmbiguous=*/false, 585 /*LParenLoc=*/NoLoc, 586 /*ArgInfo=*/0, 587 /*NumArgs=*/0, 588 /*EllipsisLoc=*/NoLoc, 589 /*RParenLoc=*/NoLoc, 590 /*TypeQuals=*/0, 591 /*RefQualifierIsLvalueRef=*/true, 592 /*RefQualifierLoc=*/NoLoc, 593 /*ConstQualifierLoc=*/NoLoc, 594 /*VolatileQualifierLoc=*/NoLoc, 595 /*MutableLoc=*/NoLoc, 596 EST_None, 597 /*ESpecLoc=*/NoLoc, 598 /*Exceptions=*/0, 599 /*ExceptionRanges=*/0, 600 /*NumExceptions=*/0, 601 /*NoexceptExpr=*/0, 602 loc, loc, declarator)); 603 604 // For consistency, make sure the state still has us as processing 605 // the decl spec. 606 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1); 607 state.setCurrentChunkIndex(declarator.getNumTypeObjects()); 608} 609 610/// \brief Convert the specified declspec to the appropriate type 611/// object. 612/// \param state Specifies the declarator containing the declaration specifier 613/// to be converted, along with other associated processing state. 614/// \returns The type described by the declaration specifiers. This function 615/// never returns null. 616static QualType ConvertDeclSpecToType(TypeProcessingState &state) { 617 // FIXME: Should move the logic from DeclSpec::Finish to here for validity 618 // checking. 619 620 Sema &S = state.getSema(); 621 Declarator &declarator = state.getDeclarator(); 622 const DeclSpec &DS = declarator.getDeclSpec(); 623 SourceLocation DeclLoc = declarator.getIdentifierLoc(); 624 if (DeclLoc.isInvalid()) 625 DeclLoc = DS.getLocStart(); 626 627 ASTContext &Context = S.Context; 628 629 QualType Result; 630 switch (DS.getTypeSpecType()) { 631 case DeclSpec::TST_void: 632 Result = Context.VoidTy; 633 break; 634 case DeclSpec::TST_char: 635 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified) 636 Result = Context.CharTy; 637 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) 638 Result = Context.SignedCharTy; 639 else { 640 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && 641 "Unknown TSS value"); 642 Result = Context.UnsignedCharTy; 643 } 644 break; 645 case DeclSpec::TST_wchar: 646 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified) 647 Result = Context.WCharTy; 648 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) { 649 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec) 650 << DS.getSpecifierName(DS.getTypeSpecType()); 651 Result = Context.getSignedWCharType(); 652 } else { 653 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && 654 "Unknown TSS value"); 655 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec) 656 << DS.getSpecifierName(DS.getTypeSpecType()); 657 Result = Context.getUnsignedWCharType(); 658 } 659 break; 660 case DeclSpec::TST_char16: 661 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && 662 "Unknown TSS value"); 663 Result = Context.Char16Ty; 664 break; 665 case DeclSpec::TST_char32: 666 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && 667 "Unknown TSS value"); 668 Result = Context.Char32Ty; 669 break; 670 case DeclSpec::TST_unspecified: 671 // "<proto1,proto2>" is an objc qualified ID with a missing id. 672 if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) { 673 Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy, 674 (ObjCProtocolDecl*const*)PQ, 675 DS.getNumProtocolQualifiers()); 676 Result = Context.getObjCObjectPointerType(Result); 677 break; 678 } 679 680 // If this is a missing declspec in a block literal return context, then it 681 // is inferred from the return statements inside the block. 682 // The declspec is always missing in a lambda expr context; it is either 683 // specified with a trailing return type or inferred. 684 if (declarator.getContext() == Declarator::LambdaExprContext || 685 isOmittedBlockReturnType(declarator)) { 686 Result = Context.DependentTy; 687 break; 688 } 689 690 // Unspecified typespec defaults to int in C90. However, the C90 grammar 691 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier, 692 // type-qualifier, or storage-class-specifier. If not, emit an extwarn. 693 // Note that the one exception to this is function definitions, which are 694 // allowed to be completely missing a declspec. This is handled in the 695 // parser already though by it pretending to have seen an 'int' in this 696 // case. 697 if (S.getLangOpts().ImplicitInt) { 698 // In C89 mode, we only warn if there is a completely missing declspec 699 // when one is not allowed. 700 if (DS.isEmpty()) { 701 S.Diag(DeclLoc, diag::ext_missing_declspec) 702 << DS.getSourceRange() 703 << FixItHint::CreateInsertion(DS.getLocStart(), "int"); 704 } 705 } else if (!DS.hasTypeSpecifier()) { 706 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says: 707 // "At least one type specifier shall be given in the declaration 708 // specifiers in each declaration, and in the specifier-qualifier list in 709 // each struct declaration and type name." 710 // FIXME: Does Microsoft really have the implicit int extension in C++? 711 if (S.getLangOpts().CPlusPlus && 712 !S.getLangOpts().MicrosoftExt) { 713 S.Diag(DeclLoc, diag::err_missing_type_specifier) 714 << DS.getSourceRange(); 715 716 // When this occurs in C++ code, often something is very broken with the 717 // value being declared, poison it as invalid so we don't get chains of 718 // errors. 719 declarator.setInvalidType(true); 720 } else { 721 S.Diag(DeclLoc, diag::ext_missing_type_specifier) 722 << DS.getSourceRange(); 723 } 724 } 725 726 // FALL THROUGH. 727 case DeclSpec::TST_int: { 728 if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) { 729 switch (DS.getTypeSpecWidth()) { 730 case DeclSpec::TSW_unspecified: Result = Context.IntTy; break; 731 case DeclSpec::TSW_short: Result = Context.ShortTy; break; 732 case DeclSpec::TSW_long: Result = Context.LongTy; break; 733 case DeclSpec::TSW_longlong: 734 Result = Context.LongLongTy; 735 736 // 'long long' is a C99 or C++11 feature. 737 if (!S.getLangOpts().C99) { 738 if (S.getLangOpts().CPlusPlus) 739 S.Diag(DS.getTypeSpecWidthLoc(), 740 S.getLangOpts().CPlusPlus11 ? 741 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 742 else 743 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong); 744 } 745 break; 746 } 747 } else { 748 switch (DS.getTypeSpecWidth()) { 749 case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break; 750 case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break; 751 case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break; 752 case DeclSpec::TSW_longlong: 753 Result = Context.UnsignedLongLongTy; 754 755 // 'long long' is a C99 or C++11 feature. 756 if (!S.getLangOpts().C99) { 757 if (S.getLangOpts().CPlusPlus) 758 S.Diag(DS.getTypeSpecWidthLoc(), 759 S.getLangOpts().CPlusPlus11 ? 760 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 761 else 762 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong); 763 } 764 break; 765 } 766 } 767 break; 768 } 769 case DeclSpec::TST_int128: 770 if (!S.PP.getTargetInfo().hasInt128Type()) 771 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_int128_unsupported); 772 if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned) 773 Result = Context.UnsignedInt128Ty; 774 else 775 Result = Context.Int128Ty; 776 break; 777 case DeclSpec::TST_half: Result = Context.HalfTy; break; 778 case DeclSpec::TST_float: Result = Context.FloatTy; break; 779 case DeclSpec::TST_double: 780 if (DS.getTypeSpecWidth() == DeclSpec::TSW_long) 781 Result = Context.LongDoubleTy; 782 else 783 Result = Context.DoubleTy; 784 785 if (S.getLangOpts().OpenCL && !S.getOpenCLOptions().cl_khr_fp64) { 786 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_double_requires_fp64); 787 declarator.setInvalidType(true); 788 } 789 break; 790 case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool 791 case DeclSpec::TST_decimal32: // _Decimal32 792 case DeclSpec::TST_decimal64: // _Decimal64 793 case DeclSpec::TST_decimal128: // _Decimal128 794 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported); 795 Result = Context.IntTy; 796 declarator.setInvalidType(true); 797 break; 798 case DeclSpec::TST_class: 799 case DeclSpec::TST_enum: 800 case DeclSpec::TST_union: 801 case DeclSpec::TST_struct: 802 case DeclSpec::TST_interface: { 803 TypeDecl *D = dyn_cast_or_null<TypeDecl>(DS.getRepAsDecl()); 804 if (!D) { 805 // This can happen in C++ with ambiguous lookups. 806 Result = Context.IntTy; 807 declarator.setInvalidType(true); 808 break; 809 } 810 811 // If the type is deprecated or unavailable, diagnose it. 812 S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc()); 813 814 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && 815 DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!"); 816 817 // TypeQuals handled by caller. 818 Result = Context.getTypeDeclType(D); 819 820 // In both C and C++, make an ElaboratedType. 821 ElaboratedTypeKeyword Keyword 822 = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType()); 823 Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result); 824 break; 825 } 826 case DeclSpec::TST_typename: { 827 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && 828 DS.getTypeSpecSign() == 0 && 829 "Can't handle qualifiers on typedef names yet!"); 830 Result = S.GetTypeFromParser(DS.getRepAsType()); 831 if (Result.isNull()) 832 declarator.setInvalidType(true); 833 else if (DeclSpec::ProtocolQualifierListTy PQ 834 = DS.getProtocolQualifiers()) { 835 if (const ObjCObjectType *ObjT = Result->getAs<ObjCObjectType>()) { 836 // Silently drop any existing protocol qualifiers. 837 // TODO: determine whether that's the right thing to do. 838 if (ObjT->getNumProtocols()) 839 Result = ObjT->getBaseType(); 840 841 if (DS.getNumProtocolQualifiers()) 842 Result = Context.getObjCObjectType(Result, 843 (ObjCProtocolDecl*const*) PQ, 844 DS.getNumProtocolQualifiers()); 845 } else if (Result->isObjCIdType()) { 846 // id<protocol-list> 847 Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy, 848 (ObjCProtocolDecl*const*) PQ, 849 DS.getNumProtocolQualifiers()); 850 Result = Context.getObjCObjectPointerType(Result); 851 } else if (Result->isObjCClassType()) { 852 // Class<protocol-list> 853 Result = Context.getObjCObjectType(Context.ObjCBuiltinClassTy, 854 (ObjCProtocolDecl*const*) PQ, 855 DS.getNumProtocolQualifiers()); 856 Result = Context.getObjCObjectPointerType(Result); 857 } else { 858 S.Diag(DeclLoc, diag::err_invalid_protocol_qualifiers) 859 << DS.getSourceRange(); 860 declarator.setInvalidType(true); 861 } 862 } 863 864 // TypeQuals handled by caller. 865 break; 866 } 867 case DeclSpec::TST_typeofType: 868 // FIXME: Preserve type source info. 869 Result = S.GetTypeFromParser(DS.getRepAsType()); 870 assert(!Result.isNull() && "Didn't get a type for typeof?"); 871 if (!Result->isDependentType()) 872 if (const TagType *TT = Result->getAs<TagType>()) 873 S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc()); 874 // TypeQuals handled by caller. 875 Result = Context.getTypeOfType(Result); 876 break; 877 case DeclSpec::TST_typeofExpr: { 878 Expr *E = DS.getRepAsExpr(); 879 assert(E && "Didn't get an expression for typeof?"); 880 // TypeQuals handled by caller. 881 Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc()); 882 if (Result.isNull()) { 883 Result = Context.IntTy; 884 declarator.setInvalidType(true); 885 } 886 break; 887 } 888 case DeclSpec::TST_decltype: { 889 Expr *E = DS.getRepAsExpr(); 890 assert(E && "Didn't get an expression for decltype?"); 891 // TypeQuals handled by caller. 892 Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc()); 893 if (Result.isNull()) { 894 Result = Context.IntTy; 895 declarator.setInvalidType(true); 896 } 897 break; 898 } 899 case DeclSpec::TST_underlyingType: 900 Result = S.GetTypeFromParser(DS.getRepAsType()); 901 assert(!Result.isNull() && "Didn't get a type for __underlying_type?"); 902 Result = S.BuildUnaryTransformType(Result, 903 UnaryTransformType::EnumUnderlyingType, 904 DS.getTypeSpecTypeLoc()); 905 if (Result.isNull()) { 906 Result = Context.IntTy; 907 declarator.setInvalidType(true); 908 } 909 break; 910 911 case DeclSpec::TST_auto: { 912 // TypeQuals handled by caller. 913 Result = Context.getAutoType(QualType()); 914 break; 915 } 916 917 case DeclSpec::TST_unknown_anytype: 918 Result = Context.UnknownAnyTy; 919 break; 920 921 case DeclSpec::TST_atomic: 922 Result = S.GetTypeFromParser(DS.getRepAsType()); 923 assert(!Result.isNull() && "Didn't get a type for _Atomic?"); 924 Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc()); 925 if (Result.isNull()) { 926 Result = Context.IntTy; 927 declarator.setInvalidType(true); 928 } 929 break; 930 931 case DeclSpec::TST_image1d_t: 932 Result = Context.OCLImage1dTy; 933 break; 934 935 case DeclSpec::TST_image1d_array_t: 936 Result = Context.OCLImage1dArrayTy; 937 break; 938 939 case DeclSpec::TST_image1d_buffer_t: 940 Result = Context.OCLImage1dBufferTy; 941 break; 942 943 case DeclSpec::TST_image2d_t: 944 Result = Context.OCLImage2dTy; 945 break; 946 947 case DeclSpec::TST_image2d_array_t: 948 Result = Context.OCLImage2dArrayTy; 949 break; 950 951 case DeclSpec::TST_image3d_t: 952 Result = Context.OCLImage3dTy; 953 break; 954 955 case DeclSpec::TST_event_t: 956 Result = Context.OCLEventTy; 957 break; 958 959 case DeclSpec::TST_error: 960 Result = Context.IntTy; 961 declarator.setInvalidType(true); 962 break; 963 } 964 965 // Handle complex types. 966 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) { 967 if (S.getLangOpts().Freestanding) 968 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex); 969 Result = Context.getComplexType(Result); 970 } else if (DS.isTypeAltiVecVector()) { 971 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result)); 972 assert(typeSize > 0 && "type size for vector must be greater than 0 bits"); 973 VectorType::VectorKind VecKind = VectorType::AltiVecVector; 974 if (DS.isTypeAltiVecPixel()) 975 VecKind = VectorType::AltiVecPixel; 976 else if (DS.isTypeAltiVecBool()) 977 VecKind = VectorType::AltiVecBool; 978 Result = Context.getVectorType(Result, 128/typeSize, VecKind); 979 } 980 981 // FIXME: Imaginary. 982 if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary) 983 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported); 984 985 // Before we process any type attributes, synthesize a block literal 986 // function declarator if necessary. 987 if (declarator.getContext() == Declarator::BlockLiteralContext) 988 maybeSynthesizeBlockSignature(state, Result); 989 990 // Apply any type attributes from the decl spec. This may cause the 991 // list of type attributes to be temporarily saved while the type 992 // attributes are pushed around. 993 if (AttributeList *attrs = DS.getAttributes().getList()) 994 processTypeAttrs(state, Result, TAL_DeclSpec, attrs); 995 996 // Apply const/volatile/restrict qualifiers to T. 997 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 998 999 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 1000 // or incomplete types shall not be restrict-qualified." C++ also allows 1001 // restrict-qualified references. 1002 if (TypeQuals & DeclSpec::TQ_restrict) { 1003 if (Result->isAnyPointerType() || Result->isReferenceType()) { 1004 QualType EltTy; 1005 if (Result->isObjCObjectPointerType()) 1006 EltTy = Result; 1007 else 1008 EltTy = Result->isPointerType() ? 1009 Result->getAs<PointerType>()->getPointeeType() : 1010 Result->getAs<ReferenceType>()->getPointeeType(); 1011 1012 // If we have a pointer or reference, the pointee must have an object 1013 // incomplete type. 1014 if (!EltTy->isIncompleteOrObjectType()) { 1015 S.Diag(DS.getRestrictSpecLoc(), 1016 diag::err_typecheck_invalid_restrict_invalid_pointee) 1017 << EltTy << DS.getSourceRange(); 1018 TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier. 1019 } 1020 } else { 1021 S.Diag(DS.getRestrictSpecLoc(), 1022 diag::err_typecheck_invalid_restrict_not_pointer) 1023 << Result << DS.getSourceRange(); 1024 TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier. 1025 } 1026 } 1027 1028 // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification 1029 // of a function type includes any type qualifiers, the behavior is 1030 // undefined." 1031 if (Result->isFunctionType() && TypeQuals) { 1032 // Get some location to point at, either the C or V location. 1033 SourceLocation Loc; 1034 if (TypeQuals & DeclSpec::TQ_const) 1035 Loc = DS.getConstSpecLoc(); 1036 else if (TypeQuals & DeclSpec::TQ_volatile) 1037 Loc = DS.getVolatileSpecLoc(); 1038 else { 1039 assert((TypeQuals & DeclSpec::TQ_restrict) && 1040 "Has CVR quals but not C, V, or R?"); 1041 Loc = DS.getRestrictSpecLoc(); 1042 } 1043 S.Diag(Loc, diag::warn_typecheck_function_qualifiers) 1044 << Result << DS.getSourceRange(); 1045 } 1046 1047 // C++ [dcl.ref]p1: 1048 // Cv-qualified references are ill-formed except when the 1049 // cv-qualifiers are introduced through the use of a typedef 1050 // (7.1.3) or of a template type argument (14.3), in which 1051 // case the cv-qualifiers are ignored. 1052 // FIXME: Shouldn't we be checking SCS_typedef here? 1053 if (DS.getTypeSpecType() == DeclSpec::TST_typename && 1054 TypeQuals && Result->isReferenceType()) { 1055 TypeQuals &= ~DeclSpec::TQ_const; 1056 TypeQuals &= ~DeclSpec::TQ_volatile; 1057 } 1058 1059 // C90 6.5.3 constraints: "The same type qualifier shall not appear more 1060 // than once in the same specifier-list or qualifier-list, either directly 1061 // or via one or more typedefs." 1062 if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus 1063 && TypeQuals & Result.getCVRQualifiers()) { 1064 if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) { 1065 S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec) 1066 << "const"; 1067 } 1068 1069 if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) { 1070 S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec) 1071 << "volatile"; 1072 } 1073 1074 // C90 doesn't have restrict, so it doesn't force us to produce a warning 1075 // in this case. 1076 } 1077 1078 Qualifiers Quals = Qualifiers::fromCVRMask(TypeQuals); 1079 Result = Context.getQualifiedType(Result, Quals); 1080 } 1081 1082 return Result; 1083} 1084 1085static std::string getPrintableNameForEntity(DeclarationName Entity) { 1086 if (Entity) 1087 return Entity.getAsString(); 1088 1089 return "type name"; 1090} 1091 1092QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc, 1093 Qualifiers Qs) { 1094 // Enforce C99 6.7.3p2: "Types other than pointer types derived from 1095 // object or incomplete types shall not be restrict-qualified." 1096 if (Qs.hasRestrict()) { 1097 unsigned DiagID = 0; 1098 QualType ProblemTy; 1099 1100 const Type *Ty = T->getCanonicalTypeInternal().getTypePtr(); 1101 if (const ReferenceType *RTy = dyn_cast<ReferenceType>(Ty)) { 1102 if (!RTy->getPointeeType()->isIncompleteOrObjectType()) { 1103 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee; 1104 ProblemTy = T->getAs<ReferenceType>()->getPointeeType(); 1105 } 1106 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) { 1107 if (!PTy->getPointeeType()->isIncompleteOrObjectType()) { 1108 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee; 1109 ProblemTy = T->getAs<PointerType>()->getPointeeType(); 1110 } 1111 } else if (const MemberPointerType *PTy = dyn_cast<MemberPointerType>(Ty)) { 1112 if (!PTy->getPointeeType()->isIncompleteOrObjectType()) { 1113 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee; 1114 ProblemTy = T->getAs<PointerType>()->getPointeeType(); 1115 } 1116 } else if (!Ty->isDependentType()) { 1117 // FIXME: this deserves a proper diagnostic 1118 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee; 1119 ProblemTy = T; 1120 } 1121 1122 if (DiagID) { 1123 Diag(Loc, DiagID) << ProblemTy; 1124 Qs.removeRestrict(); 1125 } 1126 } 1127 1128 return Context.getQualifiedType(T, Qs); 1129} 1130 1131/// \brief Build a paren type including \p T. 1132QualType Sema::BuildParenType(QualType T) { 1133 return Context.getParenType(T); 1134} 1135 1136/// Given that we're building a pointer or reference to the given 1137static QualType inferARCLifetimeForPointee(Sema &S, QualType type, 1138 SourceLocation loc, 1139 bool isReference) { 1140 // Bail out if retention is unrequired or already specified. 1141 if (!type->isObjCLifetimeType() || 1142 type.getObjCLifetime() != Qualifiers::OCL_None) 1143 return type; 1144 1145 Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None; 1146 1147 // If the object type is const-qualified, we can safely use 1148 // __unsafe_unretained. This is safe (because there are no read 1149 // barriers), and it'll be safe to coerce anything but __weak* to 1150 // the resulting type. 1151 if (type.isConstQualified()) { 1152 implicitLifetime = Qualifiers::OCL_ExplicitNone; 1153 1154 // Otherwise, check whether the static type does not require 1155 // retaining. This currently only triggers for Class (possibly 1156 // protocol-qualifed, and arrays thereof). 1157 } else if (type->isObjCARCImplicitlyUnretainedType()) { 1158 implicitLifetime = Qualifiers::OCL_ExplicitNone; 1159 1160 // If we are in an unevaluated context, like sizeof, skip adding a 1161 // qualification. 1162 } else if (S.isUnevaluatedContext()) { 1163 return type; 1164 1165 // If that failed, give an error and recover using __strong. __strong 1166 // is the option most likely to prevent spurious second-order diagnostics, 1167 // like when binding a reference to a field. 1168 } else { 1169 // These types can show up in private ivars in system headers, so 1170 // we need this to not be an error in those cases. Instead we 1171 // want to delay. 1172 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) { 1173 S.DelayedDiagnostics.add( 1174 sema::DelayedDiagnostic::makeForbiddenType(loc, 1175 diag::err_arc_indirect_no_ownership, type, isReference)); 1176 } else { 1177 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference; 1178 } 1179 implicitLifetime = Qualifiers::OCL_Strong; 1180 } 1181 assert(implicitLifetime && "didn't infer any lifetime!"); 1182 1183 Qualifiers qs; 1184 qs.addObjCLifetime(implicitLifetime); 1185 return S.Context.getQualifiedType(type, qs); 1186} 1187 1188/// \brief Build a pointer type. 1189/// 1190/// \param T The type to which we'll be building a pointer. 1191/// 1192/// \param Loc The location of the entity whose type involves this 1193/// pointer type or, if there is no such entity, the location of the 1194/// type that will have pointer type. 1195/// 1196/// \param Entity The name of the entity that involves the pointer 1197/// type, if known. 1198/// 1199/// \returns A suitable pointer type, if there are no 1200/// errors. Otherwise, returns a NULL type. 1201QualType Sema::BuildPointerType(QualType T, 1202 SourceLocation Loc, DeclarationName Entity) { 1203 if (T->isReferenceType()) { 1204 // C++ 8.3.2p4: There shall be no ... pointers to references ... 1205 Diag(Loc, diag::err_illegal_decl_pointer_to_reference) 1206 << getPrintableNameForEntity(Entity) << T; 1207 return QualType(); 1208 } 1209 1210 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType"); 1211 1212 // In ARC, it is forbidden to build pointers to unqualified pointers. 1213 if (getLangOpts().ObjCAutoRefCount) 1214 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false); 1215 1216 // Build the pointer type. 1217 return Context.getPointerType(T); 1218} 1219 1220/// \brief Build a reference type. 1221/// 1222/// \param T The type to which we'll be building a reference. 1223/// 1224/// \param Loc The location of the entity whose type involves this 1225/// reference type or, if there is no such entity, the location of the 1226/// type that will have reference type. 1227/// 1228/// \param Entity The name of the entity that involves the reference 1229/// type, if known. 1230/// 1231/// \returns A suitable reference type, if there are no 1232/// errors. Otherwise, returns a NULL type. 1233QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue, 1234 SourceLocation Loc, 1235 DeclarationName Entity) { 1236 assert(Context.getCanonicalType(T) != Context.OverloadTy && 1237 "Unresolved overloaded function type"); 1238 1239 // C++0x [dcl.ref]p6: 1240 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a 1241 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a 1242 // type T, an attempt to create the type "lvalue reference to cv TR" creates 1243 // the type "lvalue reference to T", while an attempt to create the type 1244 // "rvalue reference to cv TR" creates the type TR. 1245 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>(); 1246 1247 // C++ [dcl.ref]p4: There shall be no references to references. 1248 // 1249 // According to C++ DR 106, references to references are only 1250 // diagnosed when they are written directly (e.g., "int & &"), 1251 // but not when they happen via a typedef: 1252 // 1253 // typedef int& intref; 1254 // typedef intref& intref2; 1255 // 1256 // Parser::ParseDeclaratorInternal diagnoses the case where 1257 // references are written directly; here, we handle the 1258 // collapsing of references-to-references as described in C++0x. 1259 // DR 106 and 540 introduce reference-collapsing into C++98/03. 1260 1261 // C++ [dcl.ref]p1: 1262 // A declarator that specifies the type "reference to cv void" 1263 // is ill-formed. 1264 if (T->isVoidType()) { 1265 Diag(Loc, diag::err_reference_to_void); 1266 return QualType(); 1267 } 1268 1269 // In ARC, it is forbidden to build references to unqualified pointers. 1270 if (getLangOpts().ObjCAutoRefCount) 1271 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true); 1272 1273 // Handle restrict on references. 1274 if (LValueRef) 1275 return Context.getLValueReferenceType(T, SpelledAsLValue); 1276 return Context.getRValueReferenceType(T); 1277} 1278 1279/// Check whether the specified array size makes the array type a VLA. If so, 1280/// return true, if not, return the size of the array in SizeVal. 1281static bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal) { 1282 // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode 1283 // (like gnu99, but not c99) accept any evaluatable value as an extension. 1284 class VLADiagnoser : public Sema::VerifyICEDiagnoser { 1285 public: 1286 VLADiagnoser() : Sema::VerifyICEDiagnoser(true) {} 1287 1288 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 1289 } 1290 1291 virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR) { 1292 S.Diag(Loc, diag::ext_vla_folded_to_constant) << SR; 1293 } 1294 } Diagnoser; 1295 1296 return S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser, 1297 S.LangOpts.GNUMode).isInvalid(); 1298} 1299 1300 1301/// \brief Build an array type. 1302/// 1303/// \param T The type of each element in the array. 1304/// 1305/// \param ASM C99 array size modifier (e.g., '*', 'static'). 1306/// 1307/// \param ArraySize Expression describing the size of the array. 1308/// 1309/// \param Brackets The range from the opening '[' to the closing ']'. 1310/// 1311/// \param Entity The name of the entity that involves the array 1312/// type, if known. 1313/// 1314/// \returns A suitable array type, if there are no errors. Otherwise, 1315/// returns a NULL type. 1316QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM, 1317 Expr *ArraySize, unsigned Quals, 1318 SourceRange Brackets, DeclarationName Entity) { 1319 1320 SourceLocation Loc = Brackets.getBegin(); 1321 if (getLangOpts().CPlusPlus) { 1322 // C++ [dcl.array]p1: 1323 // T is called the array element type; this type shall not be a reference 1324 // type, the (possibly cv-qualified) type void, a function type or an 1325 // abstract class type. 1326 // 1327 // C++ [dcl.array]p3: 1328 // When several "array of" specifications are adjacent, [...] only the 1329 // first of the constant expressions that specify the bounds of the arrays 1330 // may be omitted. 1331 // 1332 // Note: function types are handled in the common path with C. 1333 if (T->isReferenceType()) { 1334 Diag(Loc, diag::err_illegal_decl_array_of_references) 1335 << getPrintableNameForEntity(Entity) << T; 1336 return QualType(); 1337 } 1338 1339 if (T->isVoidType() || T->isIncompleteArrayType()) { 1340 Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T; 1341 return QualType(); 1342 } 1343 1344 if (RequireNonAbstractType(Brackets.getBegin(), T, 1345 diag::err_array_of_abstract_type)) 1346 return QualType(); 1347 1348 } else { 1349 // C99 6.7.5.2p1: If the element type is an incomplete or function type, 1350 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]()) 1351 if (RequireCompleteType(Loc, T, 1352 diag::err_illegal_decl_array_incomplete_type)) 1353 return QualType(); 1354 } 1355 1356 if (T->isFunctionType()) { 1357 Diag(Loc, diag::err_illegal_decl_array_of_functions) 1358 << getPrintableNameForEntity(Entity) << T; 1359 return QualType(); 1360 } 1361 1362 if (T->getContainedAutoType()) { 1363 Diag(Loc, diag::err_illegal_decl_array_of_auto) 1364 << getPrintableNameForEntity(Entity) << T; 1365 return QualType(); 1366 } 1367 1368 if (const RecordType *EltTy = T->getAs<RecordType>()) { 1369 // If the element type is a struct or union that contains a variadic 1370 // array, accept it as a GNU extension: C99 6.7.2.1p2. 1371 if (EltTy->getDecl()->hasFlexibleArrayMember()) 1372 Diag(Loc, diag::ext_flexible_array_in_array) << T; 1373 } else if (T->isObjCObjectType()) { 1374 Diag(Loc, diag::err_objc_array_of_interfaces) << T; 1375 return QualType(); 1376 } 1377 1378 // Do placeholder conversions on the array size expression. 1379 if (ArraySize && ArraySize->hasPlaceholderType()) { 1380 ExprResult Result = CheckPlaceholderExpr(ArraySize); 1381 if (Result.isInvalid()) return QualType(); 1382 ArraySize = Result.take(); 1383 } 1384 1385 // Do lvalue-to-rvalue conversions on the array size expression. 1386 if (ArraySize && !ArraySize->isRValue()) { 1387 ExprResult Result = DefaultLvalueConversion(ArraySize); 1388 if (Result.isInvalid()) 1389 return QualType(); 1390 1391 ArraySize = Result.take(); 1392 } 1393 1394 // C99 6.7.5.2p1: The size expression shall have integer type. 1395 // C++11 allows contextual conversions to such types. 1396 if (!getLangOpts().CPlusPlus11 && 1397 ArraySize && !ArraySize->isTypeDependent() && 1398 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) { 1399 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int) 1400 << ArraySize->getType() << ArraySize->getSourceRange(); 1401 return QualType(); 1402 } 1403 1404 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType())); 1405 if (!ArraySize) { 1406 if (ASM == ArrayType::Star) 1407 T = Context.getVariableArrayType(T, 0, ASM, Quals, Brackets); 1408 else 1409 T = Context.getIncompleteArrayType(T, ASM, Quals); 1410 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) { 1411 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets); 1412 } else if ((!T->isDependentType() && !T->isIncompleteType() && 1413 !T->isConstantSizeType()) || 1414 isArraySizeVLA(*this, ArraySize, ConstVal)) { 1415 // Even in C++11, don't allow contextual conversions in the array bound 1416 // of a VLA. 1417 if (getLangOpts().CPlusPlus11 && 1418 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) { 1419 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int) 1420 << ArraySize->getType() << ArraySize->getSourceRange(); 1421 return QualType(); 1422 } 1423 1424 // C99: an array with an element type that has a non-constant-size is a VLA. 1425 // C99: an array with a non-ICE size is a VLA. We accept any expression 1426 // that we can fold to a non-zero positive value as an extension. 1427 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets); 1428 } else { 1429 // C99 6.7.5.2p1: If the expression is a constant expression, it shall 1430 // have a value greater than zero. 1431 if (ConstVal.isSigned() && ConstVal.isNegative()) { 1432 if (Entity) 1433 Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size) 1434 << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange(); 1435 else 1436 Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size) 1437 << ArraySize->getSourceRange(); 1438 return QualType(); 1439 } 1440 if (ConstVal == 0) { 1441 // GCC accepts zero sized static arrays. We allow them when 1442 // we're not in a SFINAE context. 1443 Diag(ArraySize->getLocStart(), 1444 isSFINAEContext()? diag::err_typecheck_zero_array_size 1445 : diag::ext_typecheck_zero_array_size) 1446 << ArraySize->getSourceRange(); 1447 1448 if (ASM == ArrayType::Static) { 1449 Diag(ArraySize->getLocStart(), 1450 diag::warn_typecheck_zero_static_array_size) 1451 << ArraySize->getSourceRange(); 1452 ASM = ArrayType::Normal; 1453 } 1454 } else if (!T->isDependentType() && !T->isVariablyModifiedType() && 1455 !T->isIncompleteType()) { 1456 // Is the array too large? 1457 unsigned ActiveSizeBits 1458 = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal); 1459 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) 1460 Diag(ArraySize->getLocStart(), diag::err_array_too_large) 1461 << ConstVal.toString(10) 1462 << ArraySize->getSourceRange(); 1463 } 1464 1465 T = Context.getConstantArrayType(T, ConstVal, ASM, Quals); 1466 } 1467 1468 // OpenCL v1.2 s6.9.d: variable length arrays are not supported. 1469 if (getLangOpts().OpenCL && T->isVariableArrayType()) { 1470 Diag(Loc, diag::err_opencl_vla); 1471 return QualType(); 1472 } 1473 // If this is not C99, extwarn about VLA's and C99 array size modifiers. 1474 if (!getLangOpts().C99) { 1475 if (T->isVariableArrayType()) { 1476 // Prohibit the use of non-POD types in VLAs. 1477 QualType BaseT = Context.getBaseElementType(T); 1478 if (!T->isDependentType() && 1479 !BaseT.isPODType(Context) && 1480 !BaseT->isObjCLifetimeType()) { 1481 Diag(Loc, diag::err_vla_non_pod) 1482 << BaseT; 1483 return QualType(); 1484 } 1485 // Prohibit the use of VLAs during template argument deduction. 1486 else if (isSFINAEContext()) { 1487 Diag(Loc, diag::err_vla_in_sfinae); 1488 return QualType(); 1489 } 1490 // Just extwarn about VLAs. 1491 else 1492 Diag(Loc, diag::ext_vla); 1493 } else if (ASM != ArrayType::Normal || Quals != 0) 1494 Diag(Loc, 1495 getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx 1496 : diag::ext_c99_array_usage) << ASM; 1497 } 1498 1499 if (T->isVariableArrayType()) { 1500 // Warn about VLAs for -Wvla. 1501 Diag(Loc, diag::warn_vla_used); 1502 } 1503 1504 return T; 1505} 1506 1507/// \brief Build an ext-vector type. 1508/// 1509/// Run the required checks for the extended vector type. 1510QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize, 1511 SourceLocation AttrLoc) { 1512 // unlike gcc's vector_size attribute, we do not allow vectors to be defined 1513 // in conjunction with complex types (pointers, arrays, functions, etc.). 1514 if (!T->isDependentType() && 1515 !T->isIntegerType() && !T->isRealFloatingType()) { 1516 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T; 1517 return QualType(); 1518 } 1519 1520 if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) { 1521 llvm::APSInt vecSize(32); 1522 if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) { 1523 Diag(AttrLoc, diag::err_attribute_argument_not_int) 1524 << "ext_vector_type" << ArraySize->getSourceRange(); 1525 return QualType(); 1526 } 1527 1528 // unlike gcc's vector_size attribute, the size is specified as the 1529 // number of elements, not the number of bytes. 1530 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue()); 1531 1532 if (vectorSize == 0) { 1533 Diag(AttrLoc, diag::err_attribute_zero_size) 1534 << ArraySize->getSourceRange(); 1535 return QualType(); 1536 } 1537 1538 return Context.getExtVectorType(T, vectorSize); 1539 } 1540 1541 return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc); 1542} 1543 1544/// \brief Build a function type. 1545/// 1546/// This routine checks the function type according to C++ rules and 1547/// under the assumption that the result type and parameter types have 1548/// just been instantiated from a template. It therefore duplicates 1549/// some of the behavior of GetTypeForDeclarator, but in a much 1550/// simpler form that is only suitable for this narrow use case. 1551/// 1552/// \param T The return type of the function. 1553/// 1554/// \param ParamTypes The parameter types of the function. This array 1555/// will be modified to account for adjustments to the types of the 1556/// function parameters. 1557/// 1558/// \param NumParamTypes The number of parameter types in ParamTypes. 1559/// 1560/// \param Variadic Whether this is a variadic function type. 1561/// 1562/// \param HasTrailingReturn Whether this function has a trailing return type. 1563/// 1564/// \param Quals The cvr-qualifiers to be applied to the function type. 1565/// 1566/// \param Loc The location of the entity whose type involves this 1567/// function type or, if there is no such entity, the location of the 1568/// type that will have function type. 1569/// 1570/// \param Entity The name of the entity that involves the function 1571/// type, if known. 1572/// 1573/// \returns A suitable function type, if there are no 1574/// errors. Otherwise, returns a NULL type. 1575QualType Sema::BuildFunctionType(QualType T, 1576 QualType *ParamTypes, 1577 unsigned NumParamTypes, 1578 bool Variadic, bool HasTrailingReturn, 1579 unsigned Quals, 1580 RefQualifierKind RefQualifier, 1581 SourceLocation Loc, DeclarationName Entity, 1582 FunctionType::ExtInfo Info) { 1583 if (T->isArrayType() || T->isFunctionType()) { 1584 Diag(Loc, diag::err_func_returning_array_function) 1585 << T->isFunctionType() << T; 1586 return QualType(); 1587 } 1588 1589 // Functions cannot return half FP. 1590 if (T->isHalfType()) { 1591 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 << 1592 FixItHint::CreateInsertion(Loc, "*"); 1593 return QualType(); 1594 } 1595 1596 bool Invalid = false; 1597 for (unsigned Idx = 0; Idx < NumParamTypes; ++Idx) { 1598 // FIXME: Loc is too inprecise here, should use proper locations for args. 1599 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]); 1600 if (ParamType->isVoidType()) { 1601 Diag(Loc, diag::err_param_with_void_type); 1602 Invalid = true; 1603 } else if (ParamType->isHalfType()) { 1604 // Disallow half FP arguments. 1605 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 << 1606 FixItHint::CreateInsertion(Loc, "*"); 1607 Invalid = true; 1608 } 1609 1610 ParamTypes[Idx] = ParamType; 1611 } 1612 1613 if (Invalid) 1614 return QualType(); 1615 1616 FunctionProtoType::ExtProtoInfo EPI; 1617 EPI.Variadic = Variadic; 1618 EPI.HasTrailingReturn = HasTrailingReturn; 1619 EPI.TypeQuals = Quals; 1620 EPI.RefQualifier = RefQualifier; 1621 EPI.ExtInfo = Info; 1622 1623 return Context.getFunctionType(T, ParamTypes, NumParamTypes, EPI); 1624} 1625 1626/// \brief Build a member pointer type \c T Class::*. 1627/// 1628/// \param T the type to which the member pointer refers. 1629/// \param Class the class type into which the member pointer points. 1630/// \param Loc the location where this type begins 1631/// \param Entity the name of the entity that will have this member pointer type 1632/// 1633/// \returns a member pointer type, if successful, or a NULL type if there was 1634/// an error. 1635QualType Sema::BuildMemberPointerType(QualType T, QualType Class, 1636 SourceLocation Loc, 1637 DeclarationName Entity) { 1638 // Verify that we're not building a pointer to pointer to function with 1639 // exception specification. 1640 if (CheckDistantExceptionSpec(T)) { 1641 Diag(Loc, diag::err_distant_exception_spec); 1642 1643 // FIXME: If we're doing this as part of template instantiation, 1644 // we should return immediately. 1645 1646 // Build the type anyway, but use the canonical type so that the 1647 // exception specifiers are stripped off. 1648 T = Context.getCanonicalType(T); 1649 } 1650 1651 // C++ 8.3.3p3: A pointer to member shall not point to ... a member 1652 // with reference type, or "cv void." 1653 if (T->isReferenceType()) { 1654 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference) 1655 << (Entity? Entity.getAsString() : "type name") << T; 1656 return QualType(); 1657 } 1658 1659 if (T->isVoidType()) { 1660 Diag(Loc, diag::err_illegal_decl_mempointer_to_void) 1661 << (Entity? Entity.getAsString() : "type name"); 1662 return QualType(); 1663 } 1664 1665 if (!Class->isDependentType() && !Class->isRecordType()) { 1666 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class; 1667 return QualType(); 1668 } 1669 1670 // C++ allows the class type in a member pointer to be an incomplete type. 1671 // In the Microsoft ABI, the size of the member pointer can vary 1672 // according to the class type, which means that we really need a 1673 // complete type if possible, which means we need to instantiate templates. 1674 // 1675 // For now, just require a complete type, which will instantiate 1676 // templates. This will also error if the type is just forward-declared, 1677 // which is a bug, but it's a bug that saves us from dealing with some 1678 // complexities at the moment. 1679 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 1680 RequireCompleteType(Loc, Class, diag::err_incomplete_type)) 1681 return QualType(); 1682 1683 return Context.getMemberPointerType(T, Class.getTypePtr()); 1684} 1685 1686/// \brief Build a block pointer type. 1687/// 1688/// \param T The type to which we'll be building a block pointer. 1689/// 1690/// \param Loc The source location, used for diagnostics. 1691/// 1692/// \param Entity The name of the entity that involves the block pointer 1693/// type, if known. 1694/// 1695/// \returns A suitable block pointer type, if there are no 1696/// errors. Otherwise, returns a NULL type. 1697QualType Sema::BuildBlockPointerType(QualType T, 1698 SourceLocation Loc, 1699 DeclarationName Entity) { 1700 if (!T->isFunctionType()) { 1701 Diag(Loc, diag::err_nonfunction_block_type); 1702 return QualType(); 1703 } 1704 1705 return Context.getBlockPointerType(T); 1706} 1707 1708QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) { 1709 QualType QT = Ty.get(); 1710 if (QT.isNull()) { 1711 if (TInfo) *TInfo = 0; 1712 return QualType(); 1713 } 1714 1715 TypeSourceInfo *DI = 0; 1716 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) { 1717 QT = LIT->getType(); 1718 DI = LIT->getTypeSourceInfo(); 1719 } 1720 1721 if (TInfo) *TInfo = DI; 1722 return QT; 1723} 1724 1725static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, 1726 Qualifiers::ObjCLifetime ownership, 1727 unsigned chunkIndex); 1728 1729/// Given that this is the declaration of a parameter under ARC, 1730/// attempt to infer attributes and such for pointer-to-whatever 1731/// types. 1732static void inferARCWriteback(TypeProcessingState &state, 1733 QualType &declSpecType) { 1734 Sema &S = state.getSema(); 1735 Declarator &declarator = state.getDeclarator(); 1736 1737 // TODO: should we care about decl qualifiers? 1738 1739 // Check whether the declarator has the expected form. We walk 1740 // from the inside out in order to make the block logic work. 1741 unsigned outermostPointerIndex = 0; 1742 bool isBlockPointer = false; 1743 unsigned numPointers = 0; 1744 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { 1745 unsigned chunkIndex = i; 1746 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex); 1747 switch (chunk.Kind) { 1748 case DeclaratorChunk::Paren: 1749 // Ignore parens. 1750 break; 1751 1752 case DeclaratorChunk::Reference: 1753 case DeclaratorChunk::Pointer: 1754 // Count the number of pointers. Treat references 1755 // interchangeably as pointers; if they're mis-ordered, normal 1756 // type building will discover that. 1757 outermostPointerIndex = chunkIndex; 1758 numPointers++; 1759 break; 1760 1761 case DeclaratorChunk::BlockPointer: 1762 // If we have a pointer to block pointer, that's an acceptable 1763 // indirect reference; anything else is not an application of 1764 // the rules. 1765 if (numPointers != 1) return; 1766 numPointers++; 1767 outermostPointerIndex = chunkIndex; 1768 isBlockPointer = true; 1769 1770 // We don't care about pointer structure in return values here. 1771 goto done; 1772 1773 case DeclaratorChunk::Array: // suppress if written (id[])? 1774 case DeclaratorChunk::Function: 1775 case DeclaratorChunk::MemberPointer: 1776 return; 1777 } 1778 } 1779 done: 1780 1781 // If we have *one* pointer, then we want to throw the qualifier on 1782 // the declaration-specifiers, which means that it needs to be a 1783 // retainable object type. 1784 if (numPointers == 1) { 1785 // If it's not a retainable object type, the rule doesn't apply. 1786 if (!declSpecType->isObjCRetainableType()) return; 1787 1788 // If it already has lifetime, don't do anything. 1789 if (declSpecType.getObjCLifetime()) return; 1790 1791 // Otherwise, modify the type in-place. 1792 Qualifiers qs; 1793 1794 if (declSpecType->isObjCARCImplicitlyUnretainedType()) 1795 qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone); 1796 else 1797 qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing); 1798 declSpecType = S.Context.getQualifiedType(declSpecType, qs); 1799 1800 // If we have *two* pointers, then we want to throw the qualifier on 1801 // the outermost pointer. 1802 } else if (numPointers == 2) { 1803 // If we don't have a block pointer, we need to check whether the 1804 // declaration-specifiers gave us something that will turn into a 1805 // retainable object pointer after we slap the first pointer on it. 1806 if (!isBlockPointer && !declSpecType->isObjCObjectType()) 1807 return; 1808 1809 // Look for an explicit lifetime attribute there. 1810 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex); 1811 if (chunk.Kind != DeclaratorChunk::Pointer && 1812 chunk.Kind != DeclaratorChunk::BlockPointer) 1813 return; 1814 for (const AttributeList *attr = chunk.getAttrs(); attr; 1815 attr = attr->getNext()) 1816 if (attr->getKind() == AttributeList::AT_ObjCOwnership) 1817 return; 1818 1819 transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing, 1820 outermostPointerIndex); 1821 1822 // Any other number of pointers/references does not trigger the rule. 1823 } else return; 1824 1825 // TODO: mark whether we did this inference? 1826} 1827 1828static void DiagnoseIgnoredQualifiers(unsigned Quals, 1829 SourceLocation ConstQualLoc, 1830 SourceLocation VolatileQualLoc, 1831 SourceLocation RestrictQualLoc, 1832 Sema& S) { 1833 std::string QualStr; 1834 unsigned NumQuals = 0; 1835 SourceLocation Loc; 1836 1837 FixItHint ConstFixIt; 1838 FixItHint VolatileFixIt; 1839 FixItHint RestrictFixIt; 1840 1841 const SourceManager &SM = S.getSourceManager(); 1842 1843 // FIXME: The locations here are set kind of arbitrarily. It'd be nicer to 1844 // find a range and grow it to encompass all the qualifiers, regardless of 1845 // the order in which they textually appear. 1846 if (Quals & Qualifiers::Const) { 1847 ConstFixIt = FixItHint::CreateRemoval(ConstQualLoc); 1848 QualStr = "const"; 1849 ++NumQuals; 1850 if (!Loc.isValid() || SM.isBeforeInTranslationUnit(ConstQualLoc, Loc)) 1851 Loc = ConstQualLoc; 1852 } 1853 if (Quals & Qualifiers::Volatile) { 1854 VolatileFixIt = FixItHint::CreateRemoval(VolatileQualLoc); 1855 QualStr += (NumQuals == 0 ? "volatile" : " volatile"); 1856 ++NumQuals; 1857 if (!Loc.isValid() || SM.isBeforeInTranslationUnit(VolatileQualLoc, Loc)) 1858 Loc = VolatileQualLoc; 1859 } 1860 if (Quals & Qualifiers::Restrict) { 1861 RestrictFixIt = FixItHint::CreateRemoval(RestrictQualLoc); 1862 QualStr += (NumQuals == 0 ? "restrict" : " restrict"); 1863 ++NumQuals; 1864 if (!Loc.isValid() || SM.isBeforeInTranslationUnit(RestrictQualLoc, Loc)) 1865 Loc = RestrictQualLoc; 1866 } 1867 1868 assert(NumQuals > 0 && "No known qualifiers?"); 1869 1870 S.Diag(Loc, diag::warn_qual_return_type) 1871 << QualStr << NumQuals << ConstFixIt << VolatileFixIt << RestrictFixIt; 1872} 1873 1874static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state, 1875 TypeSourceInfo *&ReturnTypeInfo) { 1876 Sema &SemaRef = state.getSema(); 1877 Declarator &D = state.getDeclarator(); 1878 QualType T; 1879 ReturnTypeInfo = 0; 1880 1881 // The TagDecl owned by the DeclSpec. 1882 TagDecl *OwnedTagDecl = 0; 1883 1884 switch (D.getName().getKind()) { 1885 case UnqualifiedId::IK_ImplicitSelfParam: 1886 case UnqualifiedId::IK_OperatorFunctionId: 1887 case UnqualifiedId::IK_Identifier: 1888 case UnqualifiedId::IK_LiteralOperatorId: 1889 case UnqualifiedId::IK_TemplateId: 1890 T = ConvertDeclSpecToType(state); 1891 1892 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) { 1893 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 1894 // Owned declaration is embedded in declarator. 1895 OwnedTagDecl->setEmbeddedInDeclarator(true); 1896 } 1897 break; 1898 1899 case UnqualifiedId::IK_ConstructorName: 1900 case UnqualifiedId::IK_ConstructorTemplateId: 1901 case UnqualifiedId::IK_DestructorName: 1902 // Constructors and destructors don't have return types. Use 1903 // "void" instead. 1904 T = SemaRef.Context.VoidTy; 1905 if (AttributeList *attrs = D.getDeclSpec().getAttributes().getList()) 1906 processTypeAttrs(state, T, TAL_DeclSpec, attrs); 1907 break; 1908 1909 case UnqualifiedId::IK_ConversionFunctionId: 1910 // The result type of a conversion function is the type that it 1911 // converts to. 1912 T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId, 1913 &ReturnTypeInfo); 1914 break; 1915 } 1916 1917 if (D.getAttributes()) 1918 distributeTypeAttrsFromDeclarator(state, T); 1919 1920 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context. 1921 // In C++11, a function declarator using 'auto' must have a trailing return 1922 // type (this is checked later) and we can skip this. In other languages 1923 // using auto, we need to check regardless. 1924 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto && 1925 (!SemaRef.getLangOpts().CPlusPlus11 || !D.isFunctionDeclarator())) { 1926 int Error = -1; 1927 1928 switch (D.getContext()) { 1929 case Declarator::KNRTypeListContext: 1930 llvm_unreachable("K&R type lists aren't allowed in C++"); 1931 case Declarator::LambdaExprContext: 1932 llvm_unreachable("Can't specify a type specifier in lambda grammar"); 1933 case Declarator::ObjCParameterContext: 1934 case Declarator::ObjCResultContext: 1935 case Declarator::PrototypeContext: 1936 Error = 0; // Function prototype 1937 break; 1938 case Declarator::MemberContext: 1939 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static) 1940 break; 1941 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) { 1942 case TTK_Enum: llvm_unreachable("unhandled tag kind"); 1943 case TTK_Struct: Error = 1; /* Struct member */ break; 1944 case TTK_Union: Error = 2; /* Union member */ break; 1945 case TTK_Class: Error = 3; /* Class member */ break; 1946 case TTK_Interface: Error = 4; /* Interface member */ break; 1947 } 1948 break; 1949 case Declarator::CXXCatchContext: 1950 case Declarator::ObjCCatchContext: 1951 Error = 5; // Exception declaration 1952 break; 1953 case Declarator::TemplateParamContext: 1954 Error = 6; // Template parameter 1955 break; 1956 case Declarator::BlockLiteralContext: 1957 Error = 7; // Block literal 1958 break; 1959 case Declarator::TemplateTypeArgContext: 1960 Error = 8; // Template type argument 1961 break; 1962 case Declarator::AliasDeclContext: 1963 case Declarator::AliasTemplateContext: 1964 Error = 10; // Type alias 1965 break; 1966 case Declarator::TrailingReturnContext: 1967 Error = 11; // Function return type 1968 break; 1969 case Declarator::TypeNameContext: 1970 Error = 12; // Generic 1971 break; 1972 case Declarator::FileContext: 1973 case Declarator::BlockContext: 1974 case Declarator::ForContext: 1975 case Declarator::ConditionContext: 1976 case Declarator::CXXNewContext: 1977 break; 1978 } 1979 1980 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 1981 Error = 9; 1982 1983 // In Objective-C it is an error to use 'auto' on a function declarator. 1984 if (D.isFunctionDeclarator()) 1985 Error = 11; 1986 1987 // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator 1988 // contains a trailing return type. That is only legal at the outermost 1989 // level. Check all declarator chunks (outermost first) anyway, to give 1990 // better diagnostics. 1991 if (SemaRef.getLangOpts().CPlusPlus11 && Error != -1) { 1992 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 1993 unsigned chunkIndex = e - i - 1; 1994 state.setCurrentChunkIndex(chunkIndex); 1995 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex); 1996 if (DeclType.Kind == DeclaratorChunk::Function) { 1997 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 1998 if (FTI.hasTrailingReturnType()) { 1999 Error = -1; 2000 break; 2001 } 2002 } 2003 } 2004 } 2005 2006 if (Error != -1) { 2007 SemaRef.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 2008 diag::err_auto_not_allowed) 2009 << Error; 2010 T = SemaRef.Context.IntTy; 2011 D.setInvalidType(true); 2012 } else 2013 SemaRef.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 2014 diag::warn_cxx98_compat_auto_type_specifier); 2015 } 2016 2017 if (SemaRef.getLangOpts().CPlusPlus && 2018 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) { 2019 // Check the contexts where C++ forbids the declaration of a new class 2020 // or enumeration in a type-specifier-seq. 2021 switch (D.getContext()) { 2022 case Declarator::TrailingReturnContext: 2023 // Class and enumeration definitions are syntactically not allowed in 2024 // trailing return types. 2025 llvm_unreachable("parser should not have allowed this"); 2026 break; 2027 case Declarator::FileContext: 2028 case Declarator::MemberContext: 2029 case Declarator::BlockContext: 2030 case Declarator::ForContext: 2031 case Declarator::BlockLiteralContext: 2032 case Declarator::LambdaExprContext: 2033 // C++11 [dcl.type]p3: 2034 // A type-specifier-seq shall not define a class or enumeration unless 2035 // it appears in the type-id of an alias-declaration (7.1.3) that is not 2036 // the declaration of a template-declaration. 2037 case Declarator::AliasDeclContext: 2038 break; 2039 case Declarator::AliasTemplateContext: 2040 SemaRef.Diag(OwnedTagDecl->getLocation(), 2041 diag::err_type_defined_in_alias_template) 2042 << SemaRef.Context.getTypeDeclType(OwnedTagDecl); 2043 D.setInvalidType(true); 2044 break; 2045 case Declarator::TypeNameContext: 2046 case Declarator::TemplateParamContext: 2047 case Declarator::CXXNewContext: 2048 case Declarator::CXXCatchContext: 2049 case Declarator::ObjCCatchContext: 2050 case Declarator::TemplateTypeArgContext: 2051 SemaRef.Diag(OwnedTagDecl->getLocation(), 2052 diag::err_type_defined_in_type_specifier) 2053 << SemaRef.Context.getTypeDeclType(OwnedTagDecl); 2054 D.setInvalidType(true); 2055 break; 2056 case Declarator::PrototypeContext: 2057 case Declarator::ObjCParameterContext: 2058 case Declarator::ObjCResultContext: 2059 case Declarator::KNRTypeListContext: 2060 // C++ [dcl.fct]p6: 2061 // Types shall not be defined in return or parameter types. 2062 SemaRef.Diag(OwnedTagDecl->getLocation(), 2063 diag::err_type_defined_in_param_type) 2064 << SemaRef.Context.getTypeDeclType(OwnedTagDecl); 2065 D.setInvalidType(true); 2066 break; 2067 case Declarator::ConditionContext: 2068 // C++ 6.4p2: 2069 // The type-specifier-seq shall not contain typedef and shall not declare 2070 // a new class or enumeration. 2071 SemaRef.Diag(OwnedTagDecl->getLocation(), 2072 diag::err_type_defined_in_condition); 2073 D.setInvalidType(true); 2074 break; 2075 } 2076 } 2077 2078 return T; 2079} 2080 2081static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){ 2082 std::string Quals = 2083 Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString(); 2084 2085 switch (FnTy->getRefQualifier()) { 2086 case RQ_None: 2087 break; 2088 2089 case RQ_LValue: 2090 if (!Quals.empty()) 2091 Quals += ' '; 2092 Quals += '&'; 2093 break; 2094 2095 case RQ_RValue: 2096 if (!Quals.empty()) 2097 Quals += ' '; 2098 Quals += "&&"; 2099 break; 2100 } 2101 2102 return Quals; 2103} 2104 2105/// Check that the function type T, which has a cv-qualifier or a ref-qualifier, 2106/// can be contained within the declarator chunk DeclType, and produce an 2107/// appropriate diagnostic if not. 2108static void checkQualifiedFunction(Sema &S, QualType T, 2109 DeclaratorChunk &DeclType) { 2110 // C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6: a function type with a 2111 // cv-qualifier or a ref-qualifier can only appear at the topmost level 2112 // of a type. 2113 int DiagKind = -1; 2114 switch (DeclType.Kind) { 2115 case DeclaratorChunk::Paren: 2116 case DeclaratorChunk::MemberPointer: 2117 // These cases are permitted. 2118 return; 2119 case DeclaratorChunk::Array: 2120 case DeclaratorChunk::Function: 2121 // These cases don't allow function types at all; no need to diagnose the 2122 // qualifiers separately. 2123 return; 2124 case DeclaratorChunk::BlockPointer: 2125 DiagKind = 0; 2126 break; 2127 case DeclaratorChunk::Pointer: 2128 DiagKind = 1; 2129 break; 2130 case DeclaratorChunk::Reference: 2131 DiagKind = 2; 2132 break; 2133 } 2134 2135 assert(DiagKind != -1); 2136 S.Diag(DeclType.Loc, diag::err_compound_qualified_function_type) 2137 << DiagKind << isa<FunctionType>(T.IgnoreParens()) << T 2138 << getFunctionQualifiersAsString(T->castAs<FunctionProtoType>()); 2139} 2140 2141/// Produce an approprioate diagnostic for an ambiguity between a function 2142/// declarator and a C++ direct-initializer. 2143static void warnAboutAmbiguousFunction(Sema &S, Declarator &D, 2144 DeclaratorChunk &DeclType, QualType RT) { 2145 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 2146 assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity"); 2147 2148 // If the return type is void there is no ambiguity. 2149 if (RT->isVoidType()) 2150 return; 2151 2152 // An initializer for a non-class type can have at most one argument. 2153 if (!RT->isRecordType() && FTI.NumArgs > 1) 2154 return; 2155 2156 // An initializer for a reference must have exactly one argument. 2157 if (RT->isReferenceType() && FTI.NumArgs != 1) 2158 return; 2159 2160 // Only warn if this declarator is declaring a function at block scope, and 2161 // doesn't have a storage class (such as 'extern') specified. 2162 if (!D.isFunctionDeclarator() || 2163 D.getFunctionDefinitionKind() != FDK_Declaration || 2164 !S.CurContext->isFunctionOrMethod() || 2165 D.getDeclSpec().getStorageClassSpecAsWritten() 2166 != DeclSpec::SCS_unspecified) 2167 return; 2168 2169 // Inside a condition, a direct initializer is not permitted. We allow one to 2170 // be parsed in order to give better diagnostics in condition parsing. 2171 if (D.getContext() == Declarator::ConditionContext) 2172 return; 2173 2174 SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc); 2175 2176 S.Diag(DeclType.Loc, 2177 FTI.NumArgs ? diag::warn_parens_disambiguated_as_function_declaration 2178 : diag::warn_empty_parens_are_function_decl) 2179 << ParenRange; 2180 2181 // If the declaration looks like: 2182 // T var1, 2183 // f(); 2184 // and name lookup finds a function named 'f', then the ',' was 2185 // probably intended to be a ';'. 2186 if (!D.isFirstDeclarator() && D.getIdentifier()) { 2187 FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr); 2188 FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr); 2189 if (Comma.getFileID() != Name.getFileID() || 2190 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) { 2191 LookupResult Result(S, D.getIdentifier(), SourceLocation(), 2192 Sema::LookupOrdinaryName); 2193 if (S.LookupName(Result, S.getCurScope())) 2194 S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call) 2195 << FixItHint::CreateReplacement(D.getCommaLoc(), ";") 2196 << D.getIdentifier(); 2197 } 2198 } 2199 2200 if (FTI.NumArgs > 0) { 2201 // For a declaration with parameters, eg. "T var(T());", suggest adding parens 2202 // around the first parameter to turn the declaration into a variable 2203 // declaration. 2204 SourceRange Range = FTI.ArgInfo[0].Param->getSourceRange(); 2205 SourceLocation B = Range.getBegin(); 2206 SourceLocation E = S.PP.getLocForEndOfToken(Range.getEnd()); 2207 // FIXME: Maybe we should suggest adding braces instead of parens 2208 // in C++11 for classes that don't have an initializer_list constructor. 2209 S.Diag(B, diag::note_additional_parens_for_variable_declaration) 2210 << FixItHint::CreateInsertion(B, "(") 2211 << FixItHint::CreateInsertion(E, ")"); 2212 } else { 2213 // For a declaration without parameters, eg. "T var();", suggest replacing the 2214 // parens with an initializer to turn the declaration into a variable 2215 // declaration. 2216 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl(); 2217 2218 // Empty parens mean value-initialization, and no parens mean 2219 // default initialization. These are equivalent if the default 2220 // constructor is user-provided or if zero-initialization is a 2221 // no-op. 2222 if (RD && RD->hasDefinition() && 2223 (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor())) 2224 S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor) 2225 << FixItHint::CreateRemoval(ParenRange); 2226 else { 2227 std::string Init = S.getFixItZeroInitializerForType(RT); 2228 if (Init.empty() && S.LangOpts.CPlusPlus11) 2229 Init = "{}"; 2230 if (!Init.empty()) 2231 S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize) 2232 << FixItHint::CreateReplacement(ParenRange, Init); 2233 } 2234 } 2235} 2236 2237static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state, 2238 QualType declSpecType, 2239 TypeSourceInfo *TInfo) { 2240 2241 QualType T = declSpecType; 2242 Declarator &D = state.getDeclarator(); 2243 Sema &S = state.getSema(); 2244 ASTContext &Context = S.Context; 2245 const LangOptions &LangOpts = S.getLangOpts(); 2246 2247 // The name we're declaring, if any. 2248 DeclarationName Name; 2249 if (D.getIdentifier()) 2250 Name = D.getIdentifier(); 2251 2252 // Does this declaration declare a typedef-name? 2253 bool IsTypedefName = 2254 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef || 2255 D.getContext() == Declarator::AliasDeclContext || 2256 D.getContext() == Declarator::AliasTemplateContext; 2257 2258 // Does T refer to a function type with a cv-qualifier or a ref-qualifier? 2259 bool IsQualifiedFunction = T->isFunctionProtoType() && 2260 (T->castAs<FunctionProtoType>()->getTypeQuals() != 0 || 2261 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None); 2262 2263 // Walk the DeclTypeInfo, building the recursive type as we go. 2264 // DeclTypeInfos are ordered from the identifier out, which is 2265 // opposite of what we want :). 2266 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 2267 unsigned chunkIndex = e - i - 1; 2268 state.setCurrentChunkIndex(chunkIndex); 2269 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex); 2270 if (IsQualifiedFunction) { 2271 checkQualifiedFunction(S, T, DeclType); 2272 IsQualifiedFunction = DeclType.Kind == DeclaratorChunk::Paren; 2273 } 2274 switch (DeclType.Kind) { 2275 case DeclaratorChunk::Paren: 2276 T = S.BuildParenType(T); 2277 break; 2278 case DeclaratorChunk::BlockPointer: 2279 // If blocks are disabled, emit an error. 2280 if (!LangOpts.Blocks) 2281 S.Diag(DeclType.Loc, diag::err_blocks_disable); 2282 2283 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name); 2284 if (DeclType.Cls.TypeQuals) 2285 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals); 2286 break; 2287 case DeclaratorChunk::Pointer: 2288 // Verify that we're not building a pointer to pointer to function with 2289 // exception specification. 2290 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { 2291 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 2292 D.setInvalidType(true); 2293 // Build the type anyway. 2294 } 2295 if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) { 2296 T = Context.getObjCObjectPointerType(T); 2297 if (DeclType.Ptr.TypeQuals) 2298 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals); 2299 break; 2300 } 2301 T = S.BuildPointerType(T, DeclType.Loc, Name); 2302 if (DeclType.Ptr.TypeQuals) 2303 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals); 2304 2305 break; 2306 case DeclaratorChunk::Reference: { 2307 // Verify that we're not building a reference to pointer to function with 2308 // exception specification. 2309 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { 2310 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 2311 D.setInvalidType(true); 2312 // Build the type anyway. 2313 } 2314 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name); 2315 2316 Qualifiers Quals; 2317 if (DeclType.Ref.HasRestrict) 2318 T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict); 2319 break; 2320 } 2321 case DeclaratorChunk::Array: { 2322 // Verify that we're not building an array of pointers to function with 2323 // exception specification. 2324 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { 2325 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 2326 D.setInvalidType(true); 2327 // Build the type anyway. 2328 } 2329 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr; 2330 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts); 2331 ArrayType::ArraySizeModifier ASM; 2332 if (ATI.isStar) 2333 ASM = ArrayType::Star; 2334 else if (ATI.hasStatic) 2335 ASM = ArrayType::Static; 2336 else 2337 ASM = ArrayType::Normal; 2338 if (ASM == ArrayType::Star && !D.isPrototypeContext()) { 2339 // FIXME: This check isn't quite right: it allows star in prototypes 2340 // for function definitions, and disallows some edge cases detailed 2341 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html 2342 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype); 2343 ASM = ArrayType::Normal; 2344 D.setInvalidType(true); 2345 } 2346 2347 // C99 6.7.5.2p1: The optional type qualifiers and the keyword static 2348 // shall appear only in a declaration of a function parameter with an 2349 // array type, ... 2350 if (ASM == ArrayType::Static || ATI.TypeQuals) { 2351 if (!(D.isPrototypeContext() || 2352 D.getContext() == Declarator::KNRTypeListContext)) { 2353 S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) << 2354 (ASM == ArrayType::Static ? "'static'" : "type qualifier"); 2355 // Remove the 'static' and the type qualifiers. 2356 if (ASM == ArrayType::Static) 2357 ASM = ArrayType::Normal; 2358 ATI.TypeQuals = 0; 2359 D.setInvalidType(true); 2360 } 2361 2362 // C99 6.7.5.2p1: ... and then only in the outermost array type 2363 // derivation. 2364 unsigned x = chunkIndex; 2365 while (x != 0) { 2366 // Walk outwards along the declarator chunks. 2367 x--; 2368 const DeclaratorChunk &DC = D.getTypeObject(x); 2369 switch (DC.Kind) { 2370 case DeclaratorChunk::Paren: 2371 continue; 2372 case DeclaratorChunk::Array: 2373 case DeclaratorChunk::Pointer: 2374 case DeclaratorChunk::Reference: 2375 case DeclaratorChunk::MemberPointer: 2376 S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) << 2377 (ASM == ArrayType::Static ? "'static'" : "type qualifier"); 2378 if (ASM == ArrayType::Static) 2379 ASM = ArrayType::Normal; 2380 ATI.TypeQuals = 0; 2381 D.setInvalidType(true); 2382 break; 2383 case DeclaratorChunk::Function: 2384 case DeclaratorChunk::BlockPointer: 2385 // These are invalid anyway, so just ignore. 2386 break; 2387 } 2388 } 2389 } 2390 2391 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals, 2392 SourceRange(DeclType.Loc, DeclType.EndLoc), Name); 2393 break; 2394 } 2395 case DeclaratorChunk::Function: { 2396 // If the function declarator has a prototype (i.e. it is not () and 2397 // does not have a K&R-style identifier list), then the arguments are part 2398 // of the type, otherwise the argument list is (). 2399 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 2400 IsQualifiedFunction = FTI.TypeQuals || FTI.hasRefQualifier(); 2401 2402 // Check for auto functions and trailing return type and adjust the 2403 // return type accordingly. 2404 if (!D.isInvalidType()) { 2405 // trailing-return-type is only required if we're declaring a function, 2406 // and not, for instance, a pointer to a function. 2407 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto && 2408 !FTI.hasTrailingReturnType() && chunkIndex == 0) { 2409 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 2410 diag::err_auto_missing_trailing_return); 2411 T = Context.IntTy; 2412 D.setInvalidType(true); 2413 } else if (FTI.hasTrailingReturnType()) { 2414 // T must be exactly 'auto' at this point. See CWG issue 681. 2415 if (isa<ParenType>(T)) { 2416 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 2417 diag::err_trailing_return_in_parens) 2418 << T << D.getDeclSpec().getSourceRange(); 2419 D.setInvalidType(true); 2420 } else if (D.getContext() != Declarator::LambdaExprContext && 2421 (T.hasQualifiers() || !isa<AutoType>(T))) { 2422 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 2423 diag::err_trailing_return_without_auto) 2424 << T << D.getDeclSpec().getSourceRange(); 2425 D.setInvalidType(true); 2426 } 2427 T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo); 2428 if (T.isNull()) { 2429 // An error occurred parsing the trailing return type. 2430 T = Context.IntTy; 2431 D.setInvalidType(true); 2432 } 2433 } 2434 } 2435 2436 // C99 6.7.5.3p1: The return type may not be a function or array type. 2437 // For conversion functions, we'll diagnose this particular error later. 2438 if ((T->isArrayType() || T->isFunctionType()) && 2439 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) { 2440 unsigned diagID = diag::err_func_returning_array_function; 2441 // Last processing chunk in block context means this function chunk 2442 // represents the block. 2443 if (chunkIndex == 0 && 2444 D.getContext() == Declarator::BlockLiteralContext) 2445 diagID = diag::err_block_returning_array_function; 2446 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T; 2447 T = Context.IntTy; 2448 D.setInvalidType(true); 2449 } 2450 2451 // Do not allow returning half FP value. 2452 // FIXME: This really should be in BuildFunctionType. 2453 if (T->isHalfType()) { 2454 if (S.getLangOpts().OpenCL) { 2455 if (!S.getOpenCLOptions().cl_khr_fp16) { 2456 S.Diag(D.getIdentifierLoc(), diag::err_opencl_half_return) << T; 2457 D.setInvalidType(true); 2458 } 2459 } else { 2460 S.Diag(D.getIdentifierLoc(), 2461 diag::err_parameters_retval_cannot_have_fp16_type) << 1; 2462 D.setInvalidType(true); 2463 } 2464 } 2465 2466 // cv-qualifiers on return types are pointless except when the type is a 2467 // class type in C++. 2468 if (isa<PointerType>(T) && T.getLocalCVRQualifiers() && 2469 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId) && 2470 (!LangOpts.CPlusPlus || !T->isDependentType())) { 2471 assert(chunkIndex + 1 < e && "No DeclaratorChunk for the return type?"); 2472 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1); 2473 assert(ReturnTypeChunk.Kind == DeclaratorChunk::Pointer); 2474 2475 DeclaratorChunk::PointerTypeInfo &PTI = ReturnTypeChunk.Ptr; 2476 2477 DiagnoseIgnoredQualifiers(PTI.TypeQuals, 2478 SourceLocation::getFromRawEncoding(PTI.ConstQualLoc), 2479 SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc), 2480 SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc), 2481 S); 2482 2483 } else if (T.getCVRQualifiers() && D.getDeclSpec().getTypeQualifiers() && 2484 (!LangOpts.CPlusPlus || 2485 (!T->isDependentType() && !T->isRecordType()))) { 2486 2487 DiagnoseIgnoredQualifiers(D.getDeclSpec().getTypeQualifiers(), 2488 D.getDeclSpec().getConstSpecLoc(), 2489 D.getDeclSpec().getVolatileSpecLoc(), 2490 D.getDeclSpec().getRestrictSpecLoc(), 2491 S); 2492 } 2493 2494 // Objective-C ARC ownership qualifiers are ignored on the function 2495 // return type (by type canonicalization). Complain if this attribute 2496 // was written here. 2497 if (T.getQualifiers().hasObjCLifetime()) { 2498 SourceLocation AttrLoc; 2499 if (chunkIndex + 1 < D.getNumTypeObjects()) { 2500 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1); 2501 for (const AttributeList *Attr = ReturnTypeChunk.getAttrs(); 2502 Attr; Attr = Attr->getNext()) { 2503 if (Attr->getKind() == AttributeList::AT_ObjCOwnership) { 2504 AttrLoc = Attr->getLoc(); 2505 break; 2506 } 2507 } 2508 } 2509 if (AttrLoc.isInvalid()) { 2510 for (const AttributeList *Attr 2511 = D.getDeclSpec().getAttributes().getList(); 2512 Attr; Attr = Attr->getNext()) { 2513 if (Attr->getKind() == AttributeList::AT_ObjCOwnership) { 2514 AttrLoc = Attr->getLoc(); 2515 break; 2516 } 2517 } 2518 } 2519 2520 if (AttrLoc.isValid()) { 2521 // The ownership attributes are almost always written via 2522 // the predefined 2523 // __strong/__weak/__autoreleasing/__unsafe_unretained. 2524 if (AttrLoc.isMacroID()) 2525 AttrLoc = S.SourceMgr.getImmediateExpansionRange(AttrLoc).first; 2526 2527 S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type) 2528 << T.getQualifiers().getObjCLifetime(); 2529 } 2530 } 2531 2532 if (LangOpts.CPlusPlus && D.getDeclSpec().isTypeSpecOwned()) { 2533 // C++ [dcl.fct]p6: 2534 // Types shall not be defined in return or parameter types. 2535 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 2536 if (Tag->isCompleteDefinition()) 2537 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type) 2538 << Context.getTypeDeclType(Tag); 2539 } 2540 2541 // Exception specs are not allowed in typedefs. Complain, but add it 2542 // anyway. 2543 if (IsTypedefName && FTI.getExceptionSpecType()) 2544 S.Diag(FTI.getExceptionSpecLoc(), diag::err_exception_spec_in_typedef) 2545 << (D.getContext() == Declarator::AliasDeclContext || 2546 D.getContext() == Declarator::AliasTemplateContext); 2547 2548 // If we see "T var();" or "T var(T());" at block scope, it is probably 2549 // an attempt to initialize a variable, not a function declaration. 2550 if (FTI.isAmbiguous) 2551 warnAboutAmbiguousFunction(S, D, DeclType, T); 2552 2553 if (!FTI.NumArgs && !FTI.isVariadic && !LangOpts.CPlusPlus) { 2554 // Simple void foo(), where the incoming T is the result type. 2555 T = Context.getFunctionNoProtoType(T); 2556 } else { 2557 // We allow a zero-parameter variadic function in C if the 2558 // function is marked with the "overloadable" attribute. Scan 2559 // for this attribute now. 2560 if (!FTI.NumArgs && FTI.isVariadic && !LangOpts.CPlusPlus) { 2561 bool Overloadable = false; 2562 for (const AttributeList *Attrs = D.getAttributes(); 2563 Attrs; Attrs = Attrs->getNext()) { 2564 if (Attrs->getKind() == AttributeList::AT_Overloadable) { 2565 Overloadable = true; 2566 break; 2567 } 2568 } 2569 2570 if (!Overloadable) 2571 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg); 2572 } 2573 2574 if (FTI.NumArgs && FTI.ArgInfo[0].Param == 0) { 2575 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function 2576 // definition. 2577 S.Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration); 2578 D.setInvalidType(true); 2579 break; 2580 } 2581 2582 FunctionProtoType::ExtProtoInfo EPI; 2583 EPI.Variadic = FTI.isVariadic; 2584 EPI.HasTrailingReturn = FTI.hasTrailingReturnType(); 2585 EPI.TypeQuals = FTI.TypeQuals; 2586 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None 2587 : FTI.RefQualifierIsLValueRef? RQ_LValue 2588 : RQ_RValue; 2589 2590 // Otherwise, we have a function with an argument list that is 2591 // potentially variadic. 2592 SmallVector<QualType, 16> ArgTys; 2593 ArgTys.reserve(FTI.NumArgs); 2594 2595 SmallVector<bool, 16> ConsumedArguments; 2596 ConsumedArguments.reserve(FTI.NumArgs); 2597 bool HasAnyConsumedArguments = false; 2598 2599 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) { 2600 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param); 2601 QualType ArgTy = Param->getType(); 2602 assert(!ArgTy.isNull() && "Couldn't parse type?"); 2603 2604 // Adjust the parameter type. 2605 assert((ArgTy == Context.getAdjustedParameterType(ArgTy)) && 2606 "Unadjusted type?"); 2607 2608 // Look for 'void'. void is allowed only as a single argument to a 2609 // function with no other parameters (C99 6.7.5.3p10). We record 2610 // int(void) as a FunctionProtoType with an empty argument list. 2611 if (ArgTy->isVoidType()) { 2612 // If this is something like 'float(int, void)', reject it. 'void' 2613 // is an incomplete type (C99 6.2.5p19) and function decls cannot 2614 // have arguments of incomplete type. 2615 if (FTI.NumArgs != 1 || FTI.isVariadic) { 2616 S.Diag(DeclType.Loc, diag::err_void_only_param); 2617 ArgTy = Context.IntTy; 2618 Param->setType(ArgTy); 2619 } else if (FTI.ArgInfo[i].Ident) { 2620 // Reject, but continue to parse 'int(void abc)'. 2621 S.Diag(FTI.ArgInfo[i].IdentLoc, 2622 diag::err_param_with_void_type); 2623 ArgTy = Context.IntTy; 2624 Param->setType(ArgTy); 2625 } else { 2626 // Reject, but continue to parse 'float(const void)'. 2627 if (ArgTy.hasQualifiers()) 2628 S.Diag(DeclType.Loc, diag::err_void_param_qualified); 2629 2630 // Do not add 'void' to the ArgTys list. 2631 break; 2632 } 2633 } else if (ArgTy->isHalfType()) { 2634 // Disallow half FP arguments. 2635 // FIXME: This really should be in BuildFunctionType. 2636 if (S.getLangOpts().OpenCL) { 2637 if (!S.getOpenCLOptions().cl_khr_fp16) { 2638 S.Diag(Param->getLocation(), 2639 diag::err_opencl_half_argument) << ArgTy; 2640 D.setInvalidType(); 2641 } 2642 } else { 2643 S.Diag(Param->getLocation(), 2644 diag::err_parameters_retval_cannot_have_fp16_type) << 0; 2645 D.setInvalidType(); 2646 } 2647 } else if (!FTI.hasPrototype) { 2648 if (ArgTy->isPromotableIntegerType()) { 2649 ArgTy = Context.getPromotedIntegerType(ArgTy); 2650 Param->setKNRPromoted(true); 2651 } else if (const BuiltinType* BTy = ArgTy->getAs<BuiltinType>()) { 2652 if (BTy->getKind() == BuiltinType::Float) { 2653 ArgTy = Context.DoubleTy; 2654 Param->setKNRPromoted(true); 2655 } 2656 } 2657 } 2658 2659 if (LangOpts.ObjCAutoRefCount) { 2660 bool Consumed = Param->hasAttr<NSConsumedAttr>(); 2661 ConsumedArguments.push_back(Consumed); 2662 HasAnyConsumedArguments |= Consumed; 2663 } 2664 2665 ArgTys.push_back(ArgTy); 2666 } 2667 2668 if (HasAnyConsumedArguments) 2669 EPI.ConsumedArguments = ConsumedArguments.data(); 2670 2671 SmallVector<QualType, 4> Exceptions; 2672 SmallVector<ParsedType, 2> DynamicExceptions; 2673 SmallVector<SourceRange, 2> DynamicExceptionRanges; 2674 Expr *NoexceptExpr = 0; 2675 2676 if (FTI.getExceptionSpecType() == EST_Dynamic) { 2677 // FIXME: It's rather inefficient to have to split into two vectors 2678 // here. 2679 unsigned N = FTI.NumExceptions; 2680 DynamicExceptions.reserve(N); 2681 DynamicExceptionRanges.reserve(N); 2682 for (unsigned I = 0; I != N; ++I) { 2683 DynamicExceptions.push_back(FTI.Exceptions[I].Ty); 2684 DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range); 2685 } 2686 } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) { 2687 NoexceptExpr = FTI.NoexceptExpr; 2688 } 2689 2690 S.checkExceptionSpecification(FTI.getExceptionSpecType(), 2691 DynamicExceptions, 2692 DynamicExceptionRanges, 2693 NoexceptExpr, 2694 Exceptions, 2695 EPI); 2696 2697 T = Context.getFunctionType(T, ArgTys.data(), ArgTys.size(), EPI); 2698 } 2699 2700 break; 2701 } 2702 case DeclaratorChunk::MemberPointer: 2703 // The scope spec must refer to a class, or be dependent. 2704 CXXScopeSpec &SS = DeclType.Mem.Scope(); 2705 QualType ClsType; 2706 if (SS.isInvalid()) { 2707 // Avoid emitting extra errors if we already errored on the scope. 2708 D.setInvalidType(true); 2709 } else if (S.isDependentScopeSpecifier(SS) || 2710 dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) { 2711 NestedNameSpecifier *NNS 2712 = static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 2713 NestedNameSpecifier *NNSPrefix = NNS->getPrefix(); 2714 switch (NNS->getKind()) { 2715 case NestedNameSpecifier::Identifier: 2716 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix, 2717 NNS->getAsIdentifier()); 2718 break; 2719 2720 case NestedNameSpecifier::Namespace: 2721 case NestedNameSpecifier::NamespaceAlias: 2722 case NestedNameSpecifier::Global: 2723 llvm_unreachable("Nested-name-specifier must name a type"); 2724 2725 case NestedNameSpecifier::TypeSpec: 2726 case NestedNameSpecifier::TypeSpecWithTemplate: 2727 ClsType = QualType(NNS->getAsType(), 0); 2728 // Note: if the NNS has a prefix and ClsType is a nondependent 2729 // TemplateSpecializationType, then the NNS prefix is NOT included 2730 // in ClsType; hence we wrap ClsType into an ElaboratedType. 2731 // NOTE: in particular, no wrap occurs if ClsType already is an 2732 // Elaborated, DependentName, or DependentTemplateSpecialization. 2733 if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType())) 2734 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType); 2735 break; 2736 } 2737 } else { 2738 S.Diag(DeclType.Mem.Scope().getBeginLoc(), 2739 diag::err_illegal_decl_mempointer_in_nonclass) 2740 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name") 2741 << DeclType.Mem.Scope().getRange(); 2742 D.setInvalidType(true); 2743 } 2744 2745 if (!ClsType.isNull()) 2746 T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc, D.getIdentifier()); 2747 if (T.isNull()) { 2748 T = Context.IntTy; 2749 D.setInvalidType(true); 2750 } else if (DeclType.Mem.TypeQuals) { 2751 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals); 2752 } 2753 break; 2754 } 2755 2756 if (T.isNull()) { 2757 D.setInvalidType(true); 2758 T = Context.IntTy; 2759 } 2760 2761 // See if there are any attributes on this declarator chunk. 2762 if (AttributeList *attrs = const_cast<AttributeList*>(DeclType.getAttrs())) 2763 processTypeAttrs(state, T, TAL_DeclChunk, attrs); 2764 } 2765 2766 if (LangOpts.CPlusPlus && T->isFunctionType()) { 2767 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>(); 2768 assert(FnTy && "Why oh why is there not a FunctionProtoType here?"); 2769 2770 // C++ 8.3.5p4: 2771 // A cv-qualifier-seq shall only be part of the function type 2772 // for a nonstatic member function, the function type to which a pointer 2773 // to member refers, or the top-level function type of a function typedef 2774 // declaration. 2775 // 2776 // Core issue 547 also allows cv-qualifiers on function types that are 2777 // top-level template type arguments. 2778 bool FreeFunction; 2779 if (!D.getCXXScopeSpec().isSet()) { 2780 FreeFunction = ((D.getContext() != Declarator::MemberContext && 2781 D.getContext() != Declarator::LambdaExprContext) || 2782 D.getDeclSpec().isFriendSpecified()); 2783 } else { 2784 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec()); 2785 FreeFunction = (DC && !DC->isRecord()); 2786 } 2787 2788 // C++11 [dcl.fct]p6 (w/DR1417): 2789 // An attempt to specify a function type with a cv-qualifier-seq or a 2790 // ref-qualifier (including by typedef-name) is ill-formed unless it is: 2791 // - the function type for a non-static member function, 2792 // - the function type to which a pointer to member refers, 2793 // - the top-level function type of a function typedef declaration or 2794 // alias-declaration, 2795 // - the type-id in the default argument of a type-parameter, or 2796 // - the type-id of a template-argument for a type-parameter 2797 if (IsQualifiedFunction && 2798 !(!FreeFunction && 2799 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) && 2800 !IsTypedefName && 2801 D.getContext() != Declarator::TemplateTypeArgContext) { 2802 SourceLocation Loc = D.getLocStart(); 2803 SourceRange RemovalRange; 2804 unsigned I; 2805 if (D.isFunctionDeclarator(I)) { 2806 SmallVector<SourceLocation, 4> RemovalLocs; 2807 const DeclaratorChunk &Chunk = D.getTypeObject(I); 2808 assert(Chunk.Kind == DeclaratorChunk::Function); 2809 if (Chunk.Fun.hasRefQualifier()) 2810 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc()); 2811 if (Chunk.Fun.TypeQuals & Qualifiers::Const) 2812 RemovalLocs.push_back(Chunk.Fun.getConstQualifierLoc()); 2813 if (Chunk.Fun.TypeQuals & Qualifiers::Volatile) 2814 RemovalLocs.push_back(Chunk.Fun.getVolatileQualifierLoc()); 2815 // FIXME: We do not track the location of the __restrict qualifier. 2816 //if (Chunk.Fun.TypeQuals & Qualifiers::Restrict) 2817 // RemovalLocs.push_back(Chunk.Fun.getRestrictQualifierLoc()); 2818 if (!RemovalLocs.empty()) { 2819 std::sort(RemovalLocs.begin(), RemovalLocs.end(), 2820 BeforeThanCompare<SourceLocation>(S.getSourceManager())); 2821 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back()); 2822 Loc = RemovalLocs.front(); 2823 } 2824 } 2825 2826 S.Diag(Loc, diag::err_invalid_qualified_function_type) 2827 << FreeFunction << D.isFunctionDeclarator() << T 2828 << getFunctionQualifiersAsString(FnTy) 2829 << FixItHint::CreateRemoval(RemovalRange); 2830 2831 // Strip the cv-qualifiers and ref-qualifiers from the type. 2832 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo(); 2833 EPI.TypeQuals = 0; 2834 EPI.RefQualifier = RQ_None; 2835 2836 T = Context.getFunctionType(FnTy->getResultType(), 2837 FnTy->arg_type_begin(), 2838 FnTy->getNumArgs(), EPI); 2839 // Rebuild any parens around the identifier in the function type. 2840 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 2841 if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren) 2842 break; 2843 T = S.BuildParenType(T); 2844 } 2845 } 2846 } 2847 2848 // Apply any undistributed attributes from the declarator. 2849 if (!T.isNull()) 2850 if (AttributeList *attrs = D.getAttributes()) 2851 processTypeAttrs(state, T, TAL_DeclName, attrs); 2852 2853 // Diagnose any ignored type attributes. 2854 if (!T.isNull()) state.diagnoseIgnoredTypeAttrs(T); 2855 2856 // C++0x [dcl.constexpr]p9: 2857 // A constexpr specifier used in an object declaration declares the object 2858 // as const. 2859 if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) { 2860 T.addConst(); 2861 } 2862 2863 // If there was an ellipsis in the declarator, the declaration declares a 2864 // parameter pack whose type may be a pack expansion type. 2865 if (D.hasEllipsis() && !T.isNull()) { 2866 // C++0x [dcl.fct]p13: 2867 // A declarator-id or abstract-declarator containing an ellipsis shall 2868 // only be used in a parameter-declaration. Such a parameter-declaration 2869 // is a parameter pack (14.5.3). [...] 2870 switch (D.getContext()) { 2871 case Declarator::PrototypeContext: 2872 // C++0x [dcl.fct]p13: 2873 // [...] When it is part of a parameter-declaration-clause, the 2874 // parameter pack is a function parameter pack (14.5.3). The type T 2875 // of the declarator-id of the function parameter pack shall contain 2876 // a template parameter pack; each template parameter pack in T is 2877 // expanded by the function parameter pack. 2878 // 2879 // We represent function parameter packs as function parameters whose 2880 // type is a pack expansion. 2881 if (!T->containsUnexpandedParameterPack()) { 2882 S.Diag(D.getEllipsisLoc(), 2883 diag::err_function_parameter_pack_without_parameter_packs) 2884 << T << D.getSourceRange(); 2885 D.setEllipsisLoc(SourceLocation()); 2886 } else { 2887 T = Context.getPackExpansionType(T, llvm::Optional<unsigned>()); 2888 } 2889 break; 2890 2891 case Declarator::TemplateParamContext: 2892 // C++0x [temp.param]p15: 2893 // If a template-parameter is a [...] is a parameter-declaration that 2894 // declares a parameter pack (8.3.5), then the template-parameter is a 2895 // template parameter pack (14.5.3). 2896 // 2897 // Note: core issue 778 clarifies that, if there are any unexpanded 2898 // parameter packs in the type of the non-type template parameter, then 2899 // it expands those parameter packs. 2900 if (T->containsUnexpandedParameterPack()) 2901 T = Context.getPackExpansionType(T, llvm::Optional<unsigned>()); 2902 else 2903 S.Diag(D.getEllipsisLoc(), 2904 LangOpts.CPlusPlus11 2905 ? diag::warn_cxx98_compat_variadic_templates 2906 : diag::ext_variadic_templates); 2907 break; 2908 2909 case Declarator::FileContext: 2910 case Declarator::KNRTypeListContext: 2911 case Declarator::ObjCParameterContext: // FIXME: special diagnostic here? 2912 case Declarator::ObjCResultContext: // FIXME: special diagnostic here? 2913 case Declarator::TypeNameContext: 2914 case Declarator::CXXNewContext: 2915 case Declarator::AliasDeclContext: 2916 case Declarator::AliasTemplateContext: 2917 case Declarator::MemberContext: 2918 case Declarator::BlockContext: 2919 case Declarator::ForContext: 2920 case Declarator::ConditionContext: 2921 case Declarator::CXXCatchContext: 2922 case Declarator::ObjCCatchContext: 2923 case Declarator::BlockLiteralContext: 2924 case Declarator::LambdaExprContext: 2925 case Declarator::TrailingReturnContext: 2926 case Declarator::TemplateTypeArgContext: 2927 // FIXME: We may want to allow parameter packs in block-literal contexts 2928 // in the future. 2929 S.Diag(D.getEllipsisLoc(), diag::err_ellipsis_in_declarator_not_parameter); 2930 D.setEllipsisLoc(SourceLocation()); 2931 break; 2932 } 2933 } 2934 2935 if (T.isNull()) 2936 return Context.getNullTypeSourceInfo(); 2937 else if (D.isInvalidType()) 2938 return Context.getTrivialTypeSourceInfo(T); 2939 2940 return S.GetTypeSourceInfoForDeclarator(D, T, TInfo); 2941} 2942 2943/// GetTypeForDeclarator - Convert the type for the specified 2944/// declarator to Type instances. 2945/// 2946/// The result of this call will never be null, but the associated 2947/// type may be a null type if there's an unrecoverable error. 2948TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) { 2949 // Determine the type of the declarator. Not all forms of declarator 2950 // have a type. 2951 2952 TypeProcessingState state(*this, D); 2953 2954 TypeSourceInfo *ReturnTypeInfo = 0; 2955 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); 2956 if (T.isNull()) 2957 return Context.getNullTypeSourceInfo(); 2958 2959 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount) 2960 inferARCWriteback(state, T); 2961 2962 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo); 2963} 2964 2965static void transferARCOwnershipToDeclSpec(Sema &S, 2966 QualType &declSpecTy, 2967 Qualifiers::ObjCLifetime ownership) { 2968 if (declSpecTy->isObjCRetainableType() && 2969 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) { 2970 Qualifiers qs; 2971 qs.addObjCLifetime(ownership); 2972 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs); 2973 } 2974} 2975 2976static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, 2977 Qualifiers::ObjCLifetime ownership, 2978 unsigned chunkIndex) { 2979 Sema &S = state.getSema(); 2980 Declarator &D = state.getDeclarator(); 2981 2982 // Look for an explicit lifetime attribute. 2983 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex); 2984 for (const AttributeList *attr = chunk.getAttrs(); attr; 2985 attr = attr->getNext()) 2986 if (attr->getKind() == AttributeList::AT_ObjCOwnership) 2987 return; 2988 2989 const char *attrStr = 0; 2990 switch (ownership) { 2991 case Qualifiers::OCL_None: llvm_unreachable("no ownership!"); 2992 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break; 2993 case Qualifiers::OCL_Strong: attrStr = "strong"; break; 2994 case Qualifiers::OCL_Weak: attrStr = "weak"; break; 2995 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break; 2996 } 2997 2998 // If there wasn't one, add one (with an invalid source location 2999 // so that we don't make an AttributedType for it). 3000 AttributeList *attr = D.getAttributePool() 3001 .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(), 3002 /*scope*/ 0, SourceLocation(), 3003 &S.Context.Idents.get(attrStr), SourceLocation(), 3004 /*args*/ 0, 0, AttributeList::AS_GNU); 3005 spliceAttrIntoList(*attr, chunk.getAttrListRef()); 3006 3007 // TODO: mark whether we did this inference? 3008} 3009 3010/// \brief Used for transferring ownership in casts resulting in l-values. 3011static void transferARCOwnership(TypeProcessingState &state, 3012 QualType &declSpecTy, 3013 Qualifiers::ObjCLifetime ownership) { 3014 Sema &S = state.getSema(); 3015 Declarator &D = state.getDeclarator(); 3016 3017 int inner = -1; 3018 bool hasIndirection = false; 3019 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 3020 DeclaratorChunk &chunk = D.getTypeObject(i); 3021 switch (chunk.Kind) { 3022 case DeclaratorChunk::Paren: 3023 // Ignore parens. 3024 break; 3025 3026 case DeclaratorChunk::Array: 3027 case DeclaratorChunk::Reference: 3028 case DeclaratorChunk::Pointer: 3029 if (inner != -1) 3030 hasIndirection = true; 3031 inner = i; 3032 break; 3033 3034 case DeclaratorChunk::BlockPointer: 3035 if (inner != -1) 3036 transferARCOwnershipToDeclaratorChunk(state, ownership, i); 3037 return; 3038 3039 case DeclaratorChunk::Function: 3040 case DeclaratorChunk::MemberPointer: 3041 return; 3042 } 3043 } 3044 3045 if (inner == -1) 3046 return; 3047 3048 DeclaratorChunk &chunk = D.getTypeObject(inner); 3049 if (chunk.Kind == DeclaratorChunk::Pointer) { 3050 if (declSpecTy->isObjCRetainableType()) 3051 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); 3052 if (declSpecTy->isObjCObjectType() && hasIndirection) 3053 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner); 3054 } else { 3055 assert(chunk.Kind == DeclaratorChunk::Array || 3056 chunk.Kind == DeclaratorChunk::Reference); 3057 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); 3058 } 3059} 3060 3061TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) { 3062 TypeProcessingState state(*this, D); 3063 3064 TypeSourceInfo *ReturnTypeInfo = 0; 3065 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); 3066 if (declSpecTy.isNull()) 3067 return Context.getNullTypeSourceInfo(); 3068 3069 if (getLangOpts().ObjCAutoRefCount) { 3070 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy); 3071 if (ownership != Qualifiers::OCL_None) 3072 transferARCOwnership(state, declSpecTy, ownership); 3073 } 3074 3075 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo); 3076} 3077 3078/// Map an AttributedType::Kind to an AttributeList::Kind. 3079static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) { 3080 switch (kind) { 3081 case AttributedType::attr_address_space: 3082 return AttributeList::AT_AddressSpace; 3083 case AttributedType::attr_regparm: 3084 return AttributeList::AT_Regparm; 3085 case AttributedType::attr_vector_size: 3086 return AttributeList::AT_VectorSize; 3087 case AttributedType::attr_neon_vector_type: 3088 return AttributeList::AT_NeonVectorType; 3089 case AttributedType::attr_neon_polyvector_type: 3090 return AttributeList::AT_NeonPolyVectorType; 3091 case AttributedType::attr_objc_gc: 3092 return AttributeList::AT_ObjCGC; 3093 case AttributedType::attr_objc_ownership: 3094 return AttributeList::AT_ObjCOwnership; 3095 case AttributedType::attr_noreturn: 3096 return AttributeList::AT_NoReturn; 3097 case AttributedType::attr_cdecl: 3098 return AttributeList::AT_CDecl; 3099 case AttributedType::attr_fastcall: 3100 return AttributeList::AT_FastCall; 3101 case AttributedType::attr_stdcall: 3102 return AttributeList::AT_StdCall; 3103 case AttributedType::attr_thiscall: 3104 return AttributeList::AT_ThisCall; 3105 case AttributedType::attr_pascal: 3106 return AttributeList::AT_Pascal; 3107 case AttributedType::attr_pcs: 3108 return AttributeList::AT_Pcs; 3109 case AttributedType::attr_pnaclcall: 3110 return AttributeList::AT_PnaclCall; 3111 case AttributedType::attr_inteloclbicc: 3112 return AttributeList::AT_IntelOclBicc; 3113 } 3114 llvm_unreachable("unexpected attribute kind!"); 3115} 3116 3117static void fillAttributedTypeLoc(AttributedTypeLoc TL, 3118 const AttributeList *attrs) { 3119 AttributedType::Kind kind = TL.getAttrKind(); 3120 3121 assert(attrs && "no type attributes in the expected location!"); 3122 AttributeList::Kind parsedKind = getAttrListKind(kind); 3123 while (attrs->getKind() != parsedKind) { 3124 attrs = attrs->getNext(); 3125 assert(attrs && "no matching attribute in expected location!"); 3126 } 3127 3128 TL.setAttrNameLoc(attrs->getLoc()); 3129 if (TL.hasAttrExprOperand()) 3130 TL.setAttrExprOperand(attrs->getArg(0)); 3131 else if (TL.hasAttrEnumOperand()) 3132 TL.setAttrEnumOperandLoc(attrs->getParameterLoc()); 3133 3134 // FIXME: preserve this information to here. 3135 if (TL.hasAttrOperand()) 3136 TL.setAttrOperandParensRange(SourceRange()); 3137} 3138 3139namespace { 3140 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> { 3141 ASTContext &Context; 3142 const DeclSpec &DS; 3143 3144 public: 3145 TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS) 3146 : Context(Context), DS(DS) {} 3147 3148 void VisitAttributedTypeLoc(AttributedTypeLoc TL) { 3149 fillAttributedTypeLoc(TL, DS.getAttributes().getList()); 3150 Visit(TL.getModifiedLoc()); 3151 } 3152 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 3153 Visit(TL.getUnqualifiedLoc()); 3154 } 3155 void VisitTypedefTypeLoc(TypedefTypeLoc TL) { 3156 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 3157 } 3158 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { 3159 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 3160 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires 3161 // addition field. What we have is good enough for dispay of location 3162 // of 'fixit' on interface name. 3163 TL.setNameEndLoc(DS.getLocEnd()); 3164 } 3165 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { 3166 // Handle the base type, which might not have been written explicitly. 3167 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) { 3168 TL.setHasBaseTypeAsWritten(false); 3169 TL.getBaseLoc().initialize(Context, SourceLocation()); 3170 } else { 3171 TL.setHasBaseTypeAsWritten(true); 3172 Visit(TL.getBaseLoc()); 3173 } 3174 3175 // Protocol qualifiers. 3176 if (DS.getProtocolQualifiers()) { 3177 assert(TL.getNumProtocols() > 0); 3178 assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers()); 3179 TL.setLAngleLoc(DS.getProtocolLAngleLoc()); 3180 TL.setRAngleLoc(DS.getSourceRange().getEnd()); 3181 for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i) 3182 TL.setProtocolLoc(i, DS.getProtocolLocs()[i]); 3183 } else { 3184 assert(TL.getNumProtocols() == 0); 3185 TL.setLAngleLoc(SourceLocation()); 3186 TL.setRAngleLoc(SourceLocation()); 3187 } 3188 } 3189 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 3190 TL.setStarLoc(SourceLocation()); 3191 Visit(TL.getPointeeLoc()); 3192 } 3193 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) { 3194 TypeSourceInfo *TInfo = 0; 3195 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 3196 3197 // If we got no declarator info from previous Sema routines, 3198 // just fill with the typespec loc. 3199 if (!TInfo) { 3200 TL.initialize(Context, DS.getTypeSpecTypeNameLoc()); 3201 return; 3202 } 3203 3204 TypeLoc OldTL = TInfo->getTypeLoc(); 3205 if (TInfo->getType()->getAs<ElaboratedType>()) { 3206 ElaboratedTypeLoc ElabTL = cast<ElaboratedTypeLoc>(OldTL); 3207 TemplateSpecializationTypeLoc NamedTL = 3208 cast<TemplateSpecializationTypeLoc>(ElabTL.getNamedTypeLoc()); 3209 TL.copy(NamedTL); 3210 } 3211 else 3212 TL.copy(cast<TemplateSpecializationTypeLoc>(OldTL)); 3213 } 3214 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { 3215 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr); 3216 TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); 3217 TL.setParensRange(DS.getTypeofParensRange()); 3218 } 3219 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { 3220 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType); 3221 TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); 3222 TL.setParensRange(DS.getTypeofParensRange()); 3223 assert(DS.getRepAsType()); 3224 TypeSourceInfo *TInfo = 0; 3225 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 3226 TL.setUnderlyingTInfo(TInfo); 3227 } 3228 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) { 3229 // FIXME: This holds only because we only have one unary transform. 3230 assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType); 3231 TL.setKWLoc(DS.getTypeSpecTypeLoc()); 3232 TL.setParensRange(DS.getTypeofParensRange()); 3233 assert(DS.getRepAsType()); 3234 TypeSourceInfo *TInfo = 0; 3235 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 3236 TL.setUnderlyingTInfo(TInfo); 3237 } 3238 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { 3239 // By default, use the source location of the type specifier. 3240 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc()); 3241 if (TL.needsExtraLocalData()) { 3242 // Set info for the written builtin specifiers. 3243 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs(); 3244 // Try to have a meaningful source location. 3245 if (TL.getWrittenSignSpec() != TSS_unspecified) 3246 // Sign spec loc overrides the others (e.g., 'unsigned long'). 3247 TL.setBuiltinLoc(DS.getTypeSpecSignLoc()); 3248 else if (TL.getWrittenWidthSpec() != TSW_unspecified) 3249 // Width spec loc overrides type spec loc (e.g., 'short int'). 3250 TL.setBuiltinLoc(DS.getTypeSpecWidthLoc()); 3251 } 3252 } 3253 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { 3254 ElaboratedTypeKeyword Keyword 3255 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType()); 3256 if (DS.getTypeSpecType() == TST_typename) { 3257 TypeSourceInfo *TInfo = 0; 3258 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 3259 if (TInfo) { 3260 TL.copy(cast<ElaboratedTypeLoc>(TInfo->getTypeLoc())); 3261 return; 3262 } 3263 } 3264 TL.setElaboratedKeywordLoc(Keyword != ETK_None 3265 ? DS.getTypeSpecTypeLoc() 3266 : SourceLocation()); 3267 const CXXScopeSpec& SS = DS.getTypeSpecScope(); 3268 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 3269 Visit(TL.getNextTypeLoc().getUnqualifiedLoc()); 3270 } 3271 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { 3272 assert(DS.getTypeSpecType() == TST_typename); 3273 TypeSourceInfo *TInfo = 0; 3274 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 3275 assert(TInfo); 3276 TL.copy(cast<DependentNameTypeLoc>(TInfo->getTypeLoc())); 3277 } 3278 void VisitDependentTemplateSpecializationTypeLoc( 3279 DependentTemplateSpecializationTypeLoc TL) { 3280 assert(DS.getTypeSpecType() == TST_typename); 3281 TypeSourceInfo *TInfo = 0; 3282 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 3283 assert(TInfo); 3284 TL.copy(cast<DependentTemplateSpecializationTypeLoc>( 3285 TInfo->getTypeLoc())); 3286 } 3287 void VisitTagTypeLoc(TagTypeLoc TL) { 3288 TL.setNameLoc(DS.getTypeSpecTypeNameLoc()); 3289 } 3290 void VisitAtomicTypeLoc(AtomicTypeLoc TL) { 3291 TL.setKWLoc(DS.getTypeSpecTypeLoc()); 3292 TL.setParensRange(DS.getTypeofParensRange()); 3293 3294 TypeSourceInfo *TInfo = 0; 3295 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 3296 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc()); 3297 } 3298 3299 void VisitTypeLoc(TypeLoc TL) { 3300 // FIXME: add other typespec types and change this to an assert. 3301 TL.initialize(Context, DS.getTypeSpecTypeLoc()); 3302 } 3303 }; 3304 3305 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> { 3306 ASTContext &Context; 3307 const DeclaratorChunk &Chunk; 3308 3309 public: 3310 DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk) 3311 : Context(Context), Chunk(Chunk) {} 3312 3313 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 3314 llvm_unreachable("qualified type locs not expected here!"); 3315 } 3316 3317 void VisitAttributedTypeLoc(AttributedTypeLoc TL) { 3318 fillAttributedTypeLoc(TL, Chunk.getAttrs()); 3319 } 3320 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { 3321 assert(Chunk.Kind == DeclaratorChunk::BlockPointer); 3322 TL.setCaretLoc(Chunk.Loc); 3323 } 3324 void VisitPointerTypeLoc(PointerTypeLoc TL) { 3325 assert(Chunk.Kind == DeclaratorChunk::Pointer); 3326 TL.setStarLoc(Chunk.Loc); 3327 } 3328 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 3329 assert(Chunk.Kind == DeclaratorChunk::Pointer); 3330 TL.setStarLoc(Chunk.Loc); 3331 } 3332 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { 3333 assert(Chunk.Kind == DeclaratorChunk::MemberPointer); 3334 const CXXScopeSpec& SS = Chunk.Mem.Scope(); 3335 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context); 3336 3337 const Type* ClsTy = TL.getClass(); 3338 QualType ClsQT = QualType(ClsTy, 0); 3339 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0); 3340 // Now copy source location info into the type loc component. 3341 TypeLoc ClsTL = ClsTInfo->getTypeLoc(); 3342 switch (NNSLoc.getNestedNameSpecifier()->getKind()) { 3343 case NestedNameSpecifier::Identifier: 3344 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc"); 3345 { 3346 DependentNameTypeLoc DNTLoc = cast<DependentNameTypeLoc>(ClsTL); 3347 DNTLoc.setElaboratedKeywordLoc(SourceLocation()); 3348 DNTLoc.setQualifierLoc(NNSLoc.getPrefix()); 3349 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc()); 3350 } 3351 break; 3352 3353 case NestedNameSpecifier::TypeSpec: 3354 case NestedNameSpecifier::TypeSpecWithTemplate: 3355 if (isa<ElaboratedType>(ClsTy)) { 3356 ElaboratedTypeLoc ETLoc = *cast<ElaboratedTypeLoc>(&ClsTL); 3357 ETLoc.setElaboratedKeywordLoc(SourceLocation()); 3358 ETLoc.setQualifierLoc(NNSLoc.getPrefix()); 3359 TypeLoc NamedTL = ETLoc.getNamedTypeLoc(); 3360 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc()); 3361 } else { 3362 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc()); 3363 } 3364 break; 3365 3366 case NestedNameSpecifier::Namespace: 3367 case NestedNameSpecifier::NamespaceAlias: 3368 case NestedNameSpecifier::Global: 3369 llvm_unreachable("Nested-name-specifier must name a type"); 3370 } 3371 3372 // Finally fill in MemberPointerLocInfo fields. 3373 TL.setStarLoc(Chunk.Loc); 3374 TL.setClassTInfo(ClsTInfo); 3375 } 3376 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { 3377 assert(Chunk.Kind == DeclaratorChunk::Reference); 3378 // 'Amp' is misleading: this might have been originally 3379 /// spelled with AmpAmp. 3380 TL.setAmpLoc(Chunk.Loc); 3381 } 3382 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { 3383 assert(Chunk.Kind == DeclaratorChunk::Reference); 3384 assert(!Chunk.Ref.LValueRef); 3385 TL.setAmpAmpLoc(Chunk.Loc); 3386 } 3387 void VisitArrayTypeLoc(ArrayTypeLoc TL) { 3388 assert(Chunk.Kind == DeclaratorChunk::Array); 3389 TL.setLBracketLoc(Chunk.Loc); 3390 TL.setRBracketLoc(Chunk.EndLoc); 3391 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts)); 3392 } 3393 void VisitFunctionTypeLoc(FunctionTypeLoc TL) { 3394 assert(Chunk.Kind == DeclaratorChunk::Function); 3395 TL.setLocalRangeBegin(Chunk.Loc); 3396 TL.setLocalRangeEnd(Chunk.EndLoc); 3397 3398 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun; 3399 TL.setLParenLoc(FTI.getLParenLoc()); 3400 TL.setRParenLoc(FTI.getRParenLoc()); 3401 for (unsigned i = 0, e = TL.getNumArgs(), tpi = 0; i != e; ++i) { 3402 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param); 3403 TL.setArg(tpi++, Param); 3404 } 3405 // FIXME: exception specs 3406 } 3407 void VisitParenTypeLoc(ParenTypeLoc TL) { 3408 assert(Chunk.Kind == DeclaratorChunk::Paren); 3409 TL.setLParenLoc(Chunk.Loc); 3410 TL.setRParenLoc(Chunk.EndLoc); 3411 } 3412 3413 void VisitTypeLoc(TypeLoc TL) { 3414 llvm_unreachable("unsupported TypeLoc kind in declarator!"); 3415 } 3416 }; 3417} 3418 3419/// \brief Create and instantiate a TypeSourceInfo with type source information. 3420/// 3421/// \param T QualType referring to the type as written in source code. 3422/// 3423/// \param ReturnTypeInfo For declarators whose return type does not show 3424/// up in the normal place in the declaration specifiers (such as a C++ 3425/// conversion function), this pointer will refer to a type source information 3426/// for that return type. 3427TypeSourceInfo * 3428Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T, 3429 TypeSourceInfo *ReturnTypeInfo) { 3430 TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T); 3431 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc(); 3432 3433 // Handle parameter packs whose type is a pack expansion. 3434 if (isa<PackExpansionType>(T)) { 3435 cast<PackExpansionTypeLoc>(CurrTL).setEllipsisLoc(D.getEllipsisLoc()); 3436 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); 3437 } 3438 3439 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 3440 while (isa<AttributedTypeLoc>(CurrTL)) { 3441 AttributedTypeLoc TL = cast<AttributedTypeLoc>(CurrTL); 3442 fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs()); 3443 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); 3444 } 3445 3446 DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL); 3447 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); 3448 } 3449 3450 // If we have different source information for the return type, use 3451 // that. This really only applies to C++ conversion functions. 3452 if (ReturnTypeInfo) { 3453 TypeLoc TL = ReturnTypeInfo->getTypeLoc(); 3454 assert(TL.getFullDataSize() == CurrTL.getFullDataSize()); 3455 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize()); 3456 } else { 3457 TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL); 3458 } 3459 3460 return TInfo; 3461} 3462 3463/// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo. 3464ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) { 3465 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser 3466 // and Sema during declaration parsing. Try deallocating/caching them when 3467 // it's appropriate, instead of allocating them and keeping them around. 3468 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType), 3469 TypeAlignment); 3470 new (LocT) LocInfoType(T, TInfo); 3471 assert(LocT->getTypeClass() != T->getTypeClass() && 3472 "LocInfoType's TypeClass conflicts with an existing Type class"); 3473 return ParsedType::make(QualType(LocT, 0)); 3474} 3475 3476void LocInfoType::getAsStringInternal(std::string &Str, 3477 const PrintingPolicy &Policy) const { 3478 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*" 3479 " was used directly instead of getting the QualType through" 3480 " GetTypeFromParser"); 3481} 3482 3483TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) { 3484 // C99 6.7.6: Type names have no identifier. This is already validated by 3485 // the parser. 3486 assert(D.getIdentifier() == 0 && "Type name should have no identifier!"); 3487 3488 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 3489 QualType T = TInfo->getType(); 3490 if (D.isInvalidType()) 3491 return true; 3492 3493 // Make sure there are no unused decl attributes on the declarator. 3494 // We don't want to do this for ObjC parameters because we're going 3495 // to apply them to the actual parameter declaration. 3496 if (D.getContext() != Declarator::ObjCParameterContext) 3497 checkUnusedDeclAttributes(D); 3498 3499 if (getLangOpts().CPlusPlus) { 3500 // Check that there are no default arguments (C++ only). 3501 CheckExtraCXXDefaultArguments(D); 3502 } 3503 3504 return CreateParsedType(T, TInfo); 3505} 3506 3507ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) { 3508 QualType T = Context.getObjCInstanceType(); 3509 TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 3510 return CreateParsedType(T, TInfo); 3511} 3512 3513 3514//===----------------------------------------------------------------------===// 3515// Type Attribute Processing 3516//===----------------------------------------------------------------------===// 3517 3518/// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the 3519/// specified type. The attribute contains 1 argument, the id of the address 3520/// space for the type. 3521static void HandleAddressSpaceTypeAttribute(QualType &Type, 3522 const AttributeList &Attr, Sema &S){ 3523 3524 // If this type is already address space qualified, reject it. 3525 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by 3526 // qualifiers for two or more different address spaces." 3527 if (Type.getAddressSpace()) { 3528 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers); 3529 Attr.setInvalid(); 3530 return; 3531 } 3532 3533 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be 3534 // qualified by an address-space qualifier." 3535 if (Type->isFunctionType()) { 3536 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type); 3537 Attr.setInvalid(); 3538 return; 3539 } 3540 3541 // Check the attribute arguments. 3542 if (Attr.getNumArgs() != 1) { 3543 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; 3544 Attr.setInvalid(); 3545 return; 3546 } 3547 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0)); 3548 llvm::APSInt addrSpace(32); 3549 if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() || 3550 !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) { 3551 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int) 3552 << ASArgExpr->getSourceRange(); 3553 Attr.setInvalid(); 3554 return; 3555 } 3556 3557 // Bounds checking. 3558 if (addrSpace.isSigned()) { 3559 if (addrSpace.isNegative()) { 3560 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative) 3561 << ASArgExpr->getSourceRange(); 3562 Attr.setInvalid(); 3563 return; 3564 } 3565 addrSpace.setIsSigned(false); 3566 } 3567 llvm::APSInt max(addrSpace.getBitWidth()); 3568 max = Qualifiers::MaxAddressSpace; 3569 if (addrSpace > max) { 3570 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high) 3571 << Qualifiers::MaxAddressSpace << ASArgExpr->getSourceRange(); 3572 Attr.setInvalid(); 3573 return; 3574 } 3575 3576 unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue()); 3577 Type = S.Context.getAddrSpaceQualType(Type, ASIdx); 3578} 3579 3580/// Does this type have a "direct" ownership qualifier? That is, 3581/// is it written like "__strong id", as opposed to something like 3582/// "typeof(foo)", where that happens to be strong? 3583static bool hasDirectOwnershipQualifier(QualType type) { 3584 // Fast path: no qualifier at all. 3585 assert(type.getQualifiers().hasObjCLifetime()); 3586 3587 while (true) { 3588 // __strong id 3589 if (const AttributedType *attr = dyn_cast<AttributedType>(type)) { 3590 if (attr->getAttrKind() == AttributedType::attr_objc_ownership) 3591 return true; 3592 3593 type = attr->getModifiedType(); 3594 3595 // X *__strong (...) 3596 } else if (const ParenType *paren = dyn_cast<ParenType>(type)) { 3597 type = paren->getInnerType(); 3598 3599 // That's it for things we want to complain about. In particular, 3600 // we do not want to look through typedefs, typeof(expr), 3601 // typeof(type), or any other way that the type is somehow 3602 // abstracted. 3603 } else { 3604 3605 return false; 3606 } 3607 } 3608} 3609 3610/// handleObjCOwnershipTypeAttr - Process an objc_ownership 3611/// attribute on the specified type. 3612/// 3613/// Returns 'true' if the attribute was handled. 3614static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state, 3615 AttributeList &attr, 3616 QualType &type) { 3617 bool NonObjCPointer = false; 3618 3619 if (!type->isDependentType()) { 3620 if (const PointerType *ptr = type->getAs<PointerType>()) { 3621 QualType pointee = ptr->getPointeeType(); 3622 if (pointee->isObjCRetainableType() || pointee->isPointerType()) 3623 return false; 3624 // It is important not to lose the source info that there was an attribute 3625 // applied to non-objc pointer. We will create an attributed type but 3626 // its type will be the same as the original type. 3627 NonObjCPointer = true; 3628 } else if (!type->isObjCRetainableType()) { 3629 return false; 3630 } 3631 } 3632 3633 Sema &S = state.getSema(); 3634 SourceLocation AttrLoc = attr.getLoc(); 3635 if (AttrLoc.isMacroID()) 3636 AttrLoc = S.getSourceManager().getImmediateExpansionRange(AttrLoc).first; 3637 3638 if (!attr.getParameterName()) { 3639 S.Diag(AttrLoc, diag::err_attribute_argument_n_not_string) 3640 << "objc_ownership" << 1; 3641 attr.setInvalid(); 3642 return true; 3643 } 3644 3645 // Consume lifetime attributes without further comment outside of 3646 // ARC mode. 3647 if (!S.getLangOpts().ObjCAutoRefCount) 3648 return true; 3649 3650 Qualifiers::ObjCLifetime lifetime; 3651 if (attr.getParameterName()->isStr("none")) 3652 lifetime = Qualifiers::OCL_ExplicitNone; 3653 else if (attr.getParameterName()->isStr("strong")) 3654 lifetime = Qualifiers::OCL_Strong; 3655 else if (attr.getParameterName()->isStr("weak")) 3656 lifetime = Qualifiers::OCL_Weak; 3657 else if (attr.getParameterName()->isStr("autoreleasing")) 3658 lifetime = Qualifiers::OCL_Autoreleasing; 3659 else { 3660 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported) 3661 << "objc_ownership" << attr.getParameterName(); 3662 attr.setInvalid(); 3663 return true; 3664 } 3665 3666 SplitQualType underlyingType = type.split(); 3667 3668 // Check for redundant/conflicting ownership qualifiers. 3669 if (Qualifiers::ObjCLifetime previousLifetime 3670 = type.getQualifiers().getObjCLifetime()) { 3671 // If it's written directly, that's an error. 3672 if (hasDirectOwnershipQualifier(type)) { 3673 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant) 3674 << type; 3675 return true; 3676 } 3677 3678 // Otherwise, if the qualifiers actually conflict, pull sugar off 3679 // until we reach a type that is directly qualified. 3680 if (previousLifetime != lifetime) { 3681 // This should always terminate: the canonical type is 3682 // qualified, so some bit of sugar must be hiding it. 3683 while (!underlyingType.Quals.hasObjCLifetime()) { 3684 underlyingType = underlyingType.getSingleStepDesugaredType(); 3685 } 3686 underlyingType.Quals.removeObjCLifetime(); 3687 } 3688 } 3689 3690 underlyingType.Quals.addObjCLifetime(lifetime); 3691 3692 if (NonObjCPointer) { 3693 StringRef name = attr.getName()->getName(); 3694 switch (lifetime) { 3695 case Qualifiers::OCL_None: 3696 case Qualifiers::OCL_ExplicitNone: 3697 break; 3698 case Qualifiers::OCL_Strong: name = "__strong"; break; 3699 case Qualifiers::OCL_Weak: name = "__weak"; break; 3700 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break; 3701 } 3702 S.Diag(AttrLoc, diag::warn_objc_object_attribute_wrong_type) 3703 << name << type; 3704 } 3705 3706 QualType origType = type; 3707 if (!NonObjCPointer) 3708 type = S.Context.getQualifiedType(underlyingType); 3709 3710 // If we have a valid source location for the attribute, use an 3711 // AttributedType instead. 3712 if (AttrLoc.isValid()) 3713 type = S.Context.getAttributedType(AttributedType::attr_objc_ownership, 3714 origType, type); 3715 3716 // Forbid __weak if the runtime doesn't support it. 3717 if (lifetime == Qualifiers::OCL_Weak && 3718 !S.getLangOpts().ObjCARCWeak && !NonObjCPointer) { 3719 3720 // Actually, delay this until we know what we're parsing. 3721 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) { 3722 S.DelayedDiagnostics.add( 3723 sema::DelayedDiagnostic::makeForbiddenType( 3724 S.getSourceManager().getExpansionLoc(AttrLoc), 3725 diag::err_arc_weak_no_runtime, type, /*ignored*/ 0)); 3726 } else { 3727 S.Diag(AttrLoc, diag::err_arc_weak_no_runtime); 3728 } 3729 3730 attr.setInvalid(); 3731 return true; 3732 } 3733 3734 // Forbid __weak for class objects marked as 3735 // objc_arc_weak_reference_unavailable 3736 if (lifetime == Qualifiers::OCL_Weak) { 3737 QualType T = type; 3738 while (const PointerType *ptr = T->getAs<PointerType>()) 3739 T = ptr->getPointeeType(); 3740 if (const ObjCObjectPointerType *ObjT = T->getAs<ObjCObjectPointerType>()) { 3741 if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) { 3742 if (Class->isArcWeakrefUnavailable()) { 3743 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class); 3744 S.Diag(ObjT->getInterfaceDecl()->getLocation(), 3745 diag::note_class_declared); 3746 } 3747 } 3748 } 3749 } 3750 3751 return true; 3752} 3753 3754/// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type 3755/// attribute on the specified type. Returns true to indicate that 3756/// the attribute was handled, false to indicate that the type does 3757/// not permit the attribute. 3758static bool handleObjCGCTypeAttr(TypeProcessingState &state, 3759 AttributeList &attr, 3760 QualType &type) { 3761 Sema &S = state.getSema(); 3762 3763 // Delay if this isn't some kind of pointer. 3764 if (!type->isPointerType() && 3765 !type->isObjCObjectPointerType() && 3766 !type->isBlockPointerType()) 3767 return false; 3768 3769 if (type.getObjCGCAttr() != Qualifiers::GCNone) { 3770 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc); 3771 attr.setInvalid(); 3772 return true; 3773 } 3774 3775 // Check the attribute arguments. 3776 if (!attr.getParameterName()) { 3777 S.Diag(attr.getLoc(), diag::err_attribute_argument_n_not_string) 3778 << "objc_gc" << 1; 3779 attr.setInvalid(); 3780 return true; 3781 } 3782 Qualifiers::GC GCAttr; 3783 if (attr.getNumArgs() != 0) { 3784 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; 3785 attr.setInvalid(); 3786 return true; 3787 } 3788 if (attr.getParameterName()->isStr("weak")) 3789 GCAttr = Qualifiers::Weak; 3790 else if (attr.getParameterName()->isStr("strong")) 3791 GCAttr = Qualifiers::Strong; 3792 else { 3793 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported) 3794 << "objc_gc" << attr.getParameterName(); 3795 attr.setInvalid(); 3796 return true; 3797 } 3798 3799 QualType origType = type; 3800 type = S.Context.getObjCGCQualType(origType, GCAttr); 3801 3802 // Make an attributed type to preserve the source information. 3803 if (attr.getLoc().isValid()) 3804 type = S.Context.getAttributedType(AttributedType::attr_objc_gc, 3805 origType, type); 3806 3807 return true; 3808} 3809 3810namespace { 3811 /// A helper class to unwrap a type down to a function for the 3812 /// purposes of applying attributes there. 3813 /// 3814 /// Use: 3815 /// FunctionTypeUnwrapper unwrapped(SemaRef, T); 3816 /// if (unwrapped.isFunctionType()) { 3817 /// const FunctionType *fn = unwrapped.get(); 3818 /// // change fn somehow 3819 /// T = unwrapped.wrap(fn); 3820 /// } 3821 struct FunctionTypeUnwrapper { 3822 enum WrapKind { 3823 Desugar, 3824 Parens, 3825 Pointer, 3826 BlockPointer, 3827 Reference, 3828 MemberPointer 3829 }; 3830 3831 QualType Original; 3832 const FunctionType *Fn; 3833 SmallVector<unsigned char /*WrapKind*/, 8> Stack; 3834 3835 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) { 3836 while (true) { 3837 const Type *Ty = T.getTypePtr(); 3838 if (isa<FunctionType>(Ty)) { 3839 Fn = cast<FunctionType>(Ty); 3840 return; 3841 } else if (isa<ParenType>(Ty)) { 3842 T = cast<ParenType>(Ty)->getInnerType(); 3843 Stack.push_back(Parens); 3844 } else if (isa<PointerType>(Ty)) { 3845 T = cast<PointerType>(Ty)->getPointeeType(); 3846 Stack.push_back(Pointer); 3847 } else if (isa<BlockPointerType>(Ty)) { 3848 T = cast<BlockPointerType>(Ty)->getPointeeType(); 3849 Stack.push_back(BlockPointer); 3850 } else if (isa<MemberPointerType>(Ty)) { 3851 T = cast<MemberPointerType>(Ty)->getPointeeType(); 3852 Stack.push_back(MemberPointer); 3853 } else if (isa<ReferenceType>(Ty)) { 3854 T = cast<ReferenceType>(Ty)->getPointeeType(); 3855 Stack.push_back(Reference); 3856 } else { 3857 const Type *DTy = Ty->getUnqualifiedDesugaredType(); 3858 if (Ty == DTy) { 3859 Fn = 0; 3860 return; 3861 } 3862 3863 T = QualType(DTy, 0); 3864 Stack.push_back(Desugar); 3865 } 3866 } 3867 } 3868 3869 bool isFunctionType() const { return (Fn != 0); } 3870 const FunctionType *get() const { return Fn; } 3871 3872 QualType wrap(Sema &S, const FunctionType *New) { 3873 // If T wasn't modified from the unwrapped type, do nothing. 3874 if (New == get()) return Original; 3875 3876 Fn = New; 3877 return wrap(S.Context, Original, 0); 3878 } 3879 3880 private: 3881 QualType wrap(ASTContext &C, QualType Old, unsigned I) { 3882 if (I == Stack.size()) 3883 return C.getQualifiedType(Fn, Old.getQualifiers()); 3884 3885 // Build up the inner type, applying the qualifiers from the old 3886 // type to the new type. 3887 SplitQualType SplitOld = Old.split(); 3888 3889 // As a special case, tail-recurse if there are no qualifiers. 3890 if (SplitOld.Quals.empty()) 3891 return wrap(C, SplitOld.Ty, I); 3892 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals); 3893 } 3894 3895 QualType wrap(ASTContext &C, const Type *Old, unsigned I) { 3896 if (I == Stack.size()) return QualType(Fn, 0); 3897 3898 switch (static_cast<WrapKind>(Stack[I++])) { 3899 case Desugar: 3900 // This is the point at which we potentially lose source 3901 // information. 3902 return wrap(C, Old->getUnqualifiedDesugaredType(), I); 3903 3904 case Parens: { 3905 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I); 3906 return C.getParenType(New); 3907 } 3908 3909 case Pointer: { 3910 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I); 3911 return C.getPointerType(New); 3912 } 3913 3914 case BlockPointer: { 3915 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I); 3916 return C.getBlockPointerType(New); 3917 } 3918 3919 case MemberPointer: { 3920 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old); 3921 QualType New = wrap(C, OldMPT->getPointeeType(), I); 3922 return C.getMemberPointerType(New, OldMPT->getClass()); 3923 } 3924 3925 case Reference: { 3926 const ReferenceType *OldRef = cast<ReferenceType>(Old); 3927 QualType New = wrap(C, OldRef->getPointeeType(), I); 3928 if (isa<LValueReferenceType>(OldRef)) 3929 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue()); 3930 else 3931 return C.getRValueReferenceType(New); 3932 } 3933 } 3934 3935 llvm_unreachable("unknown wrapping kind"); 3936 } 3937 }; 3938} 3939 3940/// Process an individual function attribute. Returns true to 3941/// indicate that the attribute was handled, false if it wasn't. 3942static bool handleFunctionTypeAttr(TypeProcessingState &state, 3943 AttributeList &attr, 3944 QualType &type) { 3945 Sema &S = state.getSema(); 3946 3947 FunctionTypeUnwrapper unwrapped(S, type); 3948 3949 if (attr.getKind() == AttributeList::AT_NoReturn) { 3950 if (S.CheckNoReturnAttr(attr)) 3951 return true; 3952 3953 // Delay if this is not a function type. 3954 if (!unwrapped.isFunctionType()) 3955 return false; 3956 3957 // Otherwise we can process right away. 3958 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true); 3959 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 3960 return true; 3961 } 3962 3963 // ns_returns_retained is not always a type attribute, but if we got 3964 // here, we're treating it as one right now. 3965 if (attr.getKind() == AttributeList::AT_NSReturnsRetained) { 3966 assert(S.getLangOpts().ObjCAutoRefCount && 3967 "ns_returns_retained treated as type attribute in non-ARC"); 3968 if (attr.getNumArgs()) return true; 3969 3970 // Delay if this is not a function type. 3971 if (!unwrapped.isFunctionType()) 3972 return false; 3973 3974 FunctionType::ExtInfo EI 3975 = unwrapped.get()->getExtInfo().withProducesResult(true); 3976 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 3977 return true; 3978 } 3979 3980 if (attr.getKind() == AttributeList::AT_Regparm) { 3981 unsigned value; 3982 if (S.CheckRegparmAttr(attr, value)) 3983 return true; 3984 3985 // Delay if this is not a function type. 3986 if (!unwrapped.isFunctionType()) 3987 return false; 3988 3989 // Diagnose regparm with fastcall. 3990 const FunctionType *fn = unwrapped.get(); 3991 CallingConv CC = fn->getCallConv(); 3992 if (CC == CC_X86FastCall) { 3993 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 3994 << FunctionType::getNameForCallConv(CC) 3995 << "regparm"; 3996 attr.setInvalid(); 3997 return true; 3998 } 3999 4000 FunctionType::ExtInfo EI = 4001 unwrapped.get()->getExtInfo().withRegParm(value); 4002 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 4003 return true; 4004 } 4005 4006 // Delay if the type didn't work out to a function. 4007 if (!unwrapped.isFunctionType()) return false; 4008 4009 // Otherwise, a calling convention. 4010 CallingConv CC; 4011 if (S.CheckCallingConvAttr(attr, CC)) 4012 return true; 4013 4014 const FunctionType *fn = unwrapped.get(); 4015 CallingConv CCOld = fn->getCallConv(); 4016 if (S.Context.getCanonicalCallConv(CC) == 4017 S.Context.getCanonicalCallConv(CCOld)) { 4018 FunctionType::ExtInfo EI= unwrapped.get()->getExtInfo().withCallingConv(CC); 4019 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 4020 return true; 4021 } 4022 4023 if (CCOld != (S.LangOpts.MRTD ? CC_X86StdCall : CC_Default)) { 4024 // Should we diagnose reapplications of the same convention? 4025 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 4026 << FunctionType::getNameForCallConv(CC) 4027 << FunctionType::getNameForCallConv(CCOld); 4028 attr.setInvalid(); 4029 return true; 4030 } 4031 4032 // Diagnose the use of X86 fastcall on varargs or unprototyped functions. 4033 if (CC == CC_X86FastCall) { 4034 if (isa<FunctionNoProtoType>(fn)) { 4035 S.Diag(attr.getLoc(), diag::err_cconv_knr) 4036 << FunctionType::getNameForCallConv(CC); 4037 attr.setInvalid(); 4038 return true; 4039 } 4040 4041 const FunctionProtoType *FnP = cast<FunctionProtoType>(fn); 4042 if (FnP->isVariadic()) { 4043 S.Diag(attr.getLoc(), diag::err_cconv_varargs) 4044 << FunctionType::getNameForCallConv(CC); 4045 attr.setInvalid(); 4046 return true; 4047 } 4048 4049 // Also diagnose fastcall with regparm. 4050 if (fn->getHasRegParm()) { 4051 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 4052 << "regparm" 4053 << FunctionType::getNameForCallConv(CC); 4054 attr.setInvalid(); 4055 return true; 4056 } 4057 } 4058 4059 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withCallingConv(CC); 4060 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 4061 return true; 4062} 4063 4064/// Handle OpenCL image access qualifiers: read_only, write_only, read_write 4065static void HandleOpenCLImageAccessAttribute(QualType& CurType, 4066 const AttributeList &Attr, 4067 Sema &S) { 4068 // Check the attribute arguments. 4069 if (Attr.getNumArgs() != 1) { 4070 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; 4071 Attr.setInvalid(); 4072 return; 4073 } 4074 Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0)); 4075 llvm::APSInt arg(32); 4076 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() || 4077 !sizeExpr->isIntegerConstantExpr(arg, S.Context)) { 4078 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int) 4079 << "opencl_image_access" << sizeExpr->getSourceRange(); 4080 Attr.setInvalid(); 4081 return; 4082 } 4083 unsigned iarg = static_cast<unsigned>(arg.getZExtValue()); 4084 switch (iarg) { 4085 case CLIA_read_only: 4086 case CLIA_write_only: 4087 case CLIA_read_write: 4088 // Implemented in a separate patch 4089 break; 4090 default: 4091 // Implemented in a separate patch 4092 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size) 4093 << sizeExpr->getSourceRange(); 4094 Attr.setInvalid(); 4095 break; 4096 } 4097} 4098 4099/// HandleVectorSizeAttribute - this attribute is only applicable to integral 4100/// and float scalars, although arrays, pointers, and function return values are 4101/// allowed in conjunction with this construct. Aggregates with this attribute 4102/// are invalid, even if they are of the same size as a corresponding scalar. 4103/// The raw attribute should contain precisely 1 argument, the vector size for 4104/// the variable, measured in bytes. If curType and rawAttr are well formed, 4105/// this routine will return a new vector type. 4106static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr, 4107 Sema &S) { 4108 // Check the attribute arguments. 4109 if (Attr.getNumArgs() != 1) { 4110 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; 4111 Attr.setInvalid(); 4112 return; 4113 } 4114 Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0)); 4115 llvm::APSInt vecSize(32); 4116 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() || 4117 !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) { 4118 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int) 4119 << "vector_size" << sizeExpr->getSourceRange(); 4120 Attr.setInvalid(); 4121 return; 4122 } 4123 // the base type must be integer or float, and can't already be a vector. 4124 if (!CurType->isIntegerType() && !CurType->isRealFloatingType()) { 4125 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType; 4126 Attr.setInvalid(); 4127 return; 4128 } 4129 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType)); 4130 // vecSize is specified in bytes - convert to bits. 4131 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8); 4132 4133 // the vector size needs to be an integral multiple of the type size. 4134 if (vectorSize % typeSize) { 4135 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size) 4136 << sizeExpr->getSourceRange(); 4137 Attr.setInvalid(); 4138 return; 4139 } 4140 if (vectorSize == 0) { 4141 S.Diag(Attr.getLoc(), diag::err_attribute_zero_size) 4142 << sizeExpr->getSourceRange(); 4143 Attr.setInvalid(); 4144 return; 4145 } 4146 4147 // Success! Instantiate the vector type, the number of elements is > 0, and 4148 // not required to be a power of 2, unlike GCC. 4149 CurType = S.Context.getVectorType(CurType, vectorSize/typeSize, 4150 VectorType::GenericVector); 4151} 4152 4153/// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on 4154/// a type. 4155static void HandleExtVectorTypeAttr(QualType &CurType, 4156 const AttributeList &Attr, 4157 Sema &S) { 4158 Expr *sizeExpr; 4159 4160 // Special case where the argument is a template id. 4161 if (Attr.getParameterName()) { 4162 CXXScopeSpec SS; 4163 SourceLocation TemplateKWLoc; 4164 UnqualifiedId id; 4165 id.setIdentifier(Attr.getParameterName(), Attr.getLoc()); 4166 4167 ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc, 4168 id, false, false); 4169 if (Size.isInvalid()) 4170 return; 4171 4172 sizeExpr = Size.get(); 4173 } else { 4174 // check the attribute arguments. 4175 if (Attr.getNumArgs() != 1) { 4176 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; 4177 return; 4178 } 4179 sizeExpr = Attr.getArg(0); 4180 } 4181 4182 // Create the vector type. 4183 QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc()); 4184 if (!T.isNull()) 4185 CurType = T; 4186} 4187 4188/// HandleNeonVectorTypeAttr - The "neon_vector_type" and 4189/// "neon_polyvector_type" attributes are used to create vector types that 4190/// are mangled according to ARM's ABI. Otherwise, these types are identical 4191/// to those created with the "vector_size" attribute. Unlike "vector_size" 4192/// the argument to these Neon attributes is the number of vector elements, 4193/// not the vector size in bytes. The vector width and element type must 4194/// match one of the standard Neon vector types. 4195static void HandleNeonVectorTypeAttr(QualType& CurType, 4196 const AttributeList &Attr, Sema &S, 4197 VectorType::VectorKind VecKind, 4198 const char *AttrName) { 4199 // Check the attribute arguments. 4200 if (Attr.getNumArgs() != 1) { 4201 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; 4202 Attr.setInvalid(); 4203 return; 4204 } 4205 // The number of elements must be an ICE. 4206 Expr *numEltsExpr = static_cast<Expr *>(Attr.getArg(0)); 4207 llvm::APSInt numEltsInt(32); 4208 if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() || 4209 !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) { 4210 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int) 4211 << AttrName << numEltsExpr->getSourceRange(); 4212 Attr.setInvalid(); 4213 return; 4214 } 4215 // Only certain element types are supported for Neon vectors. 4216 const BuiltinType* BTy = CurType->getAs<BuiltinType>(); 4217 if (!BTy || 4218 (VecKind == VectorType::NeonPolyVector && 4219 BTy->getKind() != BuiltinType::SChar && 4220 BTy->getKind() != BuiltinType::Short) || 4221 (BTy->getKind() != BuiltinType::SChar && 4222 BTy->getKind() != BuiltinType::UChar && 4223 BTy->getKind() != BuiltinType::Short && 4224 BTy->getKind() != BuiltinType::UShort && 4225 BTy->getKind() != BuiltinType::Int && 4226 BTy->getKind() != BuiltinType::UInt && 4227 BTy->getKind() != BuiltinType::LongLong && 4228 BTy->getKind() != BuiltinType::ULongLong && 4229 BTy->getKind() != BuiltinType::Float)) { 4230 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) <<CurType; 4231 Attr.setInvalid(); 4232 return; 4233 } 4234 // The total size of the vector must be 64 or 128 bits. 4235 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType)); 4236 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue()); 4237 unsigned vecSize = typeSize * numElts; 4238 if (vecSize != 64 && vecSize != 128) { 4239 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType; 4240 Attr.setInvalid(); 4241 return; 4242 } 4243 4244 CurType = S.Context.getVectorType(CurType, numElts, VecKind); 4245} 4246 4247static void processTypeAttrs(TypeProcessingState &state, QualType &type, 4248 TypeAttrLocation TAL, AttributeList *attrs) { 4249 // Scan through and apply attributes to this type where it makes sense. Some 4250 // attributes (such as __address_space__, __vector_size__, etc) apply to the 4251 // type, but others can be present in the type specifiers even though they 4252 // apply to the decl. Here we apply type attributes and ignore the rest. 4253 4254 AttributeList *next; 4255 do { 4256 AttributeList &attr = *attrs; 4257 next = attr.getNext(); 4258 4259 // Skip attributes that were marked to be invalid. 4260 if (attr.isInvalid()) 4261 continue; 4262 4263 if (attr.isCXX11Attribute()) { 4264 // [[gnu::...]] attributes are treated as declaration attributes, so may 4265 // not appertain to a DeclaratorChunk, even if we handle them as type 4266 // attributes. 4267 if (attr.getScopeName() && attr.getScopeName()->isStr("gnu")) { 4268 if (TAL == TAL_DeclChunk) { 4269 state.getSema().Diag(attr.getLoc(), 4270 diag::warn_cxx11_gnu_attribute_on_type) 4271 << attr.getName(); 4272 continue; 4273 } 4274 } else if (TAL != TAL_DeclChunk) { 4275 // Otherwise, only consider type processing for a C++11 attribute if 4276 // it's actually been applied to a type. 4277 continue; 4278 } 4279 } 4280 4281 // If this is an attribute we can handle, do so now, 4282 // otherwise, add it to the FnAttrs list for rechaining. 4283 switch (attr.getKind()) { 4284 default: 4285 // A C++11 attribute on a declarator chunk must appertain to a type. 4286 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) 4287 state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr) 4288 << attr.getName()->getName(); 4289 break; 4290 4291 case AttributeList::UnknownAttribute: 4292 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) 4293 state.getSema().Diag(attr.getLoc(), 4294 diag::warn_unknown_attribute_ignored) 4295 << attr.getName(); 4296 break; 4297 4298 case AttributeList::IgnoredAttribute: 4299 break; 4300 4301 case AttributeList::AT_MayAlias: 4302 // FIXME: This attribute needs to actually be handled, but if we ignore 4303 // it it breaks large amounts of Linux software. 4304 attr.setUsedAsTypeAttr(); 4305 break; 4306 case AttributeList::AT_AddressSpace: 4307 HandleAddressSpaceTypeAttribute(type, attr, state.getSema()); 4308 attr.setUsedAsTypeAttr(); 4309 break; 4310 OBJC_POINTER_TYPE_ATTRS_CASELIST: 4311 if (!handleObjCPointerTypeAttr(state, attr, type)) 4312 distributeObjCPointerTypeAttr(state, attr, type); 4313 attr.setUsedAsTypeAttr(); 4314 break; 4315 case AttributeList::AT_VectorSize: 4316 HandleVectorSizeAttr(type, attr, state.getSema()); 4317 attr.setUsedAsTypeAttr(); 4318 break; 4319 case AttributeList::AT_ExtVectorType: 4320 HandleExtVectorTypeAttr(type, attr, state.getSema()); 4321 attr.setUsedAsTypeAttr(); 4322 break; 4323 case AttributeList::AT_NeonVectorType: 4324 HandleNeonVectorTypeAttr(type, attr, state.getSema(), 4325 VectorType::NeonVector, "neon_vector_type"); 4326 attr.setUsedAsTypeAttr(); 4327 break; 4328 case AttributeList::AT_NeonPolyVectorType: 4329 HandleNeonVectorTypeAttr(type, attr, state.getSema(), 4330 VectorType::NeonPolyVector, 4331 "neon_polyvector_type"); 4332 attr.setUsedAsTypeAttr(); 4333 break; 4334 case AttributeList::AT_OpenCLImageAccess: 4335 HandleOpenCLImageAccessAttribute(type, attr, state.getSema()); 4336 attr.setUsedAsTypeAttr(); 4337 break; 4338 4339 case AttributeList::AT_NSReturnsRetained: 4340 if (!state.getSema().getLangOpts().ObjCAutoRefCount) 4341 break; 4342 // fallthrough into the function attrs 4343 4344 FUNCTION_TYPE_ATTRS_CASELIST: 4345 attr.setUsedAsTypeAttr(); 4346 4347 // Never process function type attributes as part of the 4348 // declaration-specifiers. 4349 if (TAL == TAL_DeclSpec) 4350 distributeFunctionTypeAttrFromDeclSpec(state, attr, type); 4351 4352 // Otherwise, handle the possible delays. 4353 else if (!handleFunctionTypeAttr(state, attr, type)) 4354 distributeFunctionTypeAttr(state, attr, type); 4355 break; 4356 } 4357 } while ((attrs = next)); 4358} 4359 4360/// \brief Ensure that the type of the given expression is complete. 4361/// 4362/// This routine checks whether the expression \p E has a complete type. If the 4363/// expression refers to an instantiable construct, that instantiation is 4364/// performed as needed to complete its type. Furthermore 4365/// Sema::RequireCompleteType is called for the expression's type (or in the 4366/// case of a reference type, the referred-to type). 4367/// 4368/// \param E The expression whose type is required to be complete. 4369/// \param Diagnoser The object that will emit a diagnostic if the type is 4370/// incomplete. 4371/// 4372/// \returns \c true if the type of \p E is incomplete and diagnosed, \c false 4373/// otherwise. 4374bool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser){ 4375 QualType T = E->getType(); 4376 4377 // Fast path the case where the type is already complete. 4378 if (!T->isIncompleteType()) 4379 return false; 4380 4381 // Incomplete array types may be completed by the initializer attached to 4382 // their definitions. For static data members of class templates we need to 4383 // instantiate the definition to get this initializer and complete the type. 4384 if (T->isIncompleteArrayType()) { 4385 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4386 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 4387 if (Var->isStaticDataMember() && 4388 Var->getInstantiatedFromStaticDataMember()) { 4389 4390 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo(); 4391 assert(MSInfo && "Missing member specialization information?"); 4392 if (MSInfo->getTemplateSpecializationKind() 4393 != TSK_ExplicitSpecialization) { 4394 // If we don't already have a point of instantiation, this is it. 4395 if (MSInfo->getPointOfInstantiation().isInvalid()) { 4396 MSInfo->setPointOfInstantiation(E->getLocStart()); 4397 4398 // This is a modification of an existing AST node. Notify 4399 // listeners. 4400 if (ASTMutationListener *L = getASTMutationListener()) 4401 L->StaticDataMemberInstantiated(Var); 4402 } 4403 4404 InstantiateStaticDataMemberDefinition(E->getExprLoc(), Var); 4405 4406 // Update the type to the newly instantiated definition's type both 4407 // here and within the expression. 4408 if (VarDecl *Def = Var->getDefinition()) { 4409 DRE->setDecl(Def); 4410 T = Def->getType(); 4411 DRE->setType(T); 4412 E->setType(T); 4413 } 4414 } 4415 4416 // We still go on to try to complete the type independently, as it 4417 // may also require instantiations or diagnostics if it remains 4418 // incomplete. 4419 } 4420 } 4421 } 4422 } 4423 4424 // FIXME: Are there other cases which require instantiating something other 4425 // than the type to complete the type of an expression? 4426 4427 // Look through reference types and complete the referred type. 4428 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) 4429 T = Ref->getPointeeType(); 4430 4431 return RequireCompleteType(E->getExprLoc(), T, Diagnoser); 4432} 4433 4434namespace { 4435 struct TypeDiagnoserDiag : Sema::TypeDiagnoser { 4436 unsigned DiagID; 4437 4438 TypeDiagnoserDiag(unsigned DiagID) 4439 : Sema::TypeDiagnoser(DiagID == 0), DiagID(DiagID) {} 4440 4441 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 4442 if (Suppressed) return; 4443 S.Diag(Loc, DiagID) << T; 4444 } 4445 }; 4446} 4447 4448bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) { 4449 TypeDiagnoserDiag Diagnoser(DiagID); 4450 return RequireCompleteExprType(E, Diagnoser); 4451} 4452 4453/// @brief Ensure that the type T is a complete type. 4454/// 4455/// This routine checks whether the type @p T is complete in any 4456/// context where a complete type is required. If @p T is a complete 4457/// type, returns false. If @p T is a class template specialization, 4458/// this routine then attempts to perform class template 4459/// instantiation. If instantiation fails, or if @p T is incomplete 4460/// and cannot be completed, issues the diagnostic @p diag (giving it 4461/// the type @p T) and returns true. 4462/// 4463/// @param Loc The location in the source that the incomplete type 4464/// diagnostic should refer to. 4465/// 4466/// @param T The type that this routine is examining for completeness. 4467/// 4468/// @returns @c true if @p T is incomplete and a diagnostic was emitted, 4469/// @c false otherwise. 4470bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, 4471 TypeDiagnoser &Diagnoser) { 4472 // FIXME: Add this assertion to make sure we always get instantiation points. 4473 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType"); 4474 // FIXME: Add this assertion to help us flush out problems with 4475 // checking for dependent types and type-dependent expressions. 4476 // 4477 // assert(!T->isDependentType() && 4478 // "Can't ask whether a dependent type is complete"); 4479 4480 // If we have a complete type, we're done. 4481 NamedDecl *Def = 0; 4482 if (!T->isIncompleteType(&Def)) { 4483 // If we know about the definition but it is not visible, complain. 4484 if (!Diagnoser.Suppressed && Def && !LookupResult::isVisible(Def)) { 4485 // Suppress this error outside of a SFINAE context if we've already 4486 // emitted the error once for this type. There's no usefulness in 4487 // repeating the diagnostic. 4488 // FIXME: Add a Fix-It that imports the corresponding module or includes 4489 // the header. 4490 Module *Owner = Def->getOwningModule(); 4491 Diag(Loc, diag::err_module_private_definition) 4492 << T << Owner->getFullModuleName(); 4493 Diag(Def->getLocation(), diag::note_previous_definition); 4494 4495 if (!isSFINAEContext()) { 4496 // Recover by implicitly importing this module. 4497 createImplicitModuleImport(Loc, Owner); 4498 } 4499 } 4500 4501 return false; 4502 } 4503 4504 const TagType *Tag = T->getAs<TagType>(); 4505 const ObjCInterfaceType *IFace = 0; 4506 4507 if (Tag) { 4508 // Avoid diagnosing invalid decls as incomplete. 4509 if (Tag->getDecl()->isInvalidDecl()) 4510 return true; 4511 4512 // Give the external AST source a chance to complete the type. 4513 if (Tag->getDecl()->hasExternalLexicalStorage()) { 4514 Context.getExternalSource()->CompleteType(Tag->getDecl()); 4515 if (!Tag->isIncompleteType()) 4516 return false; 4517 } 4518 } 4519 else if ((IFace = T->getAs<ObjCInterfaceType>())) { 4520 // Avoid diagnosing invalid decls as incomplete. 4521 if (IFace->getDecl()->isInvalidDecl()) 4522 return true; 4523 4524 // Give the external AST source a chance to complete the type. 4525 if (IFace->getDecl()->hasExternalLexicalStorage()) { 4526 Context.getExternalSource()->CompleteType(IFace->getDecl()); 4527 if (!IFace->isIncompleteType()) 4528 return false; 4529 } 4530 } 4531 4532 // If we have a class template specialization or a class member of a 4533 // class template specialization, or an array with known size of such, 4534 // try to instantiate it. 4535 QualType MaybeTemplate = T; 4536 while (const ConstantArrayType *Array 4537 = Context.getAsConstantArrayType(MaybeTemplate)) 4538 MaybeTemplate = Array->getElementType(); 4539 if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) { 4540 if (ClassTemplateSpecializationDecl *ClassTemplateSpec 4541 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) { 4542 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) 4543 return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec, 4544 TSK_ImplicitInstantiation, 4545 /*Complain=*/!Diagnoser.Suppressed); 4546 } else if (CXXRecordDecl *Rec 4547 = dyn_cast<CXXRecordDecl>(Record->getDecl())) { 4548 CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass(); 4549 if (!Rec->isBeingDefined() && Pattern) { 4550 MemberSpecializationInfo *MSI = Rec->getMemberSpecializationInfo(); 4551 assert(MSI && "Missing member specialization information?"); 4552 // This record was instantiated from a class within a template. 4553 if (MSI->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 4554 return InstantiateClass(Loc, Rec, Pattern, 4555 getTemplateInstantiationArgs(Rec), 4556 TSK_ImplicitInstantiation, 4557 /*Complain=*/!Diagnoser.Suppressed); 4558 } 4559 } 4560 } 4561 4562 if (Diagnoser.Suppressed) 4563 return true; 4564 4565 // We have an incomplete type. Produce a diagnostic. 4566 Diagnoser.diagnose(*this, Loc, T); 4567 4568 // If the type was a forward declaration of a class/struct/union 4569 // type, produce a note. 4570 if (Tag && !Tag->getDecl()->isInvalidDecl()) 4571 Diag(Tag->getDecl()->getLocation(), 4572 Tag->isBeingDefined() ? diag::note_type_being_defined 4573 : diag::note_forward_declaration) 4574 << QualType(Tag, 0); 4575 4576 // If the Objective-C class was a forward declaration, produce a note. 4577 if (IFace && !IFace->getDecl()->isInvalidDecl()) 4578 Diag(IFace->getDecl()->getLocation(), diag::note_forward_class); 4579 4580 return true; 4581} 4582 4583bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, 4584 unsigned DiagID) { 4585 TypeDiagnoserDiag Diagnoser(DiagID); 4586 return RequireCompleteType(Loc, T, Diagnoser); 4587} 4588 4589/// \brief Get diagnostic %select index for tag kind for 4590/// literal type diagnostic message. 4591/// WARNING: Indexes apply to particular diagnostics only! 4592/// 4593/// \returns diagnostic %select index. 4594static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) { 4595 switch (Tag) { 4596 case TTK_Struct: return 0; 4597 case TTK_Interface: return 1; 4598 case TTK_Class: return 2; 4599 default: llvm_unreachable("Invalid tag kind for literal type diagnostic!"); 4600 } 4601} 4602 4603/// @brief Ensure that the type T is a literal type. 4604/// 4605/// This routine checks whether the type @p T is a literal type. If @p T is an 4606/// incomplete type, an attempt is made to complete it. If @p T is a literal 4607/// type, or @p AllowIncompleteType is true and @p T is an incomplete type, 4608/// returns false. Otherwise, this routine issues the diagnostic @p PD (giving 4609/// it the type @p T), along with notes explaining why the type is not a 4610/// literal type, and returns true. 4611/// 4612/// @param Loc The location in the source that the non-literal type 4613/// diagnostic should refer to. 4614/// 4615/// @param T The type that this routine is examining for literalness. 4616/// 4617/// @param Diagnoser Emits a diagnostic if T is not a literal type. 4618/// 4619/// @returns @c true if @p T is not a literal type and a diagnostic was emitted, 4620/// @c false otherwise. 4621bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, 4622 TypeDiagnoser &Diagnoser) { 4623 assert(!T->isDependentType() && "type should not be dependent"); 4624 4625 QualType ElemType = Context.getBaseElementType(T); 4626 RequireCompleteType(Loc, ElemType, 0); 4627 4628 if (T->isLiteralType()) 4629 return false; 4630 4631 if (Diagnoser.Suppressed) 4632 return true; 4633 4634 Diagnoser.diagnose(*this, Loc, T); 4635 4636 if (T->isVariableArrayType()) 4637 return true; 4638 4639 const RecordType *RT = ElemType->getAs<RecordType>(); 4640 if (!RT) 4641 return true; 4642 4643 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 4644 4645 // A partially-defined class type can't be a literal type, because a literal 4646 // class type must have a trivial destructor (which can't be checked until 4647 // the class definition is complete). 4648 if (!RD->isCompleteDefinition()) { 4649 RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T); 4650 return true; 4651 } 4652 4653 // If the class has virtual base classes, then it's not an aggregate, and 4654 // cannot have any constexpr constructors or a trivial default constructor, 4655 // so is non-literal. This is better to diagnose than the resulting absence 4656 // of constexpr constructors. 4657 if (RD->getNumVBases()) { 4658 Diag(RD->getLocation(), diag::note_non_literal_virtual_base) 4659 << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 4660 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(), 4661 E = RD->vbases_end(); I != E; ++I) 4662 Diag(I->getLocStart(), 4663 diag::note_constexpr_virtual_base_here) << I->getSourceRange(); 4664 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() && 4665 !RD->hasTrivialDefaultConstructor()) { 4666 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD; 4667 } else if (RD->hasNonLiteralTypeFieldsOrBases()) { 4668 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 4669 E = RD->bases_end(); I != E; ++I) { 4670 if (!I->getType()->isLiteralType()) { 4671 Diag(I->getLocStart(), 4672 diag::note_non_literal_base_class) 4673 << RD << I->getType() << I->getSourceRange(); 4674 return true; 4675 } 4676 } 4677 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 4678 E = RD->field_end(); I != E; ++I) { 4679 if (!I->getType()->isLiteralType() || 4680 I->getType().isVolatileQualified()) { 4681 Diag(I->getLocation(), diag::note_non_literal_field) 4682 << RD << *I << I->getType() 4683 << I->getType().isVolatileQualified(); 4684 return true; 4685 } 4686 } 4687 } else if (!RD->hasTrivialDestructor()) { 4688 // All fields and bases are of literal types, so have trivial destructors. 4689 // If this class's destructor is non-trivial it must be user-declared. 4690 CXXDestructorDecl *Dtor = RD->getDestructor(); 4691 assert(Dtor && "class has literal fields and bases but no dtor?"); 4692 if (!Dtor) 4693 return true; 4694 4695 Diag(Dtor->getLocation(), Dtor->isUserProvided() ? 4696 diag::note_non_literal_user_provided_dtor : 4697 diag::note_non_literal_nontrivial_dtor) << RD; 4698 if (!Dtor->isUserProvided()) 4699 SpecialMemberIsTrivial(Dtor, CXXDestructor, /*Diagnose*/true); 4700 } 4701 4702 return true; 4703} 4704 4705bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) { 4706 TypeDiagnoserDiag Diagnoser(DiagID); 4707 return RequireLiteralType(Loc, T, Diagnoser); 4708} 4709 4710/// \brief Retrieve a version of the type 'T' that is elaborated by Keyword 4711/// and qualified by the nested-name-specifier contained in SS. 4712QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword, 4713 const CXXScopeSpec &SS, QualType T) { 4714 if (T.isNull()) 4715 return T; 4716 NestedNameSpecifier *NNS; 4717 if (SS.isValid()) 4718 NNS = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 4719 else { 4720 if (Keyword == ETK_None) 4721 return T; 4722 NNS = 0; 4723 } 4724 return Context.getElaboratedType(Keyword, NNS, T); 4725} 4726 4727QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) { 4728 ExprResult ER = CheckPlaceholderExpr(E); 4729 if (ER.isInvalid()) return QualType(); 4730 E = ER.take(); 4731 4732 if (!E->isTypeDependent()) { 4733 QualType T = E->getType(); 4734 if (const TagType *TT = T->getAs<TagType>()) 4735 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc()); 4736 } 4737 return Context.getTypeOfExprType(E); 4738} 4739 4740/// getDecltypeForExpr - Given an expr, will return the decltype for 4741/// that expression, according to the rules in C++11 4742/// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18. 4743static QualType getDecltypeForExpr(Sema &S, Expr *E) { 4744 if (E->isTypeDependent()) 4745 return S.Context.DependentTy; 4746 4747 // C++11 [dcl.type.simple]p4: 4748 // The type denoted by decltype(e) is defined as follows: 4749 // 4750 // - if e is an unparenthesized id-expression or an unparenthesized class 4751 // member access (5.2.5), decltype(e) is the type of the entity named 4752 // by e. If there is no such entity, or if e names a set of overloaded 4753 // functions, the program is ill-formed; 4754 // 4755 // We apply the same rules for Objective-C ivar and property references. 4756 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 4757 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) 4758 return VD->getType(); 4759 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 4760 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 4761 return FD->getType(); 4762 } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) { 4763 return IR->getDecl()->getType(); 4764 } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) { 4765 if (PR->isExplicitProperty()) 4766 return PR->getExplicitProperty()->getType(); 4767 } 4768 4769 // C++11 [expr.lambda.prim]p18: 4770 // Every occurrence of decltype((x)) where x is a possibly 4771 // parenthesized id-expression that names an entity of automatic 4772 // storage duration is treated as if x were transformed into an 4773 // access to a corresponding data member of the closure type that 4774 // would have been declared if x were an odr-use of the denoted 4775 // entity. 4776 using namespace sema; 4777 if (S.getCurLambda()) { 4778 if (isa<ParenExpr>(E)) { 4779 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4780 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 4781 QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation()); 4782 if (!T.isNull()) 4783 return S.Context.getLValueReferenceType(T); 4784 } 4785 } 4786 } 4787 } 4788 4789 4790 // C++11 [dcl.type.simple]p4: 4791 // [...] 4792 QualType T = E->getType(); 4793 switch (E->getValueKind()) { 4794 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the 4795 // type of e; 4796 case VK_XValue: T = S.Context.getRValueReferenceType(T); break; 4797 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the 4798 // type of e; 4799 case VK_LValue: T = S.Context.getLValueReferenceType(T); break; 4800 // - otherwise, decltype(e) is the type of e. 4801 case VK_RValue: break; 4802 } 4803 4804 return T; 4805} 4806 4807QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc) { 4808 ExprResult ER = CheckPlaceholderExpr(E); 4809 if (ER.isInvalid()) return QualType(); 4810 E = ER.take(); 4811 4812 return Context.getDecltypeType(E, getDecltypeForExpr(*this, E)); 4813} 4814 4815QualType Sema::BuildUnaryTransformType(QualType BaseType, 4816 UnaryTransformType::UTTKind UKind, 4817 SourceLocation Loc) { 4818 switch (UKind) { 4819 case UnaryTransformType::EnumUnderlyingType: 4820 if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) { 4821 Diag(Loc, diag::err_only_enums_have_underlying_types); 4822 return QualType(); 4823 } else { 4824 QualType Underlying = BaseType; 4825 if (!BaseType->isDependentType()) { 4826 EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl(); 4827 assert(ED && "EnumType has no EnumDecl"); 4828 DiagnoseUseOfDecl(ED, Loc); 4829 Underlying = ED->getIntegerType(); 4830 } 4831 assert(!Underlying.isNull()); 4832 return Context.getUnaryTransformType(BaseType, Underlying, 4833 UnaryTransformType::EnumUnderlyingType); 4834 } 4835 } 4836 llvm_unreachable("unknown unary transform type"); 4837} 4838 4839QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) { 4840 if (!T->isDependentType()) { 4841 // FIXME: It isn't entirely clear whether incomplete atomic types 4842 // are allowed or not; for simplicity, ban them for the moment. 4843 if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0)) 4844 return QualType(); 4845 4846 int DisallowedKind = -1; 4847 if (T->isArrayType()) 4848 DisallowedKind = 1; 4849 else if (T->isFunctionType()) 4850 DisallowedKind = 2; 4851 else if (T->isReferenceType()) 4852 DisallowedKind = 3; 4853 else if (T->isAtomicType()) 4854 DisallowedKind = 4; 4855 else if (T.hasQualifiers()) 4856 DisallowedKind = 5; 4857 else if (!T.isTriviallyCopyableType(Context)) 4858 // Some other non-trivially-copyable type (probably a C++ class) 4859 DisallowedKind = 6; 4860 4861 if (DisallowedKind != -1) { 4862 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T; 4863 return QualType(); 4864 } 4865 4866 // FIXME: Do we need any handling for ARC here? 4867 } 4868 4869 // Build the pointer type. 4870 return Context.getAtomicType(T); 4871} 4872