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